lab7: PKI, mTLS infra, OpenBao non-dev, hardening, lifecycle scripts
This commit is contained in:
+155
-56
@@ -1,11 +1,13 @@
|
||||
"""Shared lab6 helpers: Prometheus/Loki/Tempo/Grafana client, controlled app
|
||||
environment, SQL table lock, batch drain. Python 3.9+, standard library only."""
|
||||
"""Shared lab6 helpers (updated for lab7 HTTPS/mTLS + Basic Auth + network
|
||||
isolation): Prometheus/Loki/Tempo/Grafana client, controlled app environment,
|
||||
SQL table lock, batch drain. Python 3.9+, standard library only."""
|
||||
import base64
|
||||
import binascii
|
||||
import contextlib
|
||||
import json
|
||||
import os
|
||||
import select
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
@@ -59,25 +61,93 @@ SDK_DEFAULTS = {
|
||||
'LOG_LEVEL': 'INFO',
|
||||
}
|
||||
|
||||
_DEFAULT_CA_FILE = None
|
||||
_PROM_PREFIX = None
|
||||
|
||||
|
||||
def utc_now():
|
||||
return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
|
||||
|
||||
|
||||
def _operator_dir():
|
||||
env_dir = os.environ.get('LAB7_OPERATOR_DIR')
|
||||
if env_dir:
|
||||
return Path(env_dir)
|
||||
xdg = os.environ.get('XDG_STATE_HOME')
|
||||
base = Path(xdg) if xdg else (Path.home() / '.local/state')
|
||||
return base / 'mtusi-lab7-operator'
|
||||
|
||||
|
||||
def _default_ca_path(ca_file=None):
|
||||
for candidate in (ca_file, _DEFAULT_CA_FILE, os.environ.get('CA_FILE'),
|
||||
str(ROOT / 'secrets/pki/ca.crt')):
|
||||
if candidate and Path(candidate).is_file():
|
||||
return str(candidate)
|
||||
return None
|
||||
|
||||
|
||||
def _is_prometheus_url(url):
|
||||
if _PROM_PREFIX and url.startswith(_PROM_PREFIX):
|
||||
return True
|
||||
parsed = urllib.parse.urlparse(url)
|
||||
return parsed.port == 9090 or parsed.path.startswith('/api/v1/query') or \
|
||||
parsed.path.startswith('/api/v1/series') or \
|
||||
parsed.path.startswith('/api/v1/metadata') or \
|
||||
parsed.path.startswith('/api/v1/label/') or \
|
||||
parsed.path.startswith('/api/v1/rules') or \
|
||||
parsed.path == '/-/ready'
|
||||
|
||||
|
||||
def _prom_basic_auth_header():
|
||||
pw_path = ROOT / 'secrets/infra/prometheus_operator_password'
|
||||
if not pw_path.is_file():
|
||||
return None
|
||||
token = base64.b64encode(b'operator:' + pw_path.read_bytes().strip()).decode()
|
||||
return {'Authorization': 'Basic ' + token}
|
||||
|
||||
|
||||
def _ssl_context_for(url, ca_file=None, use_client_cert=False):
|
||||
if not url.startswith('https://'):
|
||||
return None
|
||||
ca_path = _default_ca_path(ca_file)
|
||||
ctx = ssl.create_default_context(cafile=ca_path)
|
||||
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
if use_client_cert:
|
||||
op_dir = _operator_dir() / 'operator'
|
||||
cert = op_dir / 'operator.crt'
|
||||
key = op_dir / 'operator.key'
|
||||
if cert.is_file() and key.is_file():
|
||||
ctx.load_cert_chain(certfile=str(cert), keyfile=str(key))
|
||||
return ctx
|
||||
|
||||
|
||||
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, *args, **kwargs):
|
||||
return None
|
||||
|
||||
|
||||
_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}),
|
||||
_NoRedirect())
|
||||
def _opener_for(url, ca_file=None, use_client_cert=False):
|
||||
handlers = [urllib.request.ProxyHandler({}), _NoRedirect()]
|
||||
ctx = _ssl_context_for(url, ca_file=ca_file, use_client_cert=use_client_cert)
|
||||
if ctx is not None:
|
||||
handlers.append(urllib.request.HTTPSHandler(context=ctx))
|
||||
return urllib.request.build_opener(*handlers)
|
||||
|
||||
|
||||
def http_get(url, headers=None, timeout=HTTP_TIMEOUT):
|
||||
def http_get(url, headers=None, timeout=HTTP_TIMEOUT, ca_file=None,
|
||||
use_client_cert=None):
|
||||
"""GET returning (status, bytes); never prints the URL query/headers."""
|
||||
request = urllib.request.Request(url, headers=headers or {})
|
||||
is_prom = _is_prometheus_url(url)
|
||||
need_mtls = is_prom if use_client_cert is None else bool(use_client_cert)
|
||||
req_headers = dict(headers or {})
|
||||
if is_prom and 'Authorization' not in req_headers:
|
||||
prom_auth = _prom_basic_auth_header()
|
||||
if prom_auth:
|
||||
req_headers.update(prom_auth)
|
||||
request = urllib.request.Request(url, headers=req_headers)
|
||||
opener = _opener_for(url, ca_file=ca_file, use_client_cert=need_mtls)
|
||||
try:
|
||||
with _OPENER.open(request, timeout=timeout) as response:
|
||||
with opener.open(request, timeout=timeout) as response:
|
||||
return response.status, response.read()
|
||||
except urllib.error.HTTPError as error:
|
||||
with error:
|
||||
@@ -87,8 +157,10 @@ def http_get(url, headers=None, timeout=HTTP_TIMEOUT):
|
||||
type(exc).__name__ + ')') from None
|
||||
|
||||
|
||||
def http_json(url, headers=None, timeout=HTTP_TIMEOUT, allow=(200,)):
|
||||
status, data = http_get(url, headers, timeout)
|
||||
def http_json(url, headers=None, timeout=HTTP_TIMEOUT, allow=(200,),
|
||||
ca_file=None, use_client_cert=None):
|
||||
status, data = http_get(url, headers, timeout, ca_file=ca_file,
|
||||
use_client_cert=use_client_cert)
|
||||
if status not in allow:
|
||||
raise Failure('GET ' + url.split('?')[0] + ': status ' + str(status))
|
||||
try:
|
||||
@@ -196,25 +268,34 @@ def normalize_trace(document):
|
||||
class ObsClient:
|
||||
def __init__(self, prometheus_url, grafana_url, password_file=None,
|
||||
base_url=None, ca_file=None):
|
||||
global _DEFAULT_CA_FILE, _PROM_PREFIX
|
||||
self.prometheus = prometheus_url.rstrip('/')
|
||||
self.grafana = grafana_url.rstrip('/')
|
||||
self.base_url = base_url
|
||||
self.ca_file = ca_file
|
||||
path = Path(password_file) if password_file else (
|
||||
ROOT / 'secrets/grafana_admin_password')
|
||||
if ca_file:
|
||||
_DEFAULT_CA_FILE = ca_file
|
||||
_PROM_PREFIX = self.prometheus
|
||||
candidates = [Path(password_file)] if password_file else [
|
||||
ROOT / 'secrets/infra/grafana_admin_password',
|
||||
ROOT / 'secrets/grafana_admin_password',
|
||||
]
|
||||
self._auth = None
|
||||
if path.exists():
|
||||
token = base64.b64encode(
|
||||
b'admin:' + path.read_bytes().strip()).decode()
|
||||
self._auth = {'Authorization': 'Basic ' + token}
|
||||
for path in candidates:
|
||||
if path.exists():
|
||||
token = base64.b64encode(
|
||||
b'admin:' + path.read_bytes().strip()).decode()
|
||||
self._auth = {'Authorization': 'Basic ' + token}
|
||||
break
|
||||
|
||||
# -- Prometheus
|
||||
# -- Prometheus (HTTPS + mTLS operator cert + Basic Auth)
|
||||
def prom_query(self, expr, at=None):
|
||||
params = {'query': expr}
|
||||
if at is not None:
|
||||
params['time'] = str(at)
|
||||
_, body = http_json(self.prometheus + '/api/v1/query?' +
|
||||
urllib.parse.urlencode(params))
|
||||
urllib.parse.urlencode(params),
|
||||
ca_file=self.ca_file, use_client_cert=True)
|
||||
if not isinstance(body, dict) or body.get('status') != 'success':
|
||||
raise Failure('Prometheus query failed')
|
||||
return body['data']['result']
|
||||
@@ -229,20 +310,23 @@ class ObsClient:
|
||||
params = {'query': expr, 'start': str(start), 'end': str(end),
|
||||
'step': str(step)}
|
||||
_, body = http_json(self.prometheus + '/api/v1/query_range?' +
|
||||
urllib.parse.urlencode(params))
|
||||
urllib.parse.urlencode(params),
|
||||
ca_file=self.ca_file, use_client_cert=True)
|
||||
if not isinstance(body, dict) or body.get('status') != 'success':
|
||||
raise Failure('Prometheus range query failed')
|
||||
return body['data']['result']
|
||||
|
||||
def prom_names(self):
|
||||
_, body = http_json(self.prometheus + '/api/v1/label/__name__/values')
|
||||
_, body = http_json(self.prometheus + '/api/v1/label/__name__/values',
|
||||
ca_file=self.ca_file, use_client_cert=True)
|
||||
return sorted(body['data'])
|
||||
|
||||
# -- Grafana proxied backends
|
||||
# -- Grafana proxied backends (HTTPS + Basic Auth; Grafana->DS uses mTLS)
|
||||
def _grafana_get(self, path, allow=(200,)):
|
||||
if self._auth is None:
|
||||
raise Failure('Grafana password file is missing')
|
||||
return http_get(self.grafana + path, self._auth)
|
||||
return http_get(self.grafana + path, self._auth,
|
||||
ca_file=self.ca_file, use_client_cert=False)
|
||||
|
||||
def grafana_json(self, path, allow=(200,)):
|
||||
status, data = self._grafana_get(path)
|
||||
@@ -305,7 +389,8 @@ class ObsClient:
|
||||
raise Failure('Grafana password file is missing')
|
||||
status, data = http_get(
|
||||
self.grafana + path,
|
||||
{**self._auth, 'Accept': 'application/json'})
|
||||
{**self._auth, 'Accept': 'application/json'},
|
||||
ca_file=self.ca_file, use_client_cert=False)
|
||||
if status == 200:
|
||||
try:
|
||||
return normalize_trace(json.loads(data))
|
||||
@@ -317,14 +402,22 @@ class ObsClient:
|
||||
return None
|
||||
time.sleep(1)
|
||||
|
||||
# -- closed backends from inside the compose network
|
||||
# -- closed backends from inside the compose network (HTTPS + CA verified)
|
||||
def internal_get(self, service, port, path):
|
||||
script = (
|
||||
"const fs=require('node:fs'),https=require('node:https');"
|
||||
"const [h,p,u]=process.argv.slice(1);"
|
||||
"fetch('http://'+h+':'+p+u,{signal:AbortSignal.timeout(5000)})"
|
||||
".then(async r=>{const b=await r.text();"
|
||||
"console.log(JSON.stringify({status:r.status,body:b.slice(0,1048576)}))})"
|
||||
".catch(e=>{console.log(JSON.stringify({status:0,body:String(e.name)}))})")
|
||||
"const req=https.request({host:h,port:Number(p),path:u,method:'GET',"
|
||||
"ca:fs.readFileSync('/run/certs/ca.crt'),servername:h,"
|
||||
"rejectUnauthorized:true,timeout:5000},res=>{"
|
||||
"let b='';res.setEncoding('utf8');"
|
||||
"res.on('data',c=>{if(b.length<1048576)b+=c});"
|
||||
"res.on('end',()=>console.log(JSON.stringify({status:res.statusCode,body:b})));"
|
||||
"});"
|
||||
"req.on('timeout',()=>req.destroy(new Error('Timeout')));"
|
||||
"req.on('error',e=>console.log(JSON.stringify({status:0,body:String(e.code||e.message)})));"
|
||||
"req.end();"
|
||||
)
|
||||
result = stand.compose('exec', '-T', 'api', 'node', '-e', script,
|
||||
service, str(port), path, check_result=False)
|
||||
try:
|
||||
@@ -342,26 +435,40 @@ class ObsClient:
|
||||
problems = []
|
||||
if self.base_url:
|
||||
try:
|
||||
status, _ = http_get(self.base_url.rstrip('/') + '/health/ready')
|
||||
status, _ = http_get(self.base_url.rstrip('/') + '/health/ready',
|
||||
ca_file=self.ca_file, use_client_cert=False)
|
||||
self._check(problems, 'api-ready', status == 200)
|
||||
except Failure:
|
||||
problems.append('api-ready')
|
||||
probes = (('otel-collector', 13133, '/', 'collector-health'),
|
||||
('loki', 3100, '/ready', 'loki-ready'),
|
||||
('tempo', 3200, '/ready', 'tempo-ready'))
|
||||
for service, port, path, name in probes:
|
||||
try:
|
||||
status, _ = self.internal_get(service, port, path)
|
||||
self._check(problems, name, status == 200)
|
||||
except Failure:
|
||||
problems.append(name)
|
||||
# Collector health over HTTPS from api (same app_data network).
|
||||
try:
|
||||
status, _ = http_get(self.prometheus + '/-/ready')
|
||||
status, _ = self.internal_get('otel-collector', 13133, '/')
|
||||
self._check(problems, 'collector-health', status == 200)
|
||||
except Failure:
|
||||
problems.append('collector-health')
|
||||
# Loki and Tempo live on isolated obs_net; verify via Grafana's mTLS proxy.
|
||||
try:
|
||||
body = self.grafana_json('/api/datasources/uid/loki/health',
|
||||
allow=(200, 400, 404, 500))
|
||||
self._check(problems, 'loki-ready',
|
||||
isinstance(body, dict) and
|
||||
body.get('status', '').upper() == 'OK')
|
||||
except Failure:
|
||||
problems.append('loki-ready')
|
||||
try:
|
||||
status, _ = self._grafana_get('/api/datasources/proxy/uid/tempo/api/echo')
|
||||
self._check(problems, 'tempo-ready', status == 200)
|
||||
except Failure:
|
||||
problems.append('tempo-ready')
|
||||
try:
|
||||
status, _ = http_get(self.prometheus + '/-/ready',
|
||||
ca_file=self.ca_file, use_client_cert=True)
|
||||
self._check(problems, 'prometheus-ready', status == 200)
|
||||
except Failure:
|
||||
problems.append('prometheus-ready')
|
||||
try:
|
||||
status, _ = http_get(self.grafana + '/api/health')
|
||||
status, _ = http_get(self.grafana + '/api/health',
|
||||
ca_file=self.ca_file, use_client_cert=False)
|
||||
self._check(problems, 'grafana-health', status == 200)
|
||||
except Failure:
|
||||
problems.append('grafana-health')
|
||||
@@ -388,8 +495,6 @@ class ObsClient:
|
||||
try:
|
||||
for uid in DATASOURCE_UIDS:
|
||||
if uid == 'tempo':
|
||||
# The Tempo plugin has no health resource; its API echo
|
||||
# through the datasource proxy proves the connection.
|
||||
status, _ = self._grafana_get(
|
||||
'/api/datasources/proxy/uid/tempo/api/echo')
|
||||
self._check(problems, 'datasource:tempo', status == 200)
|
||||
@@ -400,7 +505,8 @@ class ObsClient:
|
||||
self._check(problems, 'datasource:' + uid,
|
||||
isinstance(body, dict) and
|
||||
body.get('status', '').upper() == 'OK')
|
||||
_, rules = http_json(self.prometheus + '/api/v1/rules')
|
||||
_, rules = http_json(self.prometheus + '/api/v1/rules',
|
||||
ca_file=self.ca_file, use_client_cert=True)
|
||||
names = {r['name'] for g in rules['data']['groups']
|
||||
for r in g['rules']}
|
||||
for alert in RULE_ALERTS:
|
||||
@@ -518,8 +624,6 @@ class ObsClient:
|
||||
yield set_overrides
|
||||
finally:
|
||||
if dirty[0]:
|
||||
# Restore the original effective values as controller env so the
|
||||
# recreated containers match what was running before.
|
||||
for key in MUTABLE_KEYS:
|
||||
original = baseline.get(('api', key))
|
||||
if original is not None and key in touched:
|
||||
@@ -542,10 +646,9 @@ class ObsClient:
|
||||
self.wait_ready(app_telemetry=True, provisioning=True,
|
||||
timeout=120)
|
||||
|
||||
# -- foreign faults
|
||||
# -- foreign faults (Redis over mTLS + redis_admin ACL)
|
||||
def foreign_faults(self):
|
||||
result = stand.compose('exec', '-T', 'redis', 'redis-cli', '--scan',
|
||||
'--pattern', 'fault:*')
|
||||
result = stand.redis_admin('--scan', '--pattern', 'fault:*')
|
||||
return sorted(line for line in result.stdout.split() if line)
|
||||
|
||||
def require_no_foreign_faults(self):
|
||||
@@ -558,8 +661,8 @@ class ObsClient:
|
||||
# --------------------------------------------------------------- PostgreSQL
|
||||
|
||||
def psql(sql, timeout=30):
|
||||
script = 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -v ON_ERROR_STOP=1 ' \
|
||||
'-At -F , -c "$SQL"'
|
||||
script = 'psql -h /var/run/postgresql -U postgres -d "${POSTGRES_DB:-messenger}" ' \
|
||||
'-v ON_ERROR_STOP=1 -At -F , -c "$SQL"'
|
||||
result = subprocess.run(
|
||||
['docker', 'compose', '--env-file', stand.ENV_FILE, 'exec', '-T',
|
||||
'-e', 'SQL=' + sql, 'postgres', 'sh', '-c', script],
|
||||
@@ -579,7 +682,8 @@ def hold_table_lock(table):
|
||||
process = subprocess.Popen(
|
||||
['docker', 'compose', '--env-file', stand.ENV_FILE, 'exec', '-T',
|
||||
'postgres', 'sh', '-c',
|
||||
'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -v ON_ERROR_STOP=1 -At'],
|
||||
'psql -h /var/run/postgresql -U postgres -d "${POSTGRES_DB:-messenger}" '
|
||||
'-v ON_ERROR_STOP=1 -At'],
|
||||
cwd=ROOT, text=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, bufsize=1)
|
||||
pid = None
|
||||
@@ -630,12 +734,7 @@ def hold_table_lock(table):
|
||||
|
||||
|
||||
def wait_drained(attachment_ids, obs=None, timeout=120, flush_telemetry=True):
|
||||
"""Batch-check jobs/outbox/attachments in PostgreSQL (no HTTP polling).
|
||||
|
||||
Returns {'drained': bool, 'states': {id: status}, 'queued': n,
|
||||
'outbox': n, 'seconds': t, 'timestamps': ...}. A vanished known ID is a
|
||||
Failure; non-ready at the deadline is reported, not raised.
|
||||
"""
|
||||
"""Batch-check jobs/outbox/attachments in PostgreSQL (no HTTP polling)."""
|
||||
ids = list(attachment_ids)
|
||||
for item in ids:
|
||||
uuid.UUID(item)
|
||||
|
||||
Reference in New Issue
Block a user