forked from mtusi2026/mtusi2026lab7
lab7: безопасность, mTLS, OpenBao и PKI lifecycle
This commit is contained in:
@@ -11,7 +11,7 @@ mkdir -p "$OUT"
|
||||
{
|
||||
echo "# Cache consistency evidence (track 1)"
|
||||
echo "# generated: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
echo "# redis: ${TEST_REDIS_HOST:-localhost}:${TEST_REDIS_PORT:-6379} db=${TEST_REDIS_DB:-1}"
|
||||
echo "# redis: ${TEST_REDIS_HOST:-localhost}:${TEST_REDIS_PORT:-6379} db=${TEST_REDIS_DB:-7} (operator TLS)"
|
||||
echo
|
||||
"$GO" test -tags=integration -count=1 -v -timeout=5m \
|
||||
-run 'TestChatRepositorySuite|TestSessionRepositorySuite' \
|
||||
|
||||
@@ -12,12 +12,6 @@ PATTERNS = {
|
||||
'private key': re.compile(r'BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY'),
|
||||
'bearer token': re.compile(r'Bearer\s+[A-Za-z0-9._-]{20,}'),
|
||||
}
|
||||
ALLOW = {
|
||||
'PASSWORD=messenger',
|
||||
'PASSWORD=messenger',
|
||||
'password: messenger',
|
||||
'POSTGRES_PASSWORD: messenger',
|
||||
}
|
||||
|
||||
def main():
|
||||
failures = []
|
||||
@@ -31,8 +25,6 @@ def main():
|
||||
for name, pattern in PATTERNS.items():
|
||||
for match in pattern.finditer(text):
|
||||
line = text[text.rfind('\n', 0, match.start()) + 1:text.find('\n', match.end())].strip()
|
||||
if any(allowed in line for allowed in ALLOW):
|
||||
continue
|
||||
failures.append(f'{path.relative_to(ROOT)}: {name}: {line[:160]}')
|
||||
if failures:
|
||||
print('FAIL: evidence scanner found possible secrets/signatures')
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fail when the SeaweedFS identities and the API environment disagree.
|
||||
|
||||
The stand keeps synthetic credentials in two places on purpose: the identities
|
||||
file is mounted into SeaweedFS, while the API receives the same values through
|
||||
the environment. This check keeps the copies from drifting.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
IDENTITIES = ROOT / "infra/s3/s3.json"
|
||||
|
||||
|
||||
def parse_env(path: Path) -> dict[str, str]:
|
||||
values: dict[str, str] = {}
|
||||
for raw in path.read_text().splitlines():
|
||||
line = raw.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
key, value = line.split("=", 1)
|
||||
values[key.strip()] = value.strip().strip('"').strip("'")
|
||||
return values
|
||||
|
||||
|
||||
def main() -> int:
|
||||
identities = json.loads(IDENTITIES.read_text())
|
||||
by_name = {item["name"]: item for item in identities.get("identities", [])}
|
||||
|
||||
source = ROOT / ".env"
|
||||
if not source.is_file():
|
||||
source = ROOT / ".env.example"
|
||||
env = parse_env(source)
|
||||
|
||||
expected = {
|
||||
"app": ("S3_ACCESS_KEY_ID", "S3_SECRET_ACCESS_KEY"),
|
||||
}
|
||||
|
||||
failures: list[str] = []
|
||||
for name, (key_var, secret_var) in expected.items():
|
||||
identity = by_name.get(name)
|
||||
if identity is None:
|
||||
failures.append(f"{IDENTITIES}: identity {name!r} is missing")
|
||||
continue
|
||||
credentials = identity.get("credentials") or []
|
||||
if not credentials:
|
||||
failures.append(f"{IDENTITIES}: identity {name!r} has no credentials")
|
||||
continue
|
||||
access_key = credentials[0].get("accessKey")
|
||||
secret_key = credentials[0].get("secretKey")
|
||||
if env.get(key_var) != access_key:
|
||||
failures.append(f"{source.name}: {key_var} does not match identity {name!r}")
|
||||
if env.get(secret_var) != secret_key:
|
||||
failures.append(f"{source.name}: {secret_var} does not match identity {name!r}")
|
||||
|
||||
if failures:
|
||||
print("FAIL: S3 credentials are inconsistent")
|
||||
for failure in failures:
|
||||
print(" -", failure)
|
||||
return 1
|
||||
|
||||
if "admin" not in by_name:
|
||||
print("FAIL: infra/s3/s3.json has no admin identity for s3-init")
|
||||
return 1
|
||||
|
||||
print(f"PASS: S3 app identity matches {source.name}; admin stays in s3.json/s3-init")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,8 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
mkdir -p "$ROOT_DIR/secrets"
|
||||
if [ ! -s "$ROOT_DIR/secrets/grafana.env" ]; then
|
||||
(umask 077; printf 'GF_SECURITY_ADMIN_PASSWORD=%s\n' "$(openssl rand -hex 16)" > "$ROOT_DIR/secrets/grafana.env")
|
||||
echo "created secrets/grafana.env"
|
||||
fi
|
||||
@@ -5,7 +5,7 @@ Run against a live stand. Writes raw CSV samples and a summary under
|
||||
evidence/lab4/memory/. The primary metric is cgroup anon memory: memory.current
|
||||
also includes page cache from the temporary spool files.
|
||||
|
||||
python3 scripts/lab4_memory_experiment.py --base-url http://localhost:8080
|
||||
python3 scripts/lab4_memory_experiment.py --base-url https://localhost:8443
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -22,8 +22,11 @@ from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
sys.path.insert(0, str(ROOT / 'student-tests'))
|
||||
|
||||
from client import Client # noqa: E402
|
||||
from lab7_http import BASE_URL, CA_FILE # noqa: E402
|
||||
from tests_helpers import compose # noqa: E402
|
||||
|
||||
OUTPUT = ROOT / 'evidence/lab4/memory'
|
||||
|
||||
@@ -44,7 +47,7 @@ def png_of_size(width: int, height: int, seed: int) -> bytes:
|
||||
|
||||
|
||||
def containers(service: str) -> list[str]:
|
||||
output = os.popen(f'docker compose ps -q {service}').read().split()
|
||||
output = compose('ps', '-q', service).stdout.split()
|
||||
if not output:
|
||||
raise SystemExit(f'no running containers for service {service}')
|
||||
return output
|
||||
@@ -69,7 +72,8 @@ def memory_snapshot() -> dict[str, int]:
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--base-url', default='http://localhost:8080')
|
||||
parser.add_argument('--base-url', default=BASE_URL)
|
||||
parser.add_argument('--ca-file', default=CA_FILE)
|
||||
parser.add_argument('--concurrency', type=int, default=10)
|
||||
parser.add_argument('--width', type=int, default=2100)
|
||||
parser.add_argument('--height', type=int, default=1500)
|
||||
@@ -80,7 +84,7 @@ def main() -> None:
|
||||
if len(content) > 10 * 1024 * 1024:
|
||||
raise SystemExit(f'generated PNG is {len(content)} bytes, above the 10 MiB contract limit')
|
||||
|
||||
client = Client(args.base_url, timeout=120)
|
||||
client = Client(args.base_url, args.ca_file or CA_FILE, timeout=120)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
|
||||
OUTPUT.mkdir(parents=True, exist_ok=True)
|
||||
@@ -101,7 +105,7 @@ def main() -> None:
|
||||
def upload(_: int) -> None:
|
||||
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=memory.png'
|
||||
client.call(
|
||||
'POST', path, 201, actor=alice, raw=content,
|
||||
'POST', path, 202, actor=alice, raw=content,
|
||||
headers={'Content-Type': 'image/png'}, schema='Attachment',
|
||||
)
|
||||
|
||||
|
||||
+14
-8
@@ -4,7 +4,7 @@
|
||||
Measures client-facing LB traffic, API traffic, API anon memory and latency for
|
||||
two file sizes. Run against a live stand from the repository root.
|
||||
|
||||
python3 scripts/lab4_track1.py --base-url http://localhost:8080
|
||||
python3 scripts/lab4_track1.py --base-url https://localhost:8443
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -24,12 +24,14 @@ sys.path.insert(0, str(ROOT / 'student-tests'))
|
||||
from client import Client # noqa: E402
|
||||
from presign_flow import complete, presign, put # noqa: E402
|
||||
from lab4_memory_experiment import png_of_size # noqa: E402
|
||||
from lab7_http import BASE_URL, CA_FILE # noqa: E402
|
||||
from tests_helpers import compose # noqa: E402
|
||||
|
||||
OUTPUT = ROOT / 'evidence/lab4/track1'
|
||||
|
||||
|
||||
def containers(service: str) -> list[str]:
|
||||
ids = os.popen(f'docker compose ps -q {service}').read().split()
|
||||
ids = compose('ps', '-q', service).stdout.split()
|
||||
if not ids:
|
||||
raise SystemExit(f'no running containers for service {service}')
|
||||
return ids
|
||||
@@ -83,14 +85,14 @@ class Sampler:
|
||||
def proxy_upload(client: Client, actor: dict, chat: dict, content: bytes) -> None:
|
||||
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=track1.png'
|
||||
client.call(
|
||||
'POST', path, 201, actor=actor, raw=content,
|
||||
'POST', path, 202, actor=actor, raw=content,
|
||||
headers={'Content-Type': 'image/png'}, schema='Attachment',
|
||||
)
|
||||
|
||||
|
||||
def presign_upload(client: Client, actor: dict, chat: dict, content: bytes) -> None:
|
||||
def presign_upload(client: Client, actor: dict, chat: dict, content: bytes, ca_file=CA_FILE) -> None:
|
||||
prepared = presign(client, actor, chat, content)
|
||||
status = put(prepared['upload_url'], content)
|
||||
status = put(prepared['upload_url'], content, ca_file=ca_file)
|
||||
if status != 200:
|
||||
raise SystemExit(f'presigned PUT failed with {status}')
|
||||
complete(client, actor, prepared['attachment_id'], prepared['sha256'])
|
||||
@@ -98,11 +100,12 @@ def presign_upload(client: Client, actor: dict, chat: dict, content: bytes) -> N
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--base-url', default='http://localhost:8080')
|
||||
parser.add_argument('--base-url', default=BASE_URL)
|
||||
parser.add_argument('--ca-file', default=CA_FILE)
|
||||
parser.add_argument('--iterations', type=int, default=5)
|
||||
args = parser.parse_args()
|
||||
|
||||
client = Client(args.base_url, timeout=180)
|
||||
client = Client(args.base_url, args.ca_file or CA_FILE, timeout=180)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
|
||||
files = {
|
||||
@@ -121,7 +124,10 @@ def main() -> None:
|
||||
started = time.monotonic()
|
||||
|
||||
with Sampler() as sampler:
|
||||
operation(client, alice, chat, content)
|
||||
if flow == 'presign':
|
||||
operation(client, alice, chat, content, ca_file=args.ca_file or CA_FILE)
|
||||
else:
|
||||
operation(client, alice, chat, content)
|
||||
|
||||
latency = time.monotonic() - started
|
||||
lb_after, lb_tx_after = read_net('lb')
|
||||
|
||||
@@ -20,6 +20,7 @@ sys.path.insert(0, str(ROOT / 'student-tests'))
|
||||
|
||||
from client import Client, Failure, check # noqa: E402
|
||||
from tests_helpers import compose, jobctl, psql # noqa: E402
|
||||
from lab7_http import BASE_URL, CA_FILE # noqa: E402
|
||||
|
||||
FIXTURE = ROOT / 'tests/fixtures/sample.png'
|
||||
EVIDENCE = ROOT / 'evidence/lab5/track2'
|
||||
@@ -111,14 +112,15 @@ def scenario_stale_version(client, actor, chat):
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Lab5 track 2 correctness harness')
|
||||
parser.add_argument('--base-url', default='http://localhost:8080')
|
||||
parser.add_argument('--base-url', default=BASE_URL)
|
||||
parser.add_argument('--ca-file', default=CA_FILE)
|
||||
parser.add_argument('--reps', type=int, default=3)
|
||||
args = parser.parse_args()
|
||||
|
||||
EVIDENCE.mkdir(parents=True, exist_ok=True)
|
||||
rows = []
|
||||
|
||||
client = Client(args.base_url, None)
|
||||
client = Client(args.base_url, args.ca_file or CA_FILE)
|
||||
|
||||
for rep in range(1, args.reps + 1):
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
|
||||
@@ -9,23 +9,24 @@ import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
from lab7_http import open_url
|
||||
|
||||
|
||||
# The lab tools always target loopback; ignore ambient corporate proxies.
|
||||
for _proxy_key in ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy'):
|
||||
os.environ.pop(_proxy_key, None)
|
||||
os.environ['NO_PROXY'] = 'localhost,127.0.0.1,::1'
|
||||
os.environ['no_proxy'] = 'localhost,127.0.0.1,::1'
|
||||
urllib.request.getproxies = lambda: {}
|
||||
|
||||
|
||||
def get(url):
|
||||
with urllib.request.urlopen(url, timeout=5) as response:
|
||||
with open_url(url, timeout=5, operator=True) as response:
|
||||
return json.loads(response.read())
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Poll Prometheus alerts')
|
||||
parser.add_argument('--prometheus', default='http://localhost:9090')
|
||||
parser.add_argument('--prometheus', default='https://localhost:9090')
|
||||
parser.add_argument('--duration', type=float, default=600)
|
||||
parser.add_argument('--interval', type=float, default=5)
|
||||
parser.add_argument('--output', default='evidence/lab6/alerts.csv')
|
||||
|
||||
@@ -9,28 +9,29 @@ import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
from lab7_environment import Environment
|
||||
from lab7_http import BASE_URL, open_url
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
for key in ('HTTP_PROXY','HTTPS_PROXY','ALL_PROXY','http_proxy','https_proxy','all_proxy'):
|
||||
os.environ.pop(key, None)
|
||||
OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
|
||||
|
||||
def query(expr):
|
||||
url = 'http://localhost:9090/api/v1/query?' + urllib.parse.urlencode({'query': expr})
|
||||
with OPENER.open(url, timeout=10) as response:
|
||||
url = 'https://localhost:9090/api/v1/query?' + urllib.parse.urlencode({'query': expr})
|
||||
with open_url(url, timeout=10, operator=True) as response:
|
||||
result = json.loads(response.read()).get('data', {}).get('result', [])
|
||||
return result[0]['value'][1] if result else 'MISSING'
|
||||
|
||||
|
||||
def alerts():
|
||||
with OPENER.open('http://localhost:9090/api/v1/alerts', timeout=10) as response:
|
||||
with open_url('https://localhost:9090/api/v1/alerts', timeout=10, operator=True) as response:
|
||||
data = json.loads(response.read()).get('data', {}).get('alerts', [])
|
||||
return [(a['labels'].get('alertname', ''), a['state']) for a in data]
|
||||
|
||||
|
||||
def compose(*args, check=True):
|
||||
return subprocess.run(['docker','compose','--env-file','.env',*args], cwd=ROOT,
|
||||
capture_output=True, text=True, check=check)
|
||||
return Environment().compose(*args, check=check)
|
||||
|
||||
|
||||
def sample(label):
|
||||
@@ -54,7 +55,7 @@ def main():
|
||||
load_path.unlink(missing_ok=True)
|
||||
load_duration = args.duration + 300 + 60
|
||||
load = subprocess.Popen([
|
||||
'python3', str(ROOT/'scripts/lab6_load.py'), '--base-url', 'http://localhost:8080',
|
||||
'python3', str(ROOT/'scripts/lab6_load.py'), '--base-url', BASE_URL,
|
||||
'--rate', '0.2', '--duration', str(load_duration), '--upload-ratio', '0.2',
|
||||
'--deadline', '60', '--output', str(load_path),
|
||||
], cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
@@ -62,7 +63,7 @@ def main():
|
||||
print('$ docker compose ps -a', flush=True)
|
||||
print(compose('ps','-a').stdout, flush=True)
|
||||
print('$ docker compose stop otel-collector', flush=True)
|
||||
print(compose('stop','otel-collector').stdout.strip(), flush=True)
|
||||
print(compose('stop','collector-tls','otel-collector').stdout.strip(), flush=True)
|
||||
started = time.monotonic()
|
||||
while time.monotonic() - started < args.duration:
|
||||
time.sleep(30)
|
||||
@@ -70,7 +71,7 @@ def main():
|
||||
print('$ docker compose ps -a (down)', flush=True)
|
||||
print(compose('ps','-a').stdout, flush=True)
|
||||
print('$ docker compose start otel-collector', flush=True)
|
||||
print(compose('start','otel-collector').stdout.strip(), flush=True)
|
||||
print(compose('start','otel-collector','collector-tls').stdout.strip(), flush=True)
|
||||
started = time.monotonic()
|
||||
while time.monotonic() - started < 300:
|
||||
time.sleep(30)
|
||||
|
||||
@@ -27,6 +27,7 @@ urllib.request.getproxies = lambda: {}
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from lab7_http import BASE_URL, CA_FILE # noqa: E402
|
||||
|
||||
|
||||
def percentile(values, p):
|
||||
@@ -39,7 +40,8 @@ def percentile(values, p):
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Open-loop lab6 load')
|
||||
parser.add_argument('--base-url', default='http://localhost:8080')
|
||||
parser.add_argument('--base-url', default=BASE_URL)
|
||||
parser.add_argument('--ca-file', default=CA_FILE)
|
||||
parser.add_argument('--rate', type=float, default=1.0, help='arrivals per second')
|
||||
parser.add_argument('--duration', type=float, default=60.0, help='seconds')
|
||||
parser.add_argument('--upload-ratio', type=float, default=0.25)
|
||||
@@ -50,7 +52,7 @@ def main():
|
||||
args = parser.parse_args()
|
||||
|
||||
from client import Client, Failure
|
||||
bootstrap = Client(args.base_url, timeout=args.deadline)
|
||||
bootstrap = Client(args.base_url, args.ca_file or CA_FILE, timeout=args.deadline)
|
||||
alice, _, _, chat = bootstrap.bootstrap()
|
||||
|
||||
lock = threading.Lock()
|
||||
@@ -68,7 +70,7 @@ def main():
|
||||
registration = alice['registration']
|
||||
credential = base64.b64encode(
|
||||
(registration['username'] + ':' + registration['password']).encode()).decode()
|
||||
refresher = Client(args.base_url, timeout=args.deadline)
|
||||
refresher = Client(args.base_url, args.ca_file or CA_FILE, timeout=args.deadline)
|
||||
session = refresher.call(
|
||||
'POST', '/api/v1/auth/sessions', 201,
|
||||
headers={'Authorization': 'Basic ' + credential}, schema='Session')['json']
|
||||
@@ -107,7 +109,7 @@ def main():
|
||||
failures.append(detail)
|
||||
|
||||
def run_one(kind, index):
|
||||
client = Client(args.base_url, timeout=args.deadline)
|
||||
client = Client(args.base_url, args.ca_file or CA_FILE, timeout=args.deadline)
|
||||
started = time.monotonic()
|
||||
try:
|
||||
refresh_session()
|
||||
|
||||
@@ -9,35 +9,39 @@ import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
from lab7_environment import Environment
|
||||
from lab7_http import BASE_URL, open_url
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
for key in ('HTTP_PROXY','HTTPS_PROXY','ALL_PROXY','http_proxy','https_proxy','all_proxy'):
|
||||
os.environ.pop(key, None)
|
||||
OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
|
||||
|
||||
def prom(expr):
|
||||
url = 'http://localhost:9090/api/v1/query?' + urllib.parse.urlencode({'query': expr})
|
||||
with OPENER.open(url, timeout=10) as response:
|
||||
url = 'https://localhost:9090/api/v1/query?' + urllib.parse.urlencode({'query': expr})
|
||||
with open_url(url, timeout=10, operator=True) as response:
|
||||
result = json.loads(response.read()).get('data', {}).get('result', [])
|
||||
return result[0]['value'][1] if result else 'MISSING'
|
||||
|
||||
|
||||
def labels(expr, label):
|
||||
url = 'http://localhost:9090/api/v1/query?' + urllib.parse.urlencode({'query': expr})
|
||||
with OPENER.open(url, timeout=10) as response:
|
||||
url = 'https://localhost:9090/api/v1/query?' + urllib.parse.urlencode({'query': expr})
|
||||
with open_url(url, timeout=10, operator=True) as response:
|
||||
result = json.loads(response.read()).get('data', {}).get('result', [])
|
||||
return [r['metric'].get(label, '') for r in result]
|
||||
|
||||
|
||||
def compose(*args, check=True):
|
||||
return subprocess.run(['docker','compose','--env-file','.env',*args], cwd=ROOT,
|
||||
capture_output=True, text=True, check=check)
|
||||
return Environment().compose(*args, check=check)
|
||||
|
||||
|
||||
def cgroup_stats():
|
||||
output = subprocess.run(['docker','stats','--no-stream','--format','{{.Name}} {{.MemUsage}} {{.MemPerc}}',],
|
||||
ids = compose('ps', '-q', 'api', 'otel-collector').stdout.split()
|
||||
if not ids:
|
||||
return []
|
||||
output = subprocess.run(['docker','stats','--no-stream','--format','{{.Name}} {{.MemUsage}} {{.MemPerc}}', *ids],
|
||||
capture_output=True, text=True, check=True).stdout
|
||||
return [line.strip() for line in output.splitlines() if any(s in line for s in ('api-','collector'))]
|
||||
return output.splitlines()
|
||||
|
||||
|
||||
def sample(phase):
|
||||
@@ -71,7 +75,7 @@ def main():
|
||||
load_path.unlink(missing_ok=True)
|
||||
load_duration = args.baseline + args.duration + args.recovery + 120
|
||||
load = subprocess.Popen([
|
||||
'python3', str(ROOT/'scripts/lab6_load.py'), '--base-url', 'http://localhost:8080',
|
||||
'python3', str(ROOT/'scripts/lab6_load.py'), '--base-url', BASE_URL,
|
||||
'--rate', '0.2', '--duration', str(load_duration),
|
||||
'--upload-ratio', '0.2', '--deadline', '60',
|
||||
'--output', str(load_path),
|
||||
@@ -81,13 +85,13 @@ def main():
|
||||
for _ in range(args.baseline // 10):
|
||||
time.sleep(10)
|
||||
samples.append(sample('baseline'))
|
||||
compose('stop','loki','tempo')
|
||||
compose('stop','loki-tls','tempo-tls','loki','tempo')
|
||||
samples.append(sample('down-start'))
|
||||
started = time.monotonic()
|
||||
while time.monotonic() - started < args.duration:
|
||||
time.sleep(10)
|
||||
samples.append(sample('down'))
|
||||
compose('start','loki','tempo')
|
||||
compose('start','loki','tempo','loki-tls','tempo-tls')
|
||||
samples.append(sample('recovery-start'))
|
||||
started = time.monotonic()
|
||||
zero_streak = 0
|
||||
@@ -103,7 +107,7 @@ def main():
|
||||
else:
|
||||
zero_streak = 0
|
||||
finally:
|
||||
compose('start','loki','tempo')
|
||||
compose('start','loki','tempo','loki-tls','tempo-tls')
|
||||
try:
|
||||
load.wait(timeout=load_duration + 120)
|
||||
except subprocess.TimeoutExpired:
|
||||
|
||||
@@ -13,6 +13,9 @@ import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from lab7_environment import Environment
|
||||
from lab7_http import BASE_URL
|
||||
|
||||
# The lab tools always target loopback; ignore ambient corporate proxies.
|
||||
for _proxy_key in ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy'):
|
||||
os.environ.pop(_proxy_key, None)
|
||||
@@ -23,8 +26,7 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args, check=True):
|
||||
command = ['docker', 'compose', '--env-file', '.env', '-f', 'compose.yaml', *args]
|
||||
return subprocess.run(command, cwd=ROOT, check=check)
|
||||
return Environment().compose(*args, check=check)
|
||||
|
||||
|
||||
def stamp():
|
||||
@@ -35,7 +37,7 @@ def main():
|
||||
parser = argparse.ArgumentParser(description='Lab6 track 2 scenarios')
|
||||
parser.add_argument('--scenario', choices=['burst', 'sustained', 'false-positive'], default='burst')
|
||||
parser.add_argument('--quick', action='store_true', help='short 20s phases')
|
||||
parser.add_argument('--base-url', default='http://localhost:8080')
|
||||
parser.add_argument('--base-url', default=BASE_URL)
|
||||
parser.add_argument('--load-rate', type=float, default=0.5)
|
||||
parser.add_argument('--output-dir', default='evidence/lab6/track2')
|
||||
args = parser.parse_args()
|
||||
|
||||
@@ -18,13 +18,15 @@ import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
from lab7_environment import Environment
|
||||
from lab7_http import BASE_URL, open_url
|
||||
|
||||
for _key in ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy'):
|
||||
os.environ.pop(_key, None)
|
||||
os.environ['NO_PROXY'] = 'localhost,127.0.0.1,::1'
|
||||
os.environ['no_proxy'] = 'localhost,127.0.0.1,::1'
|
||||
# tests/client.py builds its own opener; make it ignore macOS system proxies too.
|
||||
urllib.request.getproxies = lambda: {}
|
||||
OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ACTIVE_LOAD = [None]
|
||||
@@ -35,24 +37,21 @@ def utc(ts=None):
|
||||
|
||||
|
||||
def http_json(url, timeout=15):
|
||||
with OPENER.open(url, timeout=timeout) as response:
|
||||
with open_url(url, timeout=timeout, operator=True) as response:
|
||||
return json.loads(response.read())
|
||||
|
||||
|
||||
def prom(expr):
|
||||
url = 'http://localhost:9090/api/v1/query?' + urllib.parse.urlencode({'query': expr})
|
||||
url = 'https://localhost:9090/api/v1/query?' + urllib.parse.urlencode({'query': expr})
|
||||
return http_json(url).get('data', {}).get('result', [])
|
||||
|
||||
|
||||
def alerts():
|
||||
return http_json('http://localhost:9090/api/v1/alerts').get('data', {}).get('alerts', [])
|
||||
return http_json('https://localhost:9090/api/v1/alerts').get('data', {}).get('alerts', [])
|
||||
|
||||
|
||||
def compose(*args, check=True):
|
||||
result = subprocess.run(
|
||||
['docker', 'compose', '--env-file', '.env', '-f', 'compose.yaml', *args],
|
||||
cwd=ROOT, capture_output=True, text=True, check=False,
|
||||
)
|
||||
result = Environment().compose(*args, check=False)
|
||||
(ROOT / 'evidence/lab6/track2').mkdir(parents=True, exist_ok=True)
|
||||
with (ROOT / 'evidence/lab6/track2/full-compose.log').open('a') as log:
|
||||
log.write(utc() + ' docker compose ' + ' '.join(args) + ' rc=' + str(result.returncode) + '\n')
|
||||
@@ -67,7 +66,7 @@ def wait_ready(timeout=120):
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
with OPENER.open('http://localhost:8080/health/ready', timeout=5) as response:
|
||||
with open_url(BASE_URL + '/health/ready', timeout=5) as response:
|
||||
if response.status == 200:
|
||||
return True
|
||||
except Exception:
|
||||
@@ -168,7 +167,7 @@ def run_load(out, label, duration, ratio=0.2, rate=0.2):
|
||||
log_path = out / (label + '-load.log')
|
||||
output_path = out / (label + '-load.json')
|
||||
cmd = [sys.executable, str(ROOT / 'scripts/lab6_load.py'),
|
||||
'--base-url', 'http://localhost:8080', '--rate', str(rate),
|
||||
'--base-url', BASE_URL, '--rate', str(rate),
|
||||
'--duration', str(duration), '--upload-ratio', str(ratio),
|
||||
'--deadline', '60', '--output', str(output_path)]
|
||||
log = log_path.open('w')
|
||||
|
||||
@@ -9,28 +9,29 @@ import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
from lab7_environment import Environment
|
||||
from lab7_http import BASE_URL, open_url
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
for key in ('HTTP_PROXY','HTTPS_PROXY','ALL_PROXY','http_proxy','https_proxy','all_proxy'):
|
||||
os.environ.pop(key, None)
|
||||
OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
|
||||
|
||||
def prom(expr):
|
||||
url = 'http://localhost:9090/api/v1/query?' + urllib.parse.urlencode({'query': expr})
|
||||
with OPENER.open(url, timeout=10) as response:
|
||||
url = 'https://localhost:9090/api/v1/query?' + urllib.parse.urlencode({'query': expr})
|
||||
with open_url(url, timeout=10, operator=True) as response:
|
||||
result = json.loads(response.read()).get('data', {}).get('result', [])
|
||||
return result[0]['value'][1] if result else 'MISSING'
|
||||
|
||||
|
||||
def alerts():
|
||||
with OPENER.open('http://localhost:9090/api/v1/alerts', timeout=10) as response:
|
||||
with open_url('https://localhost:9090/api/v1/alerts', timeout=10, operator=True) as response:
|
||||
data = json.loads(response.read()).get('data', {}).get('alerts', [])
|
||||
return [(a['labels'].get('alertname', ''), a['state']) for a in data]
|
||||
|
||||
|
||||
def compose(*args, check=True):
|
||||
return subprocess.run(['docker','compose','--env-file','.env',*args], cwd=ROOT,
|
||||
capture_output=True, text=True, check=check)
|
||||
return Environment().compose(*args, check=check)
|
||||
|
||||
|
||||
def main():
|
||||
@@ -42,7 +43,7 @@ def main():
|
||||
print('UTC', time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()), flush=True)
|
||||
print('HEAD', subprocess.run(['git','rev-parse','HEAD'], cwd=ROOT, capture_output=True, text=True, check=True).stdout.strip(), flush=True)
|
||||
print('$ /api/v1/rules (contains or vector(0))', flush=True)
|
||||
with OPENER.open('http://localhost:9090/api/v1/rules', timeout=10) as response:
|
||||
with open_url('https://localhost:9090/api/v1/rules', timeout=10, operator=True) as response:
|
||||
rules = response.read().decode()
|
||||
print('or_vector_0=', 'or vector(0)' in rules, flush=True)
|
||||
print('json_len=', len(rules), flush=True)
|
||||
@@ -53,7 +54,7 @@ def main():
|
||||
def start_load():
|
||||
index = len(loads)
|
||||
loads.append(subprocess.Popen([
|
||||
'python3', str(ROOT/'scripts/lab6_load.py'), '--base-url', 'http://localhost:8080',
|
||||
'python3', str(ROOT/'scripts/lab6_load.py'), '--base-url', BASE_URL,
|
||||
'--rate', '0.2', '--duration', '1000', '--upload-ratio', '1',
|
||||
'--deadline', '60', '--output', '/tmp/lab6-ttr-worker-load-%d.json' % index,
|
||||
], cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL))
|
||||
|
||||
+11
-16
@@ -19,6 +19,8 @@ import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from lab7_http import BASE_URL, CA_FILE, open_url, grafana_password
|
||||
|
||||
# The lab tools always target loopback; ignore ambient corporate proxies.
|
||||
for _proxy_key in ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy'):
|
||||
os.environ.pop(_proxy_key, None)
|
||||
@@ -36,7 +38,7 @@ def request(url, auth=None, timeout=10):
|
||||
if auth:
|
||||
headers['Authorization'] = 'Basic ' + base64.b64encode(auth.encode()).decode()
|
||||
req = urllib.request.Request(url, headers=headers)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as response:
|
||||
with open_url(req, timeout=timeout, operator=True) as response:
|
||||
return response.status, response.read()
|
||||
|
||||
|
||||
@@ -58,14 +60,6 @@ def loki_query(base, query, start_ns, end_ns, limit=20):
|
||||
return json.loads(raw).get('data', {}).get('result', [])
|
||||
|
||||
|
||||
def grafana_password():
|
||||
path = ROOT / 'secrets/grafana.env'
|
||||
if not path.exists():
|
||||
return None
|
||||
for line in path.read_text().splitlines():
|
||||
if '=' in line and line.split('=', 1)[0].strip() == 'GF_SECURITY_ADMIN_PASSWORD':
|
||||
return line.split('=', 1)[1].strip()
|
||||
return None
|
||||
|
||||
|
||||
def wait_for(fn, attempts=30, delay=2):
|
||||
@@ -85,11 +79,12 @@ def wait_for(fn, attempts=30, delay=2):
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Strict lab6 telemetry gate')
|
||||
parser.add_argument('--base-url', default='http://localhost:8080')
|
||||
parser.add_argument('--prometheus', default='http://localhost:9090')
|
||||
parser.add_argument('--loki', default='http://localhost:3100')
|
||||
parser.add_argument('--tempo', default='http://localhost:3200')
|
||||
parser.add_argument('--grafana', default='http://localhost:3000')
|
||||
parser.add_argument('--base-url', default=BASE_URL)
|
||||
parser.add_argument('--ca-file', default=CA_FILE)
|
||||
parser.add_argument('--prometheus', default='https://localhost:9090')
|
||||
parser.add_argument('--loki', default='https://localhost:3100')
|
||||
parser.add_argument('--tempo', default='https://localhost:3200')
|
||||
parser.add_argument('--grafana', default='https://localhost:3000')
|
||||
parser.add_argument('--wait-seconds', type=int, default=60)
|
||||
args = parser.parse_args()
|
||||
failures = []
|
||||
@@ -98,7 +93,7 @@ def main():
|
||||
# 1. Generate a controlled request, a message and a job.
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client
|
||||
client = Client(args.base_url, timeout=15)
|
||||
client = Client(args.base_url, args.ca_file, timeout=15)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
request_id = 'lab6-verify-' + uuid.uuid4().hex
|
||||
sentinel = 'SENTINEL-TELEMETRY-' + uuid.uuid4().hex
|
||||
@@ -274,7 +269,7 @@ def main():
|
||||
try:
|
||||
password = grafana_password()
|
||||
if not password:
|
||||
failures.append('Grafana admin secret is missing (secrets/grafana.env)')
|
||||
failures.append('Grafana operator secret is missing (secrets/lab7/backends/credentials.json)')
|
||||
else:
|
||||
_, raw = request(args.grafana.rstrip('/') + '/api/health')
|
||||
if json.loads(raw).get('database') != 'ok':
|
||||
|
||||
Executable
+302
@@ -0,0 +1,302 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Measure real password.Hash/Verify and optional real HTTPS login denials.
|
||||
|
||||
python3 scripts/lab7_auth_benchmark.py --concurrency 1 2 8 --operations 120 --output evidence/lab7/auth.json
|
||||
Optional: --api --ca-file <CA> --base-url https://localhost:8443
|
||||
|
||||
The temporary Go program imports this repository's password implementation,
|
||||
reads measured PHC m/t/p, and reports operation latency, busy denial and process
|
||||
peak RSS. It is deleted after execution; passwords, hashes and tokens never
|
||||
appear in output. Compiler memory/time are excluded from process RSS/latency.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import concurrent.futures
|
||||
import datetime as dt
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'student-tests'))
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from lab7_helpers import ProbeFailure, command, require, Stand
|
||||
from client import Client, Failure
|
||||
|
||||
GO_PROGRAM = r'''package main
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"os"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"mtusi-messenger/internal/platform/password"
|
||||
)
|
||||
|
||||
type sample struct {
|
||||
Operation string `json:"operation"`
|
||||
Seconds float64 `json:"seconds"`
|
||||
Result string `json:"result"`
|
||||
}
|
||||
|
||||
func fatal(classification string) {
|
||||
if err := json.NewEncoder(os.Stdout).Encode(map[string]string{"classification": classification}); err != nil {
|
||||
os.Exit(2)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
func main() {
|
||||
concurrency := flag.Int("concurrency", 1, "parallel callers")
|
||||
operations := flag.Int("operations", 120, "total operations")
|
||||
flag.Parse()
|
||||
if *concurrency < 1 || *operations < 1 {
|
||||
fatal("invalid_configuration")
|
||||
}
|
||||
plainBytes := make([]byte, 24)
|
||||
if _, err := rand.Read(plainBytes); err != nil {
|
||||
fatal("entropy_unavailable")
|
||||
}
|
||||
plain := hex.EncodeToString(plainBytes)
|
||||
encoded, err := password.Hash(plain)
|
||||
if err != nil {
|
||||
fatal("seed_hash_failed")
|
||||
}
|
||||
fields := strings.Split(encoded, "$")
|
||||
if len(fields) != 6 || fields[1] != "argon2id" {
|
||||
fatal("measured_hash_not_phc_argon2id")
|
||||
}
|
||||
params := map[string]int{}
|
||||
for _, item := range strings.Split(fields[3], ",") {
|
||||
pair := strings.SplitN(item, "=", 2)
|
||||
if len(pair) != 2 {
|
||||
fatal("measured_phc_parameters_invalid")
|
||||
}
|
||||
value, err := strconv.Atoi(pair[1])
|
||||
if err != nil {
|
||||
fatal("measured_phc_parameters_invalid")
|
||||
}
|
||||
params[pair[0]] = value
|
||||
}
|
||||
jobs := make(chan int)
|
||||
samples := make([]sample, *operations)
|
||||
var group sync.WaitGroup
|
||||
started := time.Now()
|
||||
for range *concurrency {
|
||||
group.Go(func() {
|
||||
for index := range jobs {
|
||||
began := time.Now()
|
||||
operation, result := "hash", "ok"
|
||||
switch index % 3 {
|
||||
case 0:
|
||||
_, err := password.Hash(plain)
|
||||
if errors.Is(err, password.ErrBusy) {
|
||||
result = "busy_denied"
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
result = "hash_error"
|
||||
}
|
||||
case 1, 2:
|
||||
operation = "verify_correct"
|
||||
candidate := plain
|
||||
if index % 3 == 2 {
|
||||
operation = "verify_incorrect"
|
||||
candidate += "-incorrect"
|
||||
}
|
||||
verified, err := password.Verify(candidate, encoded)
|
||||
if errors.Is(err, password.ErrBusy) {
|
||||
result = "busy_denied"
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
result = "verify_error"
|
||||
break
|
||||
}
|
||||
expectedMatch := index % 3 == 1
|
||||
if verified.Match != expectedMatch {
|
||||
result = "verification_mismatch"
|
||||
}
|
||||
}
|
||||
samples[index] = sample{
|
||||
Operation: operation,
|
||||
Seconds: time.Since(began).Seconds(),
|
||||
Result: result,
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
for index := range *operations {
|
||||
jobs <- index
|
||||
}
|
||||
close(jobs)
|
||||
group.Wait()
|
||||
elapsed := time.Since(started).Seconds()
|
||||
counts := map[string]int{}
|
||||
timings := map[string][]float64{}
|
||||
for _, value := range samples {
|
||||
counts[value.Result]++
|
||||
if value.Result == "ok" {
|
||||
timings[value.Operation] = append(timings[value.Operation], value.Seconds)
|
||||
}
|
||||
}
|
||||
latency := map[string]map[string]float64{}
|
||||
for operation, values := range timings {
|
||||
sort.Float64s(values)
|
||||
latency[operation] = map[string]float64{
|
||||
"p50_seconds": values[(len(values)-1)/2],
|
||||
"p95_seconds": values[(len(values)-1)*95/100],
|
||||
"max_seconds": values[len(values)-1],
|
||||
}
|
||||
}
|
||||
var usage syscall.Rusage
|
||||
if err := syscall.Getrusage(syscall.RUSAGE_SELF, &usage); err != nil {
|
||||
fatal("peak_rss_unavailable")
|
||||
}
|
||||
peakRSS := uint64(usage.Maxrss)
|
||||
if runtime.GOOS != "darwin" {
|
||||
peakRSS *= 1024
|
||||
}
|
||||
result := map[string]any{
|
||||
"classification": "measured",
|
||||
"algorithm": "argon2id",
|
||||
"parameters": params,
|
||||
"concurrency": *concurrency,
|
||||
"operations": *operations,
|
||||
"elapsed_seconds": elapsed,
|
||||
"successful_operations_per_second": float64(counts["ok"]) / elapsed,
|
||||
"busy_denied_rate": float64(counts["busy_denied"]) / float64(*operations),
|
||||
"counts": counts,
|
||||
"latency": latency,
|
||||
"peak_rss_bytes": peakRSS,
|
||||
"goos": runtime.GOOS,
|
||||
"gomaxprocs": runtime.GOMAXPROCS(0),
|
||||
"raw_samples": samples,
|
||||
}
|
||||
if err := json.NewEncoder(os.Stdout).Encode(result); err != nil {
|
||||
os.Exit(2)
|
||||
}
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def hash_benchmark(concurrency, operations):
|
||||
# Internal package import is legal only under this module. No permanent
|
||||
# source or build artifact is created, and the module itself is not edited.
|
||||
with tempfile.TemporaryDirectory(prefix='lab7-auth-bench-', dir=ROOT) as directory:
|
||||
source = Path(directory) / 'main.go'
|
||||
source.write_text(GO_PROGRAM)
|
||||
# Homebrew's default `go` can be older than go.mod's toolchain. Resolve
|
||||
# the cached toolchain GOROOT once, then pin that binary with local mode.
|
||||
go_bin = 'go'
|
||||
discovery = command(['go', 'env', 'GOROOT'], env={'GOTOOLCHAIN': 'auto'},
|
||||
check=False, timeout=30)
|
||||
candidate = Path(discovery.stdout.strip()) / 'bin' / 'go'
|
||||
if candidate.is_file():
|
||||
go_bin = str(candidate)
|
||||
result = command([go_bin, 'run', '-mod=readonly', str(source),
|
||||
'--concurrency', str(concurrency), '--operations', str(operations)],
|
||||
env={'GOPROXY': 'off', 'GOSUMDB': 'off', 'GOTOOLCHAIN': 'local'}, timeout=300)
|
||||
try:
|
||||
payload = json.loads(result.stdout)
|
||||
except ValueError:
|
||||
raise ProbeFailure('hash_benchmark_invalid_json') from None
|
||||
require(payload.get('classification') == 'measured', 'hash_benchmark_not_measured')
|
||||
require(payload['counts'].get('hash_error', 0) == 0 and payload['counts'].get('verify_error', 0) == 0
|
||||
and payload['counts'].get('verification_mismatch', 0) == 0, 'real_hash_verification_failure')
|
||||
return payload
|
||||
|
||||
|
||||
def api_benchmark(args, concurrency):
|
||||
stand = Stand(base_url=args.base_url)
|
||||
client = Client(stand.base_url, args.ca_file, timeout=5)
|
||||
actor = client.user('authbench')
|
||||
credential = base64.b64encode((actor['registration']['username'] + ':incorrect-local-benchmark-password').encode()).decode()
|
||||
ids = [item['Id'] for item in stand.containers('api')]
|
||||
require(len(ids) == 2, 'auth_benchmark_requires_two_replicas')
|
||||
# cgroup v2 memory.peak measures actual API containers, not the Python or
|
||||
# compiler process. It can include a previous higher peak: report honestly.
|
||||
def peak_memory():
|
||||
peaks = []
|
||||
for container in ids:
|
||||
value = command(['docker', 'exec', container, 'cat', '/sys/fs/cgroup/memory.peak'], check=False, timeout=10)
|
||||
peaks.append(int(value.stdout.strip()) if value.returncode == 0 and value.stdout.strip().isdigit() else None)
|
||||
return peaks
|
||||
peaks_before = peak_memory()
|
||||
def one(index):
|
||||
began = time.monotonic()
|
||||
try:
|
||||
current = Client(stand.base_url, args.ca_file, timeout=5)
|
||||
response = current.call('POST', '/api/v1/auth/sessions', (401, 429), headers={'Authorization': 'Basic ' + credential})
|
||||
status = response['status']
|
||||
if status == 429:
|
||||
retry = response['headers'].get('Retry-After', '')
|
||||
require(retry.isdigit() and int(retry) > 0, 'api_busy_missing_retry_after')
|
||||
return {'index': index, 'status': status, 'latency_seconds': time.monotonic() - began,
|
||||
'instance': response['headers'].get('X-Instance-Id')}
|
||||
except (Failure, ProbeFailure):
|
||||
return {'index': index, 'status': None, 'classification': 'api_benchmark_request_failed',
|
||||
'latency_seconds': time.monotonic() - began}
|
||||
started = time.monotonic()
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as pool:
|
||||
samples = list(pool.map(one, range(args.operations)))
|
||||
elapsed = time.monotonic() - started
|
||||
peaks_after = peak_memory()
|
||||
require(all(s['status'] in (401, 429) for s in samples), 'api_auth_benchmark_unexpected_failure')
|
||||
denied = sum(s['status'] == 429 for s in samples)
|
||||
latencies = sorted(s['latency_seconds'] for s in samples)
|
||||
latency = {'p50_seconds': latencies[(len(latencies) - 1) // 2],
|
||||
'p95_seconds': latencies[(len(latencies) - 1) * 95 // 100], 'max_seconds': latencies[-1]}
|
||||
return {'concurrency': concurrency, 'operations': args.operations, 'elapsed_seconds': elapsed,
|
||||
'requests_per_second': len(samples) / elapsed, 'admission_denied_rate': denied / len(samples),
|
||||
'incorrect_password_401': sum(s['status'] == 401 for s in samples),
|
||||
'api_cgroup_peak_bytes_before': peaks_before, 'api_cgroup_peak_bytes_after': peaks_after,
|
||||
'latency': latency, 'raw_samples': samples,
|
||||
'limitations': ['Cgroup memory.peak includes container lifetime history; account/shared/local rate limits all contribute to429.']}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--concurrency', type=int, nargs='+', default=[1, 2, 8])
|
||||
parser.add_argument('--operations', type=int, default=120)
|
||||
parser.add_argument('--api', action='store_true')
|
||||
parser.add_argument('--base-url', default='https://localhost:8443')
|
||||
parser.add_argument('--ca-file')
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
require(all(0 < c <= 64 for c in args.concurrency) and args.operations >= 3, 'invalid_benchmark_configuration')
|
||||
require(not args.api or bool(args.ca_file), 'api_benchmark_ca_required')
|
||||
measured = [hash_benchmark(c, args.operations) for c in args.concurrency]
|
||||
result = {'study': 'lab7-auth-benchmark', 'timestamp': dt.datetime.now(dt.timezone.utc).isoformat(),
|
||||
'hash_verify': measured, 'api_auth': [api_benchmark(args, c) for c in args.concurrency] if args.api else [],
|
||||
'limitations': ['Native benchmark imports actual configured password implementation, not a reimplementation.',
|
||||
'Operation scheduling is closed-loop; memory includes Go runtime and seed hash, excludes compiler.',
|
||||
'Optional API benchmark uses one fresh account per concurrency level and real shared rejection paths.']}
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.output.write_text(json.dumps(result, indent=2, sort_keys=True) + '\n')
|
||||
print(json.dumps({'study': result['study'], 'classification': 'measured', 'output': str(args.output)}, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except ProbeFailure as exc:
|
||||
print(json.dumps({'classification': exc.classification, 'detail': exc.detail}))
|
||||
raise SystemExit(1)
|
||||
except Exception as exc:
|
||||
print(json.dumps({'classification': 'benchmark_exception', 'type': type(exc).__name__}))
|
||||
raise SystemExit(1)
|
||||
Executable
+246
@@ -0,0 +1,246 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Operator-local environment and verified OpenBao transport for lab7."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import ssl
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ROLES = {
|
||||
'api': ['api', 'api-replica'],
|
||||
'worker': ['worker'],
|
||||
'relay': ['relay'],
|
||||
'lb': ['lb', 'localhost'],
|
||||
'postgres': ['postgres', 'localhost'],
|
||||
'redis': ['redis', 'localhost'],
|
||||
's3': ['s3', 'seaweedfs', 'localhost'],
|
||||
'broker': ['broker', 'localhost'],
|
||||
'collector': ['collector', 'otel-collector', 'localhost'],
|
||||
'prometheus': ['prometheus', 'localhost'],
|
||||
'loki': ['loki', 'localhost'],
|
||||
'tempo': ['tempo', 'localhost'],
|
||||
'grafana': ['grafana', 'localhost'],
|
||||
'openbao': ['openbao', 'localhost'],
|
||||
'operator': ['operator'],
|
||||
'rogue': ['rogue'],
|
||||
}
|
||||
ALPINE_IMAGE = 'alpine:3.22@sha256:49340b346798875b5592e5d420241f2f9cfba5f47e62ebb1446a1b34734e898f'
|
||||
|
||||
|
||||
class OperationError(RuntimeError):
|
||||
"""A sanitized failure; secret-bearing API bodies are never included."""
|
||||
|
||||
|
||||
def read_env(path: Path) -> dict[str, str]:
|
||||
values = {}
|
||||
if not path.exists():
|
||||
return values
|
||||
for line in path.read_text().splitlines():
|
||||
line = line.strip()
|
||||
if line and not line.startswith('#') and '=' in line:
|
||||
key, value = line.split('=', 1)
|
||||
values[key.strip()] = value.strip().strip('"').strip("'")
|
||||
return values
|
||||
|
||||
|
||||
def atomic_write(path: Path, content: str, mode: int = 0o600) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd, temporary = tempfile.mkstemp(prefix='.' + path.name, dir=path.parent)
|
||||
try:
|
||||
with os.fdopen(fd, 'w') as stream:
|
||||
os.fchmod(stream.fileno(), mode)
|
||||
stream.write(content)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
if os.path.exists(temporary):
|
||||
os.unlink(temporary)
|
||||
|
||||
|
||||
class Environment:
|
||||
def __init__(self) -> None:
|
||||
self.config = read_env(ROOT / '.env')
|
||||
self.project = self.value('COMPOSE_PROJECT_NAME', 'mtusi-messenger-lab6')
|
||||
if not re.fullmatch(r'[a-z0-9][a-z0-9_.-]*', self.project):
|
||||
raise OperationError('invalid local Compose project name')
|
||||
self.secrets = Path(self.value('LAB7_SECRETS_DIR', str(ROOT / 'secrets/lab7')))
|
||||
if not self.secrets.is_absolute():
|
||||
self.secrets = ROOT / self.secrets
|
||||
self.secrets = self.secrets.resolve()
|
||||
self.state = Path(self.value(
|
||||
'LAB7_OPERATOR_STATE',
|
||||
str(Path.home() / '.local/share/mtusi-lab7' / self.project),
|
||||
)).expanduser().resolve()
|
||||
self.secrets.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
self.state.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
os.chmod(self.secrets, 0o700)
|
||||
os.chmod(self.state, 0o700)
|
||||
self.redactions: set[str] = set()
|
||||
self.bao_url = 'https://localhost:' + self.value('BAO_PORT', '8200')
|
||||
self.base_url = 'https://localhost:' + self.value('PUBLIC_PORT', '8443')
|
||||
self.process_env = {
|
||||
**os.environ,
|
||||
'COMPOSE_PROJECT_NAME': self.project,
|
||||
'LAB7_SECRETS_DIR': str(self.secrets),
|
||||
'NO_PROXY': 'localhost,127.0.0.1,::1',
|
||||
'no_proxy': 'localhost,127.0.0.1,::1',
|
||||
}
|
||||
for key in ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy'):
|
||||
self.process_env.pop(key, None)
|
||||
|
||||
def value(self, key: str, fallback: str) -> str:
|
||||
return os.environ.get(key, self.config.get(key, fallback))
|
||||
|
||||
def redact(self, value: str) -> str:
|
||||
for secret in self.redactions:
|
||||
if len(secret) >= 8:
|
||||
value = value.replace(secret, '[REDACTED]')
|
||||
return value
|
||||
|
||||
def run(self, command: list[str], *, data: str | None = None,
|
||||
check: bool = True, timeout: float = 180) -> subprocess.CompletedProcess:
|
||||
result = subprocess.run(command, cwd=ROOT, input=data, text=True,
|
||||
capture_output=True, timeout=timeout, env=self.process_env)
|
||||
if check and result.returncode:
|
||||
# SQL/bootstrap commands can echo a failed statement containing a password.
|
||||
detail = '' if data is not None else self.redact(result.stderr[-1800:])
|
||||
raise OperationError(f'{Path(command[0]).name} failed ({result.returncode}): {detail}')
|
||||
return result
|
||||
|
||||
def compose(self, *args: str, data: str | None = None,
|
||||
check: bool = True, timeout: float = 180) -> subprocess.CompletedProcess:
|
||||
env_file = ROOT / ('.env' if (ROOT / '.env').exists() else '.env.example')
|
||||
configured = self.process_env.get('COMPOSE_FILE', self.value('COMPOSE_FILE', str(ROOT / 'compose.yaml')))
|
||||
files = configured.split(os.pathsep)
|
||||
override = self.value('LAB7_COMPOSE_OVERRIDE', '')
|
||||
if override and override not in files:
|
||||
files.append(override)
|
||||
arguments = ['docker', 'compose', '--env-file', str(env_file)]
|
||||
for filename in files:
|
||||
path = Path(filename)
|
||||
if not path.is_absolute():
|
||||
path = ROOT / path
|
||||
arguments.extend(['-f', str(path)])
|
||||
return self.run([*arguments, *args], data=data, check=check, timeout=timeout)
|
||||
|
||||
def private_json(self, path: Path, value: dict) -> None:
|
||||
atomic_write(path, json.dumps(value, indent=2) + '\n')
|
||||
|
||||
def read_json(self, path: Path, fallback: dict | None = None) -> dict:
|
||||
if not path.exists():
|
||||
return {} if fallback is None else fallback
|
||||
return json.loads(path.read_text())
|
||||
|
||||
def identity(self, role: str) -> Path:
|
||||
return self.secrets / 'pki' / role / 'current'
|
||||
|
||||
def group_access(self, path: Path) -> None:
|
||||
# Operator-only helper: no network, no daemon socket, narrowly scoped mount.
|
||||
# DAC_OVERRIDE is needed to traverse operator-owned private directories;
|
||||
# CHOWN assigns the runtime group without making private keys world-readable.
|
||||
self.run(['docker', 'run', '--rm', '--network', 'none', '--user', '0:0',
|
||||
'--cap-drop', 'ALL', '--cap-add', 'CHOWN', '--cap-add', 'DAC_OVERRIDE',
|
||||
'--security-opt', 'no-new-privileges:true',
|
||||
'--mount', f'type=bind,source={path},target=/generated',
|
||||
ALPINE_IMAGE, 'chown', '-R', f'{os.getuid()}:10001', '/generated'])
|
||||
|
||||
def snapshot(self, role: str) -> dict[str, str]:
|
||||
directory = self.identity(role).resolve(strict=True)
|
||||
return {name: (directory / name).read_text()
|
||||
for name in ('tls.crt', 'tls.key', 'ca.crt', 'ca.crl')}
|
||||
|
||||
def publish(self, role: str, certificate: str, private_key: str,
|
||||
ca_bundle: str, crls: str) -> dict:
|
||||
if role not in ROLES and role not in ('wrong-identity', 'untrusted', 'next-lb'):
|
||||
raise OperationError('unknown service identity')
|
||||
certificate = certificate.rstrip() + '\n'
|
||||
private_key = private_key.rstrip() + '\n'
|
||||
public = self.run(['openssl', 'x509', '-pubkey', '-noout'], data=certificate).stdout
|
||||
key_public = self.run(['openssl', 'pkey', '-pubout'], data=private_key).stdout
|
||||
if public.strip() != key_public.strip():
|
||||
raise OperationError('certificate and private key do not match')
|
||||
directory = self.secrets / 'pki' / role
|
||||
version_name = str(time.time_ns()) + '-' + hashlib.sha256(certificate.encode()).hexdigest()[:12]
|
||||
version = directory / 'versions' / version_name
|
||||
version.mkdir(parents=True, mode=0o750)
|
||||
for parent in (directory, directory / 'versions'):
|
||||
os.chmod(parent, 0o750)
|
||||
for name, content in {
|
||||
'tls.crt': certificate, 'tls.key': private_key,
|
||||
'tls.pem': certificate + private_key, 'ca.crt': ca_bundle, 'ca.crl': crls,
|
||||
}.items():
|
||||
atomic_write(version / name, content, 0o640)
|
||||
self.group_access(directory if not (directory / 'current').exists() else version)
|
||||
temporary = directory / ('.current-' + version_name)
|
||||
temporary.symlink_to(Path('versions') / version_name)
|
||||
os.replace(temporary, directory / 'current')
|
||||
selector = directory / ('.current-version-' + version_name)
|
||||
atomic_write(selector, version_name + '\n', 0o640)
|
||||
self.group_access(selector)
|
||||
os.replace(selector, directory / 'current-version')
|
||||
description = self.run(['openssl', 'x509', '-noout', '-serial', '-enddate'],
|
||||
data=certificate).stdout.splitlines()
|
||||
serial = next(line.split('=', 1)[1].lower() for line in description if line.startswith('serial='))
|
||||
expiry = next(line.split('=', 1)[1] for line in description if line.startswith('notAfter='))
|
||||
return {'role': role, 'serial_number': serial, 'not_after': expiry}
|
||||
|
||||
|
||||
class BaoClient:
|
||||
def __init__(self, environment: Environment, role: str | None = 'operator') -> None:
|
||||
self.environment = environment
|
||||
self.role = role
|
||||
identity = environment.identity(role or 'operator')
|
||||
context = ssl.create_default_context(cafile=str(identity / 'ca.crt'))
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
if role is not None:
|
||||
context.load_cert_chain(str(identity / 'tls.crt'), str(identity / 'tls.key'))
|
||||
self.opener = urllib.request.build_opener(
|
||||
urllib.request.ProxyHandler({}), urllib.request.HTTPSHandler(context=context))
|
||||
|
||||
def request(self, method: str, path: str, data: dict | None = None,
|
||||
token: str | None = None, raw: bool = False,
|
||||
allowed: tuple[int, ...] = (200, 204), timeout: float = 5):
|
||||
headers = {'Accept': 'application/json', 'Connection': 'close'}
|
||||
payload = None
|
||||
if data is not None:
|
||||
headers['Content-Type'] = 'application/json'
|
||||
payload = json.dumps(data).encode()
|
||||
if token:
|
||||
headers['X-Vault-Token'] = token
|
||||
self.environment.redactions.add(token)
|
||||
request = urllib.request.Request(self.environment.bao_url + '/v1/' + path.lstrip('/'),
|
||||
data=payload, method=method, headers=headers)
|
||||
try:
|
||||
with self.opener.open(request, timeout=timeout) as response:
|
||||
body = response.read(1024 * 1024 + 1)
|
||||
status = response.status
|
||||
except urllib.error.HTTPError as error:
|
||||
status = error.code
|
||||
body = error.read(1024 * 1024 + 1)
|
||||
except (urllib.error.URLError, TimeoutError) as error:
|
||||
raise OperationError('OpenBao verified TLS transport failed: ' + str(error)) from error
|
||||
if status not in allowed:
|
||||
raise OperationError(f'OpenBao {method} {path} rejected with HTTP {status}')
|
||||
if len(body) > 1024 * 1024:
|
||||
raise OperationError('OpenBao response exceeds one MiB')
|
||||
if raw:
|
||||
return body.decode()
|
||||
return json.loads(body) if body else {}
|
||||
|
||||
def login(self, role: str | None = None) -> str:
|
||||
response = self.request('POST', 'auth/cert/login', {'name': role or self.role})
|
||||
token = response.get('auth', {}).get('client_token')
|
||||
if not token:
|
||||
raise OperationError('OpenBao did not issue a scoped service token')
|
||||
self.environment.redactions.add(token)
|
||||
return token
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Verified local HTTPS transport shared by preserved lab1–6 operator tools."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from lab7_environment import ROOT, read_env
|
||||
|
||||
_SETTINGS = read_env(ROOT / '.env')
|
||||
|
||||
|
||||
def _value(name: str, fallback: str) -> str:
|
||||
return os.environ.get(name, _SETTINGS.get(name, fallback))
|
||||
|
||||
|
||||
def _path(value: str) -> Path:
|
||||
path = Path(value).expanduser()
|
||||
return path if path.is_absolute() else ROOT / path
|
||||
|
||||
|
||||
SECRETS_DIR = _path(_value('LAB7_SECRETS_DIR', 'secrets/lab7'))
|
||||
OPERATOR_IDENTITY = SECRETS_DIR / 'pki/operator/current'
|
||||
CA_FILE = str(_path(_value('CA_FILE', str(OPERATOR_IDENTITY / 'ca.crt'))))
|
||||
BASE_URL = _value('BASE_URL', 'https://localhost:' + _value('PUBLIC_PORT', '8443'))
|
||||
|
||||
|
||||
class _HTTPSOnly(urllib.request.HTTPHandler):
|
||||
def http_open(self, request):
|
||||
raise ValueError('legacy operator tools require a verified HTTPS URL')
|
||||
|
||||
|
||||
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, request, response, code, message, headers, new_url):
|
||||
return None
|
||||
|
||||
|
||||
def public_context(ca_file: str | None = CA_FILE) -> ssl.SSLContext:
|
||||
context = ssl.create_default_context(cafile=str(_path(ca_file or CA_FILE)))
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
return context
|
||||
|
||||
|
||||
def public_opener(ca_file: str | None = CA_FILE) -> urllib.request.OpenerDirector:
|
||||
return urllib.request.build_opener(
|
||||
urllib.request.ProxyHandler({}),
|
||||
_HTTPSOnly(), _NoRedirect(),
|
||||
urllib.request.HTTPSHandler(context=public_context(ca_file)),
|
||||
)
|
||||
|
||||
|
||||
def operator_opener(ca_file: str | None = CA_FILE) -> urllib.request.OpenerDirector:
|
||||
# Resolve the immutable identity snapshot once so rotation cannot mix key/cert.
|
||||
identity = OPERATOR_IDENTITY.resolve(strict=True)
|
||||
ca_path = _path(ca_file or CA_FILE)
|
||||
if ca_path == OPERATOR_IDENTITY / 'ca.crt':
|
||||
ca_path = identity / 'ca.crt'
|
||||
context = public_context(str(ca_path))
|
||||
context.load_cert_chain(
|
||||
str(_path(_value('OPERATOR_CERT_FILE', str(identity / 'tls.crt')))),
|
||||
str(_path(_value('OPERATOR_KEY_FILE', str(identity / 'tls.key')))),
|
||||
)
|
||||
return urllib.request.build_opener(
|
||||
urllib.request.ProxyHandler({}), _HTTPSOnly(), _NoRedirect(),
|
||||
urllib.request.HTTPSHandler(context=context),
|
||||
)
|
||||
|
||||
|
||||
def open_url(url_or_request, timeout: float = 10, *, operator: bool = False,
|
||||
ca_file: str | None = CA_FILE):
|
||||
url = url_or_request.full_url if isinstance(url_or_request, urllib.request.Request) else url_or_request
|
||||
if urllib.parse.urlsplit(url).scheme != 'https':
|
||||
raise ValueError('legacy operator tools require a verified HTTPS URL')
|
||||
opener = operator_opener(ca_file) if operator else public_opener(ca_file)
|
||||
return opener.open(url_or_request, timeout=timeout)
|
||||
|
||||
|
||||
def grafana_password() -> str:
|
||||
credentials = json.loads((SECRETS_DIR / 'backends/credentials.json').read_text())
|
||||
password = credentials['grafana']['password']
|
||||
if not isinstance(password, str) or not password:
|
||||
raise ValueError('operator Grafana password is missing')
|
||||
return password
|
||||
Executable
+65
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run existing database/cache integration tests over verified local TLS.
|
||||
|
||||
Requires a bootstrapped stand (make up). Tests create isolated PostgreSQL
|
||||
fixture databases and use Redis DB7, never production cache DB0.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from lab7_environment import OperationError, ROOT
|
||||
from securityctl import Controller
|
||||
|
||||
|
||||
def main() -> int:
|
||||
control = Controller()
|
||||
if not control.credentials_path.exists():
|
||||
raise OperationError('run make up before operator integration tests')
|
||||
values = control.credentials()
|
||||
environment = control.env.process_env.copy()
|
||||
environment['COMPOSE_FILE'] = str(ROOT / 'docker-compose.local.yaml')
|
||||
control.env.process_env.update(environment)
|
||||
control.env.config['COMPOSE_FILE'] = environment['COMPOSE_FILE']
|
||||
control.env.compose('up', '-d', '--no-build', 'postgres', 'redis', timeout=180)
|
||||
control.wait_stores()
|
||||
identity = control.env.identity('operator')
|
||||
environment.update({
|
||||
'TEST_POSTGRES_HOST': 'localhost',
|
||||
'TEST_POSTGRES_PORT': control.env.value('TEST_POSTGRES_PORT', '15432'),
|
||||
'TEST_POSTGRES_USER': values['postgres']['operator']['username'],
|
||||
'TEST_POSTGRES_PASSWORD': values['postgres']['operator']['password'],
|
||||
'TEST_POSTGRES_DATABASE': 'messenger',
|
||||
'TEST_POSTGRES_SSL_MODE': 'verify-full',
|
||||
'TEST_REDIS_HOST': 'localhost',
|
||||
'TEST_REDIS_PORT': control.env.value('TEST_REDIS_PORT', '16379'),
|
||||
'TEST_REDIS_USERNAME': 'operator',
|
||||
'TEST_REDIS_PASSWORD': values['redis']['operator']['password'],
|
||||
'TEST_REDIS_DB': '7',
|
||||
'TLS_CA_FILE': str(identity / 'ca.crt'),
|
||||
'TLS_CERT_FILE': str(identity / 'tls.crt'),
|
||||
'TLS_KEY_FILE': str(identity / 'tls.key'),
|
||||
'TLS_CRL_FILE': str(identity / 'ca.crl'),
|
||||
'TLS_VERSION_FILE': str(identity.parent / 'current-version'),
|
||||
})
|
||||
result = subprocess.run([
|
||||
os.environ.get('GO', 'go'), 'test', '-tags=integration', '-p', '1',
|
||||
'-count=1', '-timeout=15m', './internal/storage/postgres', './internal/storage/redis',
|
||||
], cwd=ROOT, env=environment, text=True, capture_output=True, timeout=1000)
|
||||
output = control.env.redact(result.stdout + result.stderr)
|
||||
destination = ROOT / 'evidence/lab7/integration.txt'
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
destination.write_text(output)
|
||||
print(output, end='')
|
||||
return result.returncode
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except (OperationError, OSError, subprocess.TimeoutExpired) as error:
|
||||
print('FAIL: ' + str(error), file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
Executable
+423
@@ -0,0 +1,423 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline root custody, OpenBao intermediate issuance and atomic leaf rotation."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import ssl
|
||||
import time
|
||||
|
||||
from lab7_environment import BaoClient, Environment, OperationError, ROLES, atomic_write
|
||||
|
||||
|
||||
class PKI:
|
||||
def __init__(self, environment: Environment) -> None:
|
||||
self.env = environment
|
||||
self.state_path = environment.state / 'pki-state.json'
|
||||
self.state = environment.read_json(self.state_path, {
|
||||
'active_root': 1, 'trust_roots': [1], 'issuers': {},
|
||||
})
|
||||
|
||||
def save(self) -> None:
|
||||
self.env.private_json(self.state_path, self.state)
|
||||
|
||||
def root_dir(self, generation: int | str) -> Path:
|
||||
return self.env.state / ('root-' + str(generation))
|
||||
|
||||
def create_root(self, generation: int | str) -> bool:
|
||||
directory = self.root_dir(generation)
|
||||
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
if not (directory / 'ca.key').exists():
|
||||
self.env.run(['openssl', 'genpkey', '-algorithm', 'EC', '-pkeyopt',
|
||||
'ec_paramgen_curve:P-256', '-out', str(directory / 'ca.key')])
|
||||
os.chmod(directory / 'ca.key', 0o600)
|
||||
self.env.run(['openssl', 'req', '-new', '-x509', '-days', '3650',
|
||||
'-key', str(directory / 'ca.key'), '-out', str(directory / 'ca.crt'),
|
||||
'-subj', '/CN=MTUSI-Lab7-Root-' + str(generation),
|
||||
'-addext', 'basicConstraints=critical,CA:TRUE,pathlen:1',
|
||||
'-addext', 'keyUsage=critical,keyCertSign,cRLSign',
|
||||
'-addext', 'subjectKeyIdentifier=hash'])
|
||||
for name, initial in (('index.txt', ''), ('serial', secrets.token_hex(16) + '\n'),
|
||||
('crlnumber', secrets.token_hex(8) + '\n')):
|
||||
if not (directory / name).exists():
|
||||
atomic_write(directory / name, initial)
|
||||
(directory / 'newcerts').mkdir(exist_ok=True, mode=0o700)
|
||||
config = f'''[ca]
|
||||
default_ca = issuer
|
||||
[issuer]
|
||||
dir = {directory}
|
||||
database = $dir/index.txt
|
||||
new_certs_dir = $dir/newcerts
|
||||
certificate = $dir/ca.crt
|
||||
private_key = $dir/ca.key
|
||||
serial = $dir/serial
|
||||
crlnumber = $dir/crlnumber
|
||||
default_md = sha256
|
||||
default_days = 1
|
||||
default_crl_days = 3
|
||||
policy = names
|
||||
unique_subject = no
|
||||
copy_extensions = none
|
||||
[names]
|
||||
commonName = supplied
|
||||
'''
|
||||
atomic_write(directory / 'openssl.cnf', config)
|
||||
crl = directory / 'ca.crl'
|
||||
refresh = not crl.exists()
|
||||
if not refresh:
|
||||
result = self.env.run(['openssl', 'crl', '-in', str(crl), '-noout', '-nextupdate'])
|
||||
expires = ssl.cert_time_to_seconds(result.stdout.strip().split('=', 1)[1])
|
||||
refresh = expires <= time.time() + 86400
|
||||
if refresh:
|
||||
result = self.env.run(['openssl', 'ca', '-gencrl', '-config', str(directory / 'openssl.cnf')])
|
||||
atomic_write(crl, result.stdout)
|
||||
return refresh
|
||||
|
||||
def root_bundle(self) -> str:
|
||||
return ''.join((self.root_dir(generation) / 'ca.crt').read_text()
|
||||
for generation in self.state['trust_roots'])
|
||||
|
||||
def bundle(self) -> str:
|
||||
result = self.root_bundle()
|
||||
for generation in self.state['trust_roots']:
|
||||
path = self.root_dir(generation) / 'intermediate.crt'
|
||||
if path.exists():
|
||||
result += path.read_text()
|
||||
return result
|
||||
|
||||
def root_crls(self) -> str:
|
||||
return ''.join((self.root_dir(generation) / 'ca.crl').read_text()
|
||||
for generation in self.state['trust_roots'])
|
||||
|
||||
def cached_crls(self) -> str:
|
||||
result = self.root_crls()
|
||||
for generation in self.state['trust_roots']:
|
||||
path = self.root_dir(generation) / 'intermediate.crl'
|
||||
if path.exists():
|
||||
result += path.read_text()
|
||||
return result
|
||||
|
||||
def offline_leaf(self, role: str, generation: int | str, *,
|
||||
common_name: str | None = None, uri_role: str | None = None) -> tuple[str, str]:
|
||||
directory = self.env.state / 'offline-leaves' / role
|
||||
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
key = directory / 'tls.key'
|
||||
csr = directory / 'leaf.csr'
|
||||
certificate = directory / 'tls.crt'
|
||||
self.env.run(['openssl', 'genpkey', '-algorithm', 'EC', '-pkeyopt',
|
||||
'ec_paramgen_curve:P-256', '-out', str(key)])
|
||||
os.chmod(key, 0o600)
|
||||
cn = common_name or role
|
||||
self.env.run(['openssl', 'req', '-new', '-key', str(key), '-out', str(csr),
|
||||
'-subj', '/CN=' + cn])
|
||||
dns = ROLES.get(role, [cn])
|
||||
san = ','.join(['DNS:' + value for value in dns] + ['URI:spiffe://mtusi/' + (uri_role or role)])
|
||||
extensions = f'''[leaf]
|
||||
basicConstraints=critical,CA:FALSE
|
||||
keyUsage=critical,digitalSignature,keyEncipherment
|
||||
extendedKeyUsage=serverAuth,clientAuth
|
||||
subjectKeyIdentifier=hash
|
||||
authorityKeyIdentifier=keyid,issuer
|
||||
subjectAltName={san}
|
||||
'''
|
||||
atomic_write(directory / 'extensions.cnf', extensions)
|
||||
self.env.run(['openssl', 'ca', '-batch', '-notext', '-days', '1',
|
||||
'-config', str(self.root_dir(generation) / 'openssl.cnf'),
|
||||
'-extfile', str(directory / 'extensions.cnf'), '-extensions', 'leaf',
|
||||
'-in', str(csr), '-out', str(certificate)])
|
||||
return certificate.read_text(), key.read_text()
|
||||
|
||||
def prepare(self) -> None:
|
||||
refreshed = False
|
||||
for generation in self.state['trust_roots']:
|
||||
refreshed = self.create_root(generation) or refreshed
|
||||
for role in ROLES:
|
||||
if not self.env.identity(role).exists():
|
||||
certificate, key = self.offline_leaf(role, self.state['active_root'])
|
||||
self.env.publish(role, certificate, key, self.bundle(), self.cached_crls())
|
||||
elif refreshed or not (self.env.secrets / 'pki' / role / 'current-version').exists():
|
||||
snapshot = self.env.snapshot(role)
|
||||
self.env.publish(role, snapshot['tls.crt'], snapshot['tls.key'],
|
||||
self.bundle(), self.cached_crls())
|
||||
# Controlled wrong identity and wrong CA fixtures contain no root key.
|
||||
if not self.env.identity('wrong-identity').exists():
|
||||
certificate, key = self.offline_leaf('wrong-identity', self.state['active_root'],
|
||||
common_name='lb', uri_role='rogue')
|
||||
self.env.publish('wrong-identity', certificate, key, self.bundle(), self.cached_crls())
|
||||
if not self.env.identity('untrusted').exists():
|
||||
self.create_root('foreign')
|
||||
certificate, key = self.offline_leaf('untrusted', 'foreign', common_name='lb', uri_role='lb')
|
||||
self.env.publish('untrusted', certificate, key, self.bundle(), self.cached_crls())
|
||||
self.save()
|
||||
|
||||
def recover_transport(self) -> bool:
|
||||
restarted_listener = False
|
||||
for role in ('operator', 'openbao'):
|
||||
certificate = self.env.identity(role) / 'tls.crt'
|
||||
valid = self.env.run(['openssl', 'x509', '-checkend', '30', '-noout',
|
||||
'-in', str(certificate)], check=False).returncode == 0
|
||||
if valid:
|
||||
continue
|
||||
issued, key = self.offline_leaf(role, self.state['active_root'])
|
||||
self.env.publish(role, issued, key, self.bundle(), self.cached_crls())
|
||||
restarted_listener = restarted_listener or role == 'openbao'
|
||||
return restarted_listener
|
||||
|
||||
def create_intermediate(self, client: BaoClient, token: str, generation: int) -> str:
|
||||
known = self.state['issuers'].get(str(generation))
|
||||
if known:
|
||||
client.request('GET', 'pki/issuer/' + known, token=token)
|
||||
return known
|
||||
before = client.request('LIST', 'pki/issuers', token=token, allowed=(200, 404))
|
||||
previous = set(before.get('data', {}).get('keys', []))
|
||||
response = client.request('POST', 'pki/intermediate/generate/internal', {
|
||||
'common_name': 'MTUSI-Lab7-Intermediate-' + str(generation),
|
||||
'key_type': 'ec', 'key_bits': 256,
|
||||
}, token)
|
||||
csr = response.get('data', {}).get('csr')
|
||||
if not csr:
|
||||
raise OperationError('OpenBao did not return an intermediate CSR')
|
||||
directory = self.root_dir(generation)
|
||||
atomic_write(directory / 'intermediate.csr', csr)
|
||||
atomic_write(directory / 'intermediate.cnf', '''[intermediate]
|
||||
basicConstraints=critical,CA:TRUE,pathlen:0
|
||||
keyUsage=critical,keyCertSign,cRLSign
|
||||
subjectKeyIdentifier=hash
|
||||
authorityKeyIdentifier=keyid,issuer
|
||||
''')
|
||||
self.env.run(['openssl', 'ca', '-batch', '-notext', '-days', '365',
|
||||
'-config', str(directory / 'openssl.cnf'),
|
||||
'-extfile', str(directory / 'intermediate.cnf'), '-extensions', 'intermediate',
|
||||
'-in', str(directory / 'intermediate.csr'), '-out', str(directory / 'intermediate.crt')])
|
||||
imported = client.request('POST', 'pki/intermediate/set-signed', {
|
||||
'certificate': (directory / 'intermediate.crt').read_text() + (directory / 'ca.crt').read_text(),
|
||||
}, token)
|
||||
issuers = imported.get('data', {}).get('imported_issuers', [])
|
||||
if not issuers:
|
||||
after = client.request('LIST', 'pki/issuers', token=token)
|
||||
issuers = list(set(after['data']['keys']) - previous)
|
||||
expected = (directory / 'intermediate.crt').read_text().strip()
|
||||
matching = []
|
||||
for candidate in issuers:
|
||||
record = client.request('GET', 'pki/issuer/' + candidate, token=token)
|
||||
if record.get('data', {}).get('certificate', '').strip() == expected:
|
||||
matching.append(candidate)
|
||||
if len(matching) != 1:
|
||||
raise OperationError('cannot identify imported intermediate issuer')
|
||||
self.state['issuers'][str(generation)] = matching[0]
|
||||
self.save()
|
||||
return matching[0]
|
||||
|
||||
def provision(self, client: BaoClient, token: str) -> None:
|
||||
mounts = client.request('GET', 'sys/mounts', token=token)
|
||||
mounts = mounts.get('data', mounts)
|
||||
if 'pki/' not in mounts:
|
||||
client.request('POST', 'sys/mounts/pki', {
|
||||
'type': 'pki', 'config': {'max_lease_ttl': '8760h'},
|
||||
}, token)
|
||||
issuer = self.create_intermediate(client, token, self.state['active_root'])
|
||||
client.request('POST', 'pki/config/issuers', {'default': issuer}, token)
|
||||
client.request('POST', 'pki/config/urls', {
|
||||
'issuing_certificates': ['https://openbao:8200/v1/pki/ca'],
|
||||
'crl_distribution_points': ['https://openbao:8200/v1/pki/crl'],
|
||||
}, token)
|
||||
client.request('POST', 'pki/config/crl', {
|
||||
'expiry': '72h', 'auto_rebuild': True, 'auto_rebuild_grace_period': '24h',
|
||||
}, token, allowed=(200, 204, 404))
|
||||
for role, domains in ROLES.items():
|
||||
client.request('POST', 'pki/roles/' + role, {
|
||||
'allowed_domains': domains, 'allow_bare_domains': True,
|
||||
'allow_subdomains': False, 'allow_glob_domains': False,
|
||||
'allow_wildcard_certificates': False,
|
||||
'allow_localhost': 'localhost' in domains,
|
||||
'allow_ip_sans': False,
|
||||
'allowed_uri_sans': ['spiffe://mtusi/' + role],
|
||||
'key_type': 'ec', 'key_bits': 256, 'ttl': '1h', 'max_ttl': '1h',
|
||||
'server_flag': True, 'client_flag': True, 'issuer_ref': 'default',
|
||||
}, token)
|
||||
|
||||
def crl_remaining(self, crl: str) -> float:
|
||||
result = self.env.run(['openssl', 'crl', '-noout', '-nextupdate'], data=crl, check=False)
|
||||
if result.returncode:
|
||||
return -1
|
||||
try:
|
||||
stamp = result.stdout.strip().split('=', 1)[1]
|
||||
return ssl.cert_time_to_seconds(stamp) - time.time()
|
||||
except (IndexError, ValueError):
|
||||
return -1
|
||||
|
||||
def sync_crls(self, client: BaoClient, token: str) -> int:
|
||||
for generation in self.state['trust_roots']:
|
||||
self.create_root(generation)
|
||||
issuer = self.state['issuers'].get(str(generation))
|
||||
if issuer:
|
||||
crl = client.request('GET', 'pki/issuer/' + issuer + '/crl/pem',
|
||||
token=token, raw=True)
|
||||
if self.crl_remaining(crl) < 86400:
|
||||
client.request('POST', 'pki/issuer/' + issuer + '/crl/rotate', {},
|
||||
token=token, allowed=(200, 204, 403, 404, 405))
|
||||
crl = client.request('GET', 'pki/issuer/' + issuer + '/crl/pem',
|
||||
token=token, raw=True)
|
||||
if self.crl_remaining(crl) < 86400:
|
||||
raise OperationError('intermediate CRL remains inside its 24h margin')
|
||||
atomic_write(self.root_dir(generation) / 'intermediate.crl', crl)
|
||||
client.request('POST', 'auth/cert/crls/intermediate-' + str(generation),
|
||||
{'crl': crl}, token)
|
||||
root_crl = (self.root_dir(generation) / 'ca.crl').read_text()
|
||||
client.request('POST', 'auth/cert/crls/root-' + str(generation), {'crl': root_crl}, token)
|
||||
republished = 0
|
||||
for role in list(ROLES) + ['wrong-identity', 'untrusted', 'next-lb']:
|
||||
if self.env.identity(role).exists():
|
||||
snapshot = self.env.snapshot(role)
|
||||
self.env.publish(role, snapshot['tls.crt'], snapshot['tls.key'],
|
||||
self.bundle(), self.cached_crls())
|
||||
republished += 1
|
||||
return republished
|
||||
|
||||
def issue(self, role: str, ttl: str = '1h', *, service_auth: bool = False,
|
||||
issuer: str | None = None) -> dict:
|
||||
if role not in ROLES:
|
||||
raise OperationError('unknown PKI role')
|
||||
client = BaoClient(self.env, role if service_auth else 'operator')
|
||||
token = client.login()
|
||||
path = 'pki/issue/' + role
|
||||
if issuer:
|
||||
if service_auth:
|
||||
raise OperationError('service cannot override its allowed issuer path')
|
||||
path = 'pki/issuer/' + issuer + '/issue/' + role
|
||||
response = client.request('POST', path, {
|
||||
'common_name': role, 'alt_names': ','.join(ROLES[role][1:]),
|
||||
'uri_sans': 'spiffe://mtusi/' + role, 'ttl': ttl,
|
||||
}, token)
|
||||
data = response.get('data', {})
|
||||
certificate = data.get('certificate', '')
|
||||
private_key = data.get('private_key', '')
|
||||
if not certificate or not private_key:
|
||||
raise OperationError('OpenBao did not issue a complete leaf identity')
|
||||
chain = '\n'.join(part.strip() for part in [certificate, *data.get('ca_chain', [])]) + '\n'
|
||||
description = self.env.publish(role, chain, private_key,
|
||||
self.bundle(), self.cached_crls())
|
||||
archive = self.env.state / 'issued'
|
||||
archive.mkdir(exist_ok=True, mode=0o700)
|
||||
atomic_write(archive / (description['serial_number'] + '.crt'), certificate)
|
||||
return description
|
||||
|
||||
def renew_watch(self, role: str, ttl: str, interval: float, on_issued=None) -> None:
|
||||
if not 0 < interval <= 1:
|
||||
raise OperationError('leaf watchdog interval must be in (0, 1] seconds')
|
||||
result = self.issue(role, ttl, service_auth=True)
|
||||
if on_issued is not None:
|
||||
on_issued(role)
|
||||
print(json.dumps(result), flush=True)
|
||||
expiry = ssl.cert_time_to_seconds(result['not_after'])
|
||||
next_renewal = time.time() + max(1, (expiry - time.time()) / 2)
|
||||
while True:
|
||||
now = time.time()
|
||||
if now >= expiry - 1:
|
||||
raise OperationError('leaf renewal did not complete before certificate deadline')
|
||||
if now >= next_renewal:
|
||||
try:
|
||||
result = self.issue(role, ttl, service_auth=True)
|
||||
if on_issued is not None:
|
||||
on_issued(role)
|
||||
except OperationError as error:
|
||||
print(json.dumps({'role': role, 'renewal_error': str(error)}), flush=True)
|
||||
time.sleep(interval)
|
||||
continue
|
||||
print(json.dumps(result), flush=True)
|
||||
expiry = ssl.cert_time_to_seconds(result['not_after'])
|
||||
next_renewal = time.time() + max(1, (expiry - time.time()) / 2)
|
||||
time.sleep(interval)
|
||||
|
||||
def revoke(self, role: str, serial: str) -> dict:
|
||||
normalized = serial.replace(':', '').replace('-', '').lower()
|
||||
if not normalized or any(ch not in '0123456789abcdef' for ch in normalized):
|
||||
raise OperationError('invalid public certificate serial')
|
||||
client = BaoClient(self.env)
|
||||
token = client.login()
|
||||
formatted = ':'.join(normalized[index:index + 2] for index in range(0, len(normalized), 2))
|
||||
client.request('POST', 'pki/revoke', {'serial_number': formatted}, token)
|
||||
# auto_rebuild only refreshes an expired CRL; a fresh revocation must
|
||||
# be published now, before the old identity can be retried. OpenBao
|
||||
# exposes rotation as GET /pki/crl/rotate (POST is 405 here).
|
||||
client.request('GET', 'pki/crl/rotate', token=token)
|
||||
self.sync_crls(client, token)
|
||||
return {'role': role, 'revoked_serial': normalized, 'crls_updated': True, 'crl_rotated': True}
|
||||
|
||||
def prepare_rollover(self) -> dict:
|
||||
if self.state.get('next_root'):
|
||||
return {'phase': 'prepare', 'next_root': self.state['next_root']}
|
||||
generation = self.state['active_root'] + 1
|
||||
self.create_root(generation)
|
||||
client = BaoClient(self.env)
|
||||
token = client.login()
|
||||
self.create_intermediate(client, token, generation)
|
||||
self.state['next_root'] = generation
|
||||
self.state['trust_roots'].append(generation)
|
||||
self.save()
|
||||
# sync_crls publishes the overlap bundle to every role before issue:
|
||||
# clients and native services trust the next root before new leaves.
|
||||
republished = self.sync_crls(client, token)
|
||||
certificate, key = self.offline_leaf('next-lb', generation, common_name='lb', uri_role='lb')
|
||||
self.env.publish('next-lb', certificate, key, self.bundle(), self.cached_crls())
|
||||
return {'phase': 'prepare', 'next_root': generation, 'identities_republished': republished}
|
||||
|
||||
def switch_issuer(self) -> dict:
|
||||
generation = self.state.get('next_root')
|
||||
if not generation:
|
||||
raise OperationError('prepare CA overlap before switching issuance')
|
||||
client = BaoClient(self.env)
|
||||
token = client.login()
|
||||
client.request('POST', 'pki/config/issuers', {
|
||||
'default': self.state['issuers'][str(generation)],
|
||||
}, token)
|
||||
self.state['previous_root'] = self.state['active_root']
|
||||
self.state['active_root'] = generation
|
||||
self.save()
|
||||
leaves = [self.issue(role) for role in ROLES]
|
||||
# Keep the same-CA rogue identity fixture meaningful after the switch:
|
||||
# otherwise it would be rejected as unknown CA instead of bad identity.
|
||||
if self.env.identity('wrong-identity').exists():
|
||||
certificate, key = self.offline_leaf('wrong-identity', generation,
|
||||
common_name='lb', uri_role='rogue')
|
||||
self.env.publish('wrong-identity', certificate, key, self.bundle(), self.cached_crls())
|
||||
return {'phase': 'issue', 'active_root': generation, 'leaves': leaves}
|
||||
|
||||
def certificate_name(self, path: Path, field: str) -> str:
|
||||
output = self.env.run(['openssl', 'x509', '-in', str(path), '-noout',
|
||||
'-' + field, '-nameopt', 'RFC2253']).stdout.strip()
|
||||
return output.split('=', 1)[1] if '=' in output else output
|
||||
|
||||
def retire_issuer(self) -> dict:
|
||||
previous = self.state.get('previous_root')
|
||||
if not previous:
|
||||
raise OperationError('switch issuance before retiring old CA')
|
||||
root_dir = self.root_dir(self.state['active_root'])
|
||||
active_issuers = {
|
||||
self.certificate_name(root_dir / 'intermediate.crt', 'subject'),
|
||||
self.certificate_name(root_dir / 'ca.crt', 'subject'),
|
||||
}
|
||||
for role in list(ROLES) + ['wrong-identity']:
|
||||
current = self.env.identity(role)
|
||||
if not current.exists():
|
||||
continue
|
||||
if self.certificate_name(current / 'tls.crt', 'issuer') not in active_issuers:
|
||||
raise OperationError('retire blocked: leaf is not from the active issuer: ' + role)
|
||||
client = BaoClient(self.env)
|
||||
token = client.login()
|
||||
self.state['trust_roots'] = [self.state['active_root']]
|
||||
self.state.pop('next_root', None)
|
||||
self.save()
|
||||
# sync_crls re-publishes every identity with the retired trust set:
|
||||
# the leaf stays, but the old root and its CRL disappear from mounts.
|
||||
republished = self.sync_crls(client, token)
|
||||
# Old auth CRLs are removed to avoid stale/cross-issuer serial constraints.
|
||||
for name in ('root-' + str(previous), 'intermediate-' + str(previous)):
|
||||
client.request('DELETE', 'auth/cert/crls/' + name, token=token)
|
||||
old_issuer = self.state['issuers'].get(str(previous))
|
||||
if old_issuer:
|
||||
client.request('DELETE', 'pki/issuer/' + old_issuer, token=token)
|
||||
return {'phase': 'retire', 'retired_root': previous, 'active_root': self.state['active_root'],
|
||||
'identities_republished': republished}
|
||||
Executable
+72
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Renew short-lived role leaves and publish fresh CRLs on an interval.
|
||||
|
||||
The controller runs on the operator host next to `securityctl.py`: it needs the
|
||||
operator identity and the Docker CLI to reload native owners. It is not mounted
|
||||
into application containers. Run it under a supervisor (systemd/launchd) or as
|
||||
`make renewer` for a foreground lab session.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'scripts'))
|
||||
from lab7_environment import ROLES
|
||||
|
||||
SKIP = {'rogue'}
|
||||
|
||||
|
||||
def run(arguments: list[str]) -> tuple[bool, str]:
|
||||
result = subprocess.run([sys.executable, 'scripts/securityctl.py', *arguments],
|
||||
cwd=ROOT, capture_output=True, text=True, timeout=300)
|
||||
output = (result.stdout or result.stderr).strip()
|
||||
return result.returncode == 0, output[-600:]
|
||||
|
||||
|
||||
def cycle(ttl: str) -> dict:
|
||||
started = dt.datetime.now(dt.timezone.utc).isoformat()
|
||||
roles = {}
|
||||
for role in ROLES:
|
||||
if role in SKIP:
|
||||
continue
|
||||
ok, output = run(['renew', role, '--ttl', ttl])
|
||||
mode = 'renew'
|
||||
if not ok and 'expired' in output.lower():
|
||||
# Expiry is the only fallback: a revoked/disabled identity must
|
||||
# stay contained instead of being reissued by the operator.
|
||||
mode = 'issue'
|
||||
ok, output = run(['issue', role, '--ttl', ttl])
|
||||
roles[role] = {'ok': ok, 'mode': mode, 'output': output}
|
||||
crls_ok, crls_output = run(['sync-crls'])
|
||||
return {'timestamp': started, 'ttl': ttl, 'roles': roles,
|
||||
'crls': {'ok': crls_ok, 'output': crls_output},
|
||||
'passed': crls_ok and all(item['ok'] for item in roles.values())}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--interval', type=float, default=1800, help='seconds between cycles')
|
||||
parser.add_argument('--ttl', default='1h', help='leaf TTL requested from OpenBao')
|
||||
parser.add_argument('--once', action='store_true')
|
||||
parser.add_argument('--output', type=Path, default=None)
|
||||
args = parser.parse_args()
|
||||
while True:
|
||||
result = cycle(args.ttl)
|
||||
print(json.dumps(result, ensure_ascii=False), flush=True)
|
||||
if args.output:
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.output.write_text(json.dumps(result, indent=2, ensure_ascii=False) + '\n')
|
||||
if args.once:
|
||||
return 0 if result['passed'] else 1
|
||||
time.sleep(max(1, args.interval if result['passed'] else min(60, args.interval)))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
Executable
+108
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Pinned source/image vulnerability scans with no Docker socket in scanners."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
from lab7_environment import Environment, ROOT
|
||||
|
||||
TRIVY = 'aquasec/trivy:0.76.2@sha256:8f6bb947dbc528902e11f2f5be52f7b519f6a39d5d148f41166f2040499768fb'
|
||||
GOVULNCHECK = 'golang.org/x/vuln/cmd/govulncheck@v1.9.0'
|
||||
|
||||
|
||||
def source_messages(text: str) -> list[dict]:
|
||||
"""govulncheck emits consecutive pretty-printed JSON objects, not JSONL."""
|
||||
decoder = json.JSONDecoder()
|
||||
messages, offset = [], 0
|
||||
while offset < len(text):
|
||||
while offset < len(text) and text[offset].isspace():
|
||||
offset += 1
|
||||
if offset == len(text):
|
||||
break
|
||||
message, offset = decoder.raw_decode(text, offset)
|
||||
messages.append(message)
|
||||
return messages
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--source-only', action='store_true')
|
||||
parser.add_argument('--output', type=Path, default=ROOT / 'evidence/lab7/scans')
|
||||
args = parser.parse_args()
|
||||
output = args.output.resolve()
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
cache = ROOT / '.cache/lab7-scans'
|
||||
cache.mkdir(parents=True, exist_ok=True)
|
||||
tool = ROOT / 'bin/govulncheck'
|
||||
if not tool.exists():
|
||||
subprocess.run(['go', 'install', GOVULNCHECK], cwd=ROOT,
|
||||
env={**os.environ, 'GOBIN': str(tool.parent)}, check=True)
|
||||
source = subprocess.run([str(tool), '-json', './...'], cwd=ROOT,
|
||||
capture_output=True, text=True, timeout=300)
|
||||
messages = source_messages(source.stdout)
|
||||
(output / 'govulncheck.json').write_text(json.dumps(messages, indent=2) + '\n')
|
||||
(output / 'govulncheck-status.txt').write_text('exit=' + str(source.returncode) + '\n' + source.stderr)
|
||||
advisories = {scope: set() for scope in ('symbol', 'package', 'module')}
|
||||
for message in messages:
|
||||
finding = message.get('finding')
|
||||
if finding:
|
||||
for scope, field in (('symbol', 'function'), ('package', 'package'), ('module', 'module')):
|
||||
if any(frame.get(field) for frame in finding.get('trace', [])):
|
||||
advisories[scope].add(finding['osv'])
|
||||
summary = {'govulncheck': {
|
||||
'exit': source.returncode, 'tool': GOVULNCHECK,
|
||||
'advisories': {'symbol': sorted(advisories['symbol']),
|
||||
'package_only': sorted(advisories['package'] - advisories['symbol']),
|
||||
'module_only': sorted(advisories['module'] - advisories['package'])},
|
||||
}, 'images': []}
|
||||
environment = Environment()
|
||||
if not args.source_only:
|
||||
images = sorted(set(environment.compose('config', '--images').stdout.split()))
|
||||
for index, image in enumerate(images):
|
||||
archive = cache / ('image-' + uuid.uuid4().hex + '.tar')
|
||||
subprocess.run(['docker', 'image', 'save', '--output', str(archive), image],
|
||||
cwd=ROOT, check=True, timeout=300)
|
||||
filename = f'image-{index:02d}.json'
|
||||
(output / filename).unlink(missing_ok=True)
|
||||
try:
|
||||
scan = subprocess.run([
|
||||
'docker', 'run', '--rm', '--cap-drop', 'ALL',
|
||||
'--security-opt', 'no-new-privileges:true',
|
||||
'--mount', f'type=bind,source={cache},target=/cache',
|
||||
'--mount', f'type=bind,source={output},target=/reports',
|
||||
TRIVY, 'image', '--input', '/cache/' + archive.name, '--cache-dir', '/cache/trivy',
|
||||
'--scanners', 'vuln', '--format', 'json', '--output', '/reports/' + filename,
|
||||
'--timeout', '5m',
|
||||
], cwd=ROOT, capture_output=True, text=True, timeout=330)
|
||||
(output / f'image-{index:02d}-status.txt').write_text(
|
||||
'exit=' + str(scan.returncode) + '\n' + scan.stdout + scan.stderr)
|
||||
counts = {}
|
||||
if scan.returncode == 0 and (output / filename).exists():
|
||||
report = json.loads((output / filename).read_text())
|
||||
for result in report.get('Results', []):
|
||||
for finding in result.get('Vulnerabilities') or []:
|
||||
severity = finding.get('Severity', 'UNKNOWN')
|
||||
counts[severity] = counts.get(severity, 0) + 1
|
||||
summary['images'].append({'image': image, 'exit': scan.returncode,
|
||||
'file': filename, 'counts': counts})
|
||||
print(json.dumps(summary['images'][-1]), flush=True)
|
||||
finally:
|
||||
archive.unlink(missing_ok=True)
|
||||
summary['trivy'] = TRIVY
|
||||
(output / 'summary.json').write_text(json.dumps(summary, indent=2) + '\n')
|
||||
print(json.dumps(summary), flush=True)
|
||||
return 0 if source.returncode in (0, 3) and all(item['exit'] == 0 for item in summary['images']) else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except (OSError, subprocess.SubprocessError, json.JSONDecodeError) as error:
|
||||
print('SCAN FAILED: ' + str(error), file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
Executable
+594
@@ -0,0 +1,594 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Repeatable destructive PKI study, restricted to fresh local synthetic projects.
|
||||
|
||||
python3 scripts/lab7_track2.py --reps 3 --duration 30 --output evidence/lab7/track2.json
|
||||
|
||||
Each repetition creates its own mtusi-lab7-track2-* Compose project, volumes,
|
||||
loopback ports and operator state outside checkout; cleanup removes only that
|
||||
project. Existing projects/volumes are never stopped or mutated. Images must
|
||||
already exist: all application recreation uses --no-build. One stable HTTPS
|
||||
client continuously POSTs messages; these total-expiry phases are NOT failover.
|
||||
Requires securityctl bootstrap/up/issue/renew --watch/revoke/rotate-secret/
|
||||
ca-rollover/audit-summary and automatic complete trust/CRL consumer reloads.
|
||||
"""
|
||||
import argparse
|
||||
import collections
|
||||
import concurrent.futures
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
sys.path.insert(0, str(ROOT / 'student-tests'))
|
||||
from client import Client, Failure
|
||||
from lab7_helpers import Stand, ProbeFailure, command, require, http, temporary_directory
|
||||
from lab7_security import isolation
|
||||
|
||||
|
||||
def percentile(values, fraction):
|
||||
if not values:
|
||||
return None
|
||||
ordered = sorted(values)
|
||||
return ordered[min(len(ordered) - 1, int((len(ordered) - 1) * fraction))]
|
||||
|
||||
|
||||
def certificate(path):
|
||||
result = command(['openssl', 'x509', '-in', str(path), '-noout', '-serial', '-enddate', '-issuer'])
|
||||
fields = dict(line.split('=', 1) for line in result.stdout.splitlines() if '=' in line)
|
||||
require('serial' in fields and 'notAfter' in fields, 'certificate_metadata_missing')
|
||||
expires = dt.datetime.strptime(fields['notAfter'], '%b %d %H:%M:%S %Y %Z').replace(tzinfo=dt.timezone.utc)
|
||||
return {'serial_number': fields['serial'].upper(), 'not_after': expires.isoformat(),
|
||||
'expires_unix': expires.timestamp(), 'issuer': fields.get('issuer')}
|
||||
|
||||
|
||||
def current_api_certificate(stand):
|
||||
directory = stand.secrets / 'pki/api'
|
||||
version = (directory / 'current-version').read_text().strip()
|
||||
require(version and version not in ('.', '..') and Path(version).name == version,
|
||||
'invalid_api_version_selector')
|
||||
return certificate(directory / 'versions' / version / 'tls.crt')
|
||||
|
||||
|
||||
def snapshot(stand, role, directory):
|
||||
destination = Path(directory) / role
|
||||
destination.mkdir(mode=0o700)
|
||||
current = destination / 'current'
|
||||
current.mkdir(mode=0o700)
|
||||
for name in ('tls.crt', 'tls.key', 'ca.crt', 'ca.crl'):
|
||||
shutil.copyfile(stand.secrets / 'pki' / role / 'current' / name, current / name)
|
||||
(current / name).chmod(0o600)
|
||||
return destination
|
||||
|
||||
|
||||
def until(predicate, deadline=90, classification='recovery_deadline_exceeded'):
|
||||
end = time.monotonic() + deadline
|
||||
while time.monotonic() < end:
|
||||
try:
|
||||
result = predicate()
|
||||
if result:
|
||||
return result
|
||||
except (ProbeFailure, Failure, OSError):
|
||||
pass
|
||||
time.sleep(0.2)
|
||||
raise ProbeFailure(classification)
|
||||
|
||||
|
||||
class Load:
|
||||
"""A single bounded closed-loop HTTPS load client with stable actors."""
|
||||
def __init__(self, base, ca, actor, chat, rate, started=None):
|
||||
self.client = Client(base, str(ca), timeout=3)
|
||||
self.actor, self.chat, self.rate = actor, chat, rate
|
||||
self.stop = threading.Event()
|
||||
self.lock = threading.Lock()
|
||||
self.phase = 'baseline'
|
||||
self.started = started if started is not None else time.monotonic()
|
||||
self.samples = []
|
||||
self.thread = threading.Thread(target=self.run, daemon=True)
|
||||
|
||||
def set_phase(self, phase):
|
||||
with self.lock:
|
||||
self.phase = phase
|
||||
|
||||
def run(self):
|
||||
count = 0
|
||||
while not self.stop.is_set():
|
||||
started = time.monotonic()
|
||||
with self.lock:
|
||||
phase = self.phase
|
||||
try:
|
||||
result = self.client.message(self.actor, self.chat, 'lab7-load-' + str(count))
|
||||
status, error = result['status'], None
|
||||
except Failure as exc:
|
||||
# Client messages omit bodies/credentials; retain only status or
|
||||
# a fixed exception category, never arbitrary error text.
|
||||
text = str(exc)
|
||||
status = int(text.rsplit('received ', 1)[1]) if 'received ' in text and text.rsplit('received ', 1)[1].isdigit() else None
|
||||
error = 'http_' + str(status) if status else 'connection_or_tls'
|
||||
except Exception:
|
||||
status, error = None, 'client_exception'
|
||||
sample = {'at_seconds': round(started - self.started, 6), 'phase': phase,
|
||||
'latency_seconds': round(time.monotonic() - started, 6), 'status': status, 'error': error}
|
||||
with self.lock:
|
||||
self.samples.append(sample)
|
||||
count += 1
|
||||
self.stop.wait(max(0, 1 / self.rate - (time.monotonic() - started)))
|
||||
|
||||
def close(self):
|
||||
self.stop.set()
|
||||
self.thread.join(timeout=8)
|
||||
require(not self.thread.is_alive(), 'load_client_shutdown_timeout')
|
||||
|
||||
def refresh_trust(self, ca):
|
||||
# Only the load thread uses self.client; pointer swap retains actor/token
|
||||
# and creates a fresh CA-verified opener after trust-store publication.
|
||||
self.client = Client(self.client.base, str(ca), timeout=3)
|
||||
|
||||
def summary(self):
|
||||
with self.lock:
|
||||
samples = list(self.samples)
|
||||
phases = {}
|
||||
for name in dict.fromkeys(s['phase'] for s in samples):
|
||||
selected = [s for s in samples if s['phase'] == name]
|
||||
successes = [s for s in selected if s['status'] == 201]
|
||||
elapsed = max(0.001, selected[-1]['at_seconds'] + selected[-1]['latency_seconds'] - selected[0]['at_seconds'])
|
||||
failures = [s for s in selected if s['error']]
|
||||
phases[name] = {'requests': len(selected), 'successes': len(successes), 'errors': len(failures),
|
||||
'elapsed_seconds': elapsed, 'rps': len(successes) / elapsed,
|
||||
'p50_seconds': percentile([s['latency_seconds'] for s in successes], 0.50),
|
||||
'p95_seconds': percentile([s['latency_seconds'] for s in successes], 0.95),
|
||||
'errors_by_class': dict(collections.Counter(s['error'] for s in failures)),
|
||||
'failed_span_seconds': failures[-1]['at_seconds'] - failures[0]['at_seconds'] if failures else 0}
|
||||
outages = []
|
||||
began = None
|
||||
for sample in samples:
|
||||
if sample['error'] and began is None:
|
||||
began = sample
|
||||
if not sample['error'] and began is not None:
|
||||
outages.append({'phase_started': began['phase'], 'start_seconds': began['at_seconds'],
|
||||
'recovered_seconds': sample['at_seconds'],
|
||||
'observed_outage_seconds': sample['at_seconds'] - began['at_seconds'],
|
||||
'recovery_request_latency_seconds': sample['latency_seconds']})
|
||||
began = None
|
||||
if began is not None:
|
||||
outages.append({'phase_started': began['phase'], 'start_seconds': began['at_seconds'],
|
||||
'recovered_seconds': None, 'observed_outage_seconds': samples[-1]['at_seconds'] - began['at_seconds']})
|
||||
return {'phases': phases, 'raw_samples': samples, 'observed_outage_windows': outages,
|
||||
'outage_measurement': 'Failure-to-next-success sampling windows; resolution is the actual closed-loop request cadence.'}
|
||||
|
||||
|
||||
def free_ports(count):
|
||||
sockets = []
|
||||
try:
|
||||
for _ in range(count):
|
||||
sock = socket.socket()
|
||||
sock.bind(('127.0.0.1', 0))
|
||||
sockets.append(sock)
|
||||
return [sock.getsockname()[1] for sock in sockets]
|
||||
finally:
|
||||
for sock in sockets:
|
||||
sock.close()
|
||||
|
||||
|
||||
def isolated_stand(directory, run_number):
|
||||
root = Path(directory)
|
||||
project = 'mtusi-lab7-track2-' + str(run_number) + '-' + uuid.uuid4().hex[:10]
|
||||
ingress, s3, bao, grafana, prometheus, loki, tempo, broker, stats = free_ports(9)
|
||||
env = {'OTEL_TRACES_SAMPLER': 'always_on', 'LAB7_OPERATOR_STATE': str(root / 'operator'),
|
||||
'BAO_PORT': str(bao), 'GRAFANA_PORT': str(grafana), 'PUBLIC_PORT': str(ingress), 'S3_PORT': str(s3),
|
||||
'PROMETHEUS_PORT': str(prometheus), 'LOKI_PORT': str(loki), 'TEMPO_PORT': str(tempo),
|
||||
'BROKER_MANAGEMENT_PORT': str(broker), 'LB_STATS_PORT': str(stats)}
|
||||
stand = Stand(project, root / 'secrets', 'https://localhost:' + str(ingress), env)
|
||||
override = root / 'compose-study.yaml'
|
||||
# Compose ports !override prevents the normal fixed loopback ports merging.
|
||||
# Namespace consumers do not receive ports; publication belongs to owners.
|
||||
owners = ('lb', 'seaweedfs', 'openbao', 'grafana', 'prometheus', 'loki', 'tempo', 'broker', 'otel-collector')
|
||||
mappings = {'lb': [f'127.0.0.1:{ingress}:8443'], 'seaweedfs': [f'127.0.0.1:{s3}:8333'],
|
||||
'openbao': [f'127.0.0.1:{bao}:8200'], 'grafana': [f'127.0.0.1:{grafana}:3000']}
|
||||
lines = ['services:']
|
||||
for owner in owners:
|
||||
lines += [' ' + owner + ':', ' ports: !override ' + json.dumps(mappings.get(owner, []))]
|
||||
for service in ('api', 'worker', 'relay'):
|
||||
lines += [' ' + service + ':', ' environment:', ' OTEL_TRACES_SAMPLER: "always_on"']
|
||||
override.write_text('\n'.join(lines) + '\n')
|
||||
stand.overrides.append(override)
|
||||
# securityctl subprocess Compose invocations must consume the same override.
|
||||
stand.env['LAB7_COMPOSE_OVERRIDE'] = str(override)
|
||||
return stand
|
||||
|
||||
|
||||
def server_serial(stand):
|
||||
result = stand.probe('tls', roles=('lb',), config={'host': 'api-replica', 'port': 8080, 'role': 'lb'})
|
||||
require(result.get('status') == 200 and result.get('serial'), 'fresh_api_tls_control_failed')
|
||||
return result['serial'].replace(':', '').upper()
|
||||
|
||||
|
||||
def api_ready(stand, ca):
|
||||
parsed = urllib.parse.urlsplit(stand.base_url)
|
||||
return http('localhost', parsed.port, 'GET', '/health/ready', ca=str(ca))['status'] == 200
|
||||
|
||||
|
||||
def retained(client, actor, chat, sentinel, attachment, content):
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=100'
|
||||
found = False
|
||||
seen = set()
|
||||
for _ in range(100):
|
||||
page = client.call('GET', path, actor=actor, schema='MessagePage')['json']
|
||||
if any(m['id'] == sentinel['id'] and m['text'] == sentinel['text'] for m in page['items']):
|
||||
found = True
|
||||
break
|
||||
cursor = page['next_cursor']
|
||||
if cursor is None:
|
||||
break
|
||||
require(cursor not in seen, 'persisted_history_cursor_loop')
|
||||
seen.add(cursor)
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=100&cursor=' + urllib.parse.quote(cursor, safe='')
|
||||
require(found, 'persisted_message_sentinel_missing')
|
||||
got = client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=actor)['bytes']
|
||||
require(hashlib.sha256(got).digest() == hashlib.sha256(content).digest(), 'persisted_attachment_sentinel_changed')
|
||||
return {'user_id': actor['id'], 'chat_id': chat['id'], 'message_id': sentinel['id'], 'attachment_id': attachment['id'],
|
||||
'attachment_sha256': hashlib.sha256(content).hexdigest()}
|
||||
|
||||
|
||||
def resume_negative(stand, identity, mutate, control_root, expect_detail=''):
|
||||
control = Path(control_root)
|
||||
control.mkdir(mode=0o700)
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
|
||||
future = pool.submit(stand.probe, 'session', roles=('operator',),
|
||||
config={'role': 'oldlb', 'host': 'api-replica', 'port': 8080, 'wait_seconds': 480},
|
||||
extra_mounts=((identity, '/pki/oldlb'),), control_dir=control, timeout=540)
|
||||
try:
|
||||
until(lambda: (control / 'armed').exists() or (future.done() and future.result()), deadline=45,
|
||||
classification='resumption_probe_not_armed')
|
||||
mutate()
|
||||
finally:
|
||||
(control / 'proceed').write_text('go')
|
||||
result = future.result(timeout=240)
|
||||
require(all(x['classification'] == 'tls_certificate_rejected' for x in result['after']),
|
||||
'old_identity_fresh_or_resumed_accepted')
|
||||
if expect_detail:
|
||||
require(all(expect_detail.upper() in (x.get('detail') or '').upper() for x in result['after']),
|
||||
'old_identity_rejected_for_unexpected_reason', expect_detail)
|
||||
return result
|
||||
|
||||
|
||||
def run_study(args, repetition, directory):
|
||||
stand = isolated_stand(directory, repetition)
|
||||
ca = stand.secrets / 'pki/operator/current/ca.crt'
|
||||
actions, errors = [], []
|
||||
load, watcher = None, None
|
||||
started = time.monotonic()
|
||||
started_at = dt.datetime.now(dt.timezone.utc).isoformat()
|
||||
stage = 'start'
|
||||
|
||||
def mark(name):
|
||||
nonlocal stage
|
||||
stage = name
|
||||
|
||||
def action(name, fn):
|
||||
nonlocal stage
|
||||
stage = name
|
||||
before = time.monotonic()
|
||||
if load:
|
||||
load.set_phase(name)
|
||||
result = fn()
|
||||
actions.append({'phase': name, 'at_seconds': before - started, 'seconds': time.monotonic() - before, 'result': result or {}})
|
||||
return result
|
||||
try:
|
||||
# No image build, and never bootstrap an existing project/namespace.
|
||||
require(not stand.containers(), 'isolated_project_already_exists')
|
||||
action('bootstrap', lambda: stand.security('bootstrap', timeout=300))
|
||||
action('startup', lambda: stand.security('up', timeout=360))
|
||||
stand.compose('up', '-d', '--no-build', '--scale', 'api=2', timeout=240)
|
||||
until(lambda: api_ready(stand, ca), deadline=120)
|
||||
client = Client(stand.base_url, str(ca), timeout=5)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
attachment, content = client.attachment(alice, chat)
|
||||
attachment = client.wait_ready(alice, attachment, wait_seconds=120)
|
||||
sentinel = client.message(alice, chat, 'lab7-persisted-' + uuid.uuid4().hex)['json']
|
||||
image_ids = sorted(c['Image'] for c in stand.containers('api') + stand.containers('worker'))
|
||||
action('initial_native_tls_control', lambda: {'serial_number': server_serial(stand)})
|
||||
action('initial_namespace_isolation', lambda: isolation(stand))
|
||||
load = Load(stand.base_url, ca, alice, chat, args.rate, started=started)
|
||||
load.thread.start()
|
||||
action('baseline', lambda: time.sleep(args.duration))
|
||||
baseline = load.summary()['phases'].get('baseline', {})
|
||||
require(baseline.get('successes', 0) > 0 and baseline.get('errors', 0) == 0, 'baseline_not_healthy')
|
||||
|
||||
def renewal():
|
||||
nonlocal watcher
|
||||
stand.security('issue', 'api', '--ttl', '20s')
|
||||
original = current_api_certificate(stand)
|
||||
old_expiry = original['expires_unix']
|
||||
until(lambda: server_serial(stand) == original['serial_number'], deadline=10)
|
||||
# Start independent cert-auth watcher at half of remaining lifetime.
|
||||
time.sleep(max(0, (old_expiry - time.time()) / 2))
|
||||
watcher = subprocess.Popen([sys.executable, 'scripts/securityctl.py', 'renew', 'api', '--ttl', '20s', '--watch', '--interval', '1'],
|
||||
cwd=ROOT, env={**os.environ, **stand.env}, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
seen = {original['serial_number']}
|
||||
records = [original]
|
||||
end = time.monotonic() + max(60, args.duration)
|
||||
while time.monotonic() < end:
|
||||
require(watcher.poll() is None, 'leaf_renew_watcher_exited')
|
||||
current = current_api_certificate(stand)
|
||||
if current['serial_number'] not in seen:
|
||||
# A polling timestamp is not the publication timestamp.
|
||||
# Prove adoption on fresh TLS and continuity past old expiry.
|
||||
until(lambda: server_serial(stand) == current['serial_number'],
|
||||
deadline=5, classification='published_leaf_not_used_on_fresh_tls')
|
||||
seen.add(current['serial_number'])
|
||||
records.append(current)
|
||||
time.sleep(0.5)
|
||||
require(len(seen) >= 3 and time.time() > old_expiry, 'renewal_not_repeated_before_old_expiry')
|
||||
require(api_ready(stand, ca), 'api_stopped_at_old_certificate_expiry')
|
||||
return {'original_expiry': original['not_after'], 'leaf_versions': records,
|
||||
'replacement_count': len(seen) - 1, 'old_expiry_survived': True}
|
||||
action('leaf_renewal', renewal)
|
||||
require(load.summary()['phases']['leaf_renewal']['errors'] == 0, 'renewal_load_interrupted')
|
||||
|
||||
def expiry():
|
||||
nonlocal watcher
|
||||
watcher.terminate()
|
||||
try:
|
||||
watcher.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
watcher.kill()
|
||||
watcher.wait(timeout=5)
|
||||
watcher = None
|
||||
last = current_api_certificate(stand)
|
||||
before = {c['Id']: c.get('RestartCount', 0) for c in stand.containers('api')}
|
||||
time.sleep(max(0, last['expires_unix'] - time.time() + 1))
|
||||
require(not api_ready(stand, ca), 'expired_api_remains_ready')
|
||||
# The process may be in restart policy after bounded drain. A
|
||||
# restart count is evidence of exit, not a fabricated state check.
|
||||
def exited():
|
||||
state = stand.containers('api')
|
||||
return state and all(not c['State']['Running'] or c.get('RestartCount', 0) > before.get(c['Id'], 0) for c in state)
|
||||
remaining = max(0.1, last['expires_unix'] + 29 - time.time())
|
||||
until(exited, deadline=remaining, classification='expired_api_did_not_exit_within_shutdown_bound')
|
||||
time.sleep(2)
|
||||
require(not api_ready(stand, ca), 'expired_api_reopened_admission')
|
||||
return {'expired_leaf': last, 'ready_closed': True, 'bounded_process_exit': True,
|
||||
'shutdown_deadline_unix': last['expires_unix'] + 29, 'total_outage_not_failover': True}
|
||||
action('intentional_expiry', expiry)
|
||||
require(load.summary()['phases']['intentional_expiry']['errors'] > 0, 'expiry_outage_not_exercised')
|
||||
|
||||
def recover():
|
||||
before = time.monotonic()
|
||||
stand.security('issue', 'api', '--ttl', '1h')
|
||||
stand.compose('up', '-d', '--no-build', '--no-deps', '--force-recreate', '--scale', 'api=2', 'api', timeout=150)
|
||||
until(lambda: api_ready(stand, ca), deadline=90)
|
||||
return {'recovery_seconds': time.monotonic() - before, 'retained': retained(client, alice, chat, sentinel, attachment, content)}
|
||||
action('expiry_recovery', recover)
|
||||
action('recovery_control', lambda: time.sleep(args.duration))
|
||||
|
||||
def sealed_bao():
|
||||
before = time.monotonic()
|
||||
stand.security('seal')
|
||||
until(lambda: not api_ready(stand, ca), deadline=65,
|
||||
classification='sealed_bao_did_not_close_admission')
|
||||
time.sleep(2)
|
||||
require(not api_ready(stand, ca), 'sealed_bao_reopened_admission')
|
||||
return {'admission_closed_seconds': time.monotonic() - before,
|
||||
'max_authorization_freshness_seconds': 60, 'ready_closed': True}
|
||||
action('sealed_bao', sealed_bao)
|
||||
require(load.summary()['phases']['sealed_bao']['errors'] > 0, 'sealed_bao_outage_not_exercised')
|
||||
|
||||
def unseal_recovery():
|
||||
before = time.monotonic()
|
||||
stand.security('unseal')
|
||||
stand.compose('up', '-d', '--no-build', '--no-deps', 'api', 'worker', 'relay', timeout=150)
|
||||
until(lambda: api_ready(stand, ca), deadline=90)
|
||||
return {'recovery_seconds': time.monotonic() - before,
|
||||
'retained': retained(client, alice, chat, sentinel, attachment, content)}
|
||||
action('sealed_bao_recovery', unseal_recovery)
|
||||
action('unsealed_recovery_control', lambda: time.sleep(args.duration))
|
||||
require(load.summary()['phases']['unsealed_recovery_control']['errors'] == 0,
|
||||
'unsealed_bao_not_recovered')
|
||||
|
||||
def revoke():
|
||||
old = snapshot(stand, 'lb', Path(directory) / 'revoke-private')
|
||||
metadata = certificate(old / 'current/tls.crt')
|
||||
def mutation():
|
||||
stand.security('issue', 'lb', '--ttl', '1h')
|
||||
stand.security('revoke', 'lb', '--serial', metadata['serial_number'])
|
||||
result = resume_negative(stand, old, mutation, Path(directory) / 'revoke-control')
|
||||
until(lambda: api_ready(stand, ca), deadline=90)
|
||||
return {'revoked_serial': metadata['serial_number'], 'old_identity': result, 'fresh_current_serial': server_serial(stand)}
|
||||
(Path(directory) / 'revoke-private').mkdir(mode=0o700)
|
||||
action('lb_leaf_rotate_revoke', revoke)
|
||||
|
||||
def rotate_secret():
|
||||
secret_path = stand.secrets / 'backends/credentials.json'
|
||||
old = json.loads(secret_path.read_text())
|
||||
# Old material lives only in private temporary operator state; not
|
||||
# stdout, argv, image, logs, or evidence. Only worker key is copied.
|
||||
oldfile = Path(directory) / 'old-worker-credentials.json'
|
||||
oldfile.write_text(json.dumps({'s3': {'worker': old['s3']['worker']}}))
|
||||
oldfile.chmod(0o600)
|
||||
key = 'attachments/lab7-rotation-missing-' + uuid.uuid4().hex
|
||||
control = stand.probe('s3', roles=('operator',), credentials=True,
|
||||
config={'single': True, 'role': 'worker', 'key': key})
|
||||
require(control.get('status') == 404, 'old_s3_credential_control_not_authorized')
|
||||
stand.security('rotate-secret', 'worker', timeout=180)
|
||||
denied = stand.probe('s3', roles=('operator',), extra_mounts=((oldfile, '/old-credentials.json'),),
|
||||
config={'credentials': '/old-credentials.json', 'single': True, 'role': 'worker', 'key': key})
|
||||
require(denied.get('status') == 403, 'old_worker_s3_credential_not_403')
|
||||
fresh, _ = client.attachment(alice, chat)
|
||||
fresh = client.wait_ready(alice, fresh, wait_seconds=120)
|
||||
oldfile.unlink()
|
||||
return {'old_credential_status': 403, 'new_worker_attachment_id': fresh['id'], 'status': fresh['status']}
|
||||
action('worker_s3_secret_rotation', rotate_secret)
|
||||
|
||||
def warm_pipeline(phase):
|
||||
# Every CA phase restarts stores and both application identities.
|
||||
# Retry only transport cold starts; a failed attachment is a real
|
||||
# pipeline defect and must fail the run immediately.
|
||||
started = time.monotonic()
|
||||
deadline = started + 180
|
||||
errors = []
|
||||
attempts = 0
|
||||
while time.monotonic() < deadline:
|
||||
attempts += 1
|
||||
try:
|
||||
probe = Client(stand.base_url, str(ca), timeout=15)
|
||||
ready, _ = probe.attachment(alice, chat)
|
||||
probe.wait_ready(alice, ready, wait_seconds=60)
|
||||
return {'phase': phase, 'attempts': attempts,
|
||||
'seconds': round(time.monotonic() - started, 3), 'errors': errors}
|
||||
except Failure as exc:
|
||||
text = str(exc)
|
||||
errors.append(text)
|
||||
if 'attachment reached failed' in text or 'incorrect upload status' in text:
|
||||
raise ProbeFailure('attachment_pipeline_failed', phase + ':' + text[:300]) from None
|
||||
if time.monotonic() >= deadline:
|
||||
raise ProbeFailure('attachment_pipeline_not_recovered',
|
||||
phase + ':' + str(attempts) + ':' + text[:240]) from None
|
||||
time.sleep(2)
|
||||
raise ProbeFailure('attachment_pipeline_not_recovered', phase + ':' + str(attempts))
|
||||
|
||||
def rollover():
|
||||
old = snapshot(stand, 'lb', Path(directory) / 'ca-private')
|
||||
metadata = certificate(old / 'current/tls.crt')
|
||||
warm_results = []
|
||||
mark('ca_prepare')
|
||||
prepare_result = stand.security('ca-rollover', '--phase', 'prepare', timeout=300)
|
||||
load.refresh_trust(ca)
|
||||
warm_results.append(warm_pipeline('prepare'))
|
||||
mark('ca_overlap_probe')
|
||||
old_control = stand.probe('tls', roles=('operator',), extra_mounts=((old, '/pki/oldlb'),),
|
||||
config={'role': 'oldlb', 'host': 'api-replica', 'port': 8080, 'ca': '/pki/operator/current/ca.crt'})
|
||||
require(old_control.get('status') == 200, 'overlap_old_identity_not_valid')
|
||||
mark('ca_issue')
|
||||
issue_result = stand.security('ca-rollover', '--phase', 'issue', timeout=360)
|
||||
warm_results.append(warm_pipeline('issue'))
|
||||
load.refresh_trust(ca)
|
||||
mark('ca_new_replica_probe')
|
||||
new_control = server_serial(stand)
|
||||
again = stand.probe('tls', roles=('operator',), extra_mounts=((old, '/pki/oldlb'),),
|
||||
config={'role': 'oldlb', 'host': 'api-replica', 'port': 8080, 'ca': '/pki/operator/current/ca.crt'})
|
||||
require(again.get('status') == 200, 'overlap_old_identity_lost_before_retire')
|
||||
mark('ca_retire')
|
||||
retire_result = {}
|
||||
|
||||
def retire():
|
||||
retire_result.update(stand.security('ca-rollover', '--phase', 'retire', timeout=360))
|
||||
|
||||
result = resume_negative(stand, old, retire, Path(directory) / 'ca-control',
|
||||
expect_detail='UNKNOWN_CA')
|
||||
load.refresh_trust(ca)
|
||||
mark('ca_retire_ready')
|
||||
until(lambda: api_ready(stand, ca), deadline=120)
|
||||
warm_results.append(warm_pipeline('retire'))
|
||||
mark('ca_attachment')
|
||||
current = Client(stand.base_url, str(ca), timeout=10)
|
||||
fresh, _ = current.attachment(alice, chat)
|
||||
fresh = current.wait_ready(alice, fresh, wait_seconds=120)
|
||||
mark('ca_backends')
|
||||
bao = stand.probe('bao', roles=('api',), config={'role': 'api'})
|
||||
redis = stand.probe('redis', roles=('api',), credentials=True, config={'role': 'api'})
|
||||
mark('ca_telemetry')
|
||||
telemetry = {}
|
||||
for name, host, port, role, method, path, body in (
|
||||
('api_otlp', 'otel-collector', 4318, 'api', 'POST', '/v1/traces', '{}'),
|
||||
('grafana_prometheus', 'prometheus', 9090, 'grafana', 'GET', '/api/v1/query?query=1', ''),
|
||||
('grafana_loki', 'loki', 3100, 'grafana', 'GET', '/loki/api/v1/query?query=vector%281%29', ''),
|
||||
('prometheus_collector_scrape', 'otel-collector', 8888, 'prometheus', 'GET', '/metrics', '')):
|
||||
response = stand.probe('tls', roles=(role,), config={'host': host, 'port': port, 'role': role,
|
||||
'method': method, 'path': path, 'body': body, 'headers': {'Content-Type': 'application/json'}}, network='observability')
|
||||
require(response.get('status') == 200, 'new_ca_telemetry_path_failed', name)
|
||||
telemetry[name] = response
|
||||
mark('ca_isolation')
|
||||
namespace = isolation(stand)
|
||||
mark('ca_retained')
|
||||
return {'old_leaf_serial': metadata['serial_number'], 'overlap_old': old_control, 'overlap_new_api_serial': new_control,
|
||||
'retired_old_identity': result, 'prepare': prepare_result, 'issue': issue_result,
|
||||
'retire': retire_result, 'warm_pipeline': warm_results,
|
||||
'new_pipeline_attachment_id': fresh['id'], 'new_bao_policy': bao,
|
||||
'new_redis_cache_path': redis, 'new_telemetry_paths': telemetry, 'new_namespace_isolation': namespace,
|
||||
'retained': retained(current, alice, chat, sentinel, attachment, content)}
|
||||
(Path(directory) / 'ca-private').mkdir(mode=0o700)
|
||||
action('ca_prepare_issue_retire', rollover)
|
||||
action('final_recovery_control', lambda: time.sleep(args.duration))
|
||||
require(load.summary()['phases']['final_recovery_control']['errors'] == 0, 'new_trust_paths_not_recovered')
|
||||
require(sorted(c['Image'] for c in stand.containers('api') + stand.containers('worker')) == image_ids, 'study_rebuilt_or_changed_application_image')
|
||||
action('bao_audit', lambda: stand.security('audit-summary'))
|
||||
except ProbeFailure as exc:
|
||||
errors.append({'classification': exc.classification, 'stage': stage, 'detail': exc.detail})
|
||||
except Failure as exc:
|
||||
# Public client errors deliberately omit credentials and query strings.
|
||||
errors.append({'classification': 'public_api_contract_failure', 'stage': stage, 'detail': str(exc)})
|
||||
except Exception as exc:
|
||||
errors.append({'classification': 'study_exception', 'type': type(exc).__name__})
|
||||
finally:
|
||||
if watcher and watcher.poll() is None:
|
||||
watcher.terminate()
|
||||
try:
|
||||
watcher.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
watcher.kill()
|
||||
watcher.wait(timeout=5)
|
||||
if load:
|
||||
try:
|
||||
load.close()
|
||||
except ProbeFailure as exc:
|
||||
errors.append({'classification': exc.classification})
|
||||
# Destructive cleanup is confined to this generated namespace; never
|
||||
# default stand, retained lab6 volumes, or user-supplied projects.
|
||||
require(stand.project.startswith('mtusi-lab7-track2-') and str(stand.secrets).startswith(str(Path(directory))), 'unsafe_cleanup_namespace')
|
||||
result = stand.compose('down', '--volumes', '--remove-orphans', timeout=180, check=False)
|
||||
if result.returncode:
|
||||
errors.append({'classification': 'isolated_project_cleanup_failed'})
|
||||
return {'repetition': repetition, 'project': stand.project, 'passed': not errors, 'seconds': time.monotonic() - started, 'started_at': started_at,
|
||||
'actions': actions, 'load': load.summary() if load else {'raw_samples': [], 'phases': {}}, 'errors': errors}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--reps', type=int, default=3)
|
||||
parser.add_argument('--duration', type=float, default=30, help='seconds per baseline/recovery control phase; renewal is at least60s')
|
||||
parser.add_argument('--rate', type=float, default=2, help='single-client offered messages per second')
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
require(args.reps >= 3 and args.duration >= 5 and 0 < args.rate <= 10, 'invalid_repeatability_parameters')
|
||||
runs = []
|
||||
for repetition in range(1, args.reps + 1):
|
||||
with temporary_directory(prefix='mtusi-lab7-track2-private-') as directory:
|
||||
Path(directory).chmod(0o700)
|
||||
runs.append(run_study(args, repetition, directory))
|
||||
result = {'study': 'lab7-track2', 'timestamp': dt.datetime.now(dt.timezone.utc).isoformat(), 'runs': runs,
|
||||
'completed_repetitions': len(runs), 'required_repetitions': args.reps,
|
||||
'passed': len(runs) == args.reps and all(run['passed'] for run in runs),
|
||||
'configuration': {'offered_rate': args.rate, 'control_seconds': args.duration, 'renewal_ttl_seconds': 20,
|
||||
'load_clients': 1, 'api_replicas': 2, 'trace_sampler': 'always_on', 'request_counter_sampling': 'every attempt'},
|
||||
'limitations': ['Local synthetic stand; single-node Bao/PostgreSQL/S3/broker and Docker Desktop resource limits.',
|
||||
'Single closed-loop client is a lifecycle continuity probe, not a capacity or open-loop benchmark.',
|
||||
'Both API leaves intentionally expire: this measures total-outage fail-closed recovery, not A/B failover.',
|
||||
'Fresh connections and explicit resumption attempts tested; servers with tickets disabled cannot positively resume.',
|
||||
'Temporary old keys/credentials are deleted with private operator state and never written into evidence.']}
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.output.write_text(json.dumps(result, indent=2, sort_keys=True) + '\n')
|
||||
print(json.dumps({'study': result['study'], 'passed': result['passed'], 'completed_repetitions': len(runs),
|
||||
'output': str(args.output), 'failed_repetitions': [r['repetition'] for r in runs if not r['passed']]}, sort_keys=True))
|
||||
return 0 if result['passed'] else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except ProbeFailure as exc:
|
||||
print(json.dumps({'passed': False, 'classification': exc.classification, 'detail': exc.detail}))
|
||||
raise SystemExit(1)
|
||||
except Exception as exc:
|
||||
print(json.dumps({'passed': False, 'classification': 'driver_exception', 'type': type(exc).__name__}))
|
||||
raise SystemExit(1)
|
||||
+98
-184
@@ -1,200 +1,114 @@
|
||||
#!/bin/sh
|
||||
# Проверка критерия «LB исключает неготовую реплику» (lab5).
|
||||
#
|
||||
# Рядом с рабочими репликами поднимается третья с тем же сетевым alias, но её
|
||||
# доступ к БД идёт через временный TCP-прокси. Пока прокси жив, реплика готова и
|
||||
# получает трафик через LB. После остановки прокси реплика остаётся доступной по
|
||||
# сети (процесс жив, порт открыт), но /health/ready отвечает 503 — и балансировщик
|
||||
# обязан убрать её из ротации и не отправлять ей ни одного запроса.
|
||||
#
|
||||
# scripts/lb_readiness_check.sh # стенд поднят (make up)
|
||||
# OUT=evidence/lb-readiness.txt scripts/lb_readiness_check.sh
|
||||
# Verify LB exclusion of a live API whose native TLS PostgreSQL path has failed.
|
||||
set -eu
|
||||
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
exec "${PYTHON:-python3}" - "$@" <<'PY'
|
||||
from collections import Counter
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
|
||||
# .env определяет, на каком порту публикуется LB (compose.yaml) и какие креды у
|
||||
# хранилищ, поэтому значения берём оттуда же, а не из окружения вызывающего.
|
||||
if [ -f .env ]; then
|
||||
set -a
|
||||
# shellcheck disable=SC1091
|
||||
. ./.env
|
||||
set +a
|
||||
fi
|
||||
sys.path.insert(0, str(Path.cwd() / 'scripts'))
|
||||
sys.path.insert(0, str(Path.cwd() / 'tests'))
|
||||
from lab7_environment import Environment, ROOT
|
||||
from lab7_http import BASE_URL, CA_FILE, open_url
|
||||
from client import Client
|
||||
|
||||
OUT=${OUT:-evidence/lab5/lb-readiness-detail.txt}
|
||||
PROJECT=${COMPOSE_PROJECT_NAME:-mtusi-messenger-lab6}
|
||||
NET=${PROJECT}_default
|
||||
IMAGE=${IMAGE:-mtusi-messenger:lab6}
|
||||
STATS=${STATS:-http://127.0.0.1:${LB_STATS_PORT:-8404}/stats;csv}
|
||||
BASE_URL=${BASE_URL:-http://localhost:${SERVER_PORT:-8080}}
|
||||
CANDIDATE=lb-readiness-candidate
|
||||
PROXY=lb-readiness-pgproxy
|
||||
REQUESTS=${REQUESTS:-40}
|
||||
environment = Environment()
|
||||
client = Client(BASE_URL, CA_FILE, timeout=5)
|
||||
output = Path(os.environ.get('OUT', 'evidence/lab5/lb-readiness-detail.txt'))
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
replicas = environment.compose('ps', '-q', 'api').stdout.split()
|
||||
if len(replicas) < 2:
|
||||
raise SystemExit('readiness exclusion needs two healthy Compose API replicas')
|
||||
networks = json.loads(environment.run(['docker', 'inspect', '--format',
|
||||
'{{json .NetworkSettings.Networks}}', replicas[0]]).stdout)
|
||||
if len(networks) != 1:
|
||||
raise SystemExit('expected exactly one API network for the isolated TLS tunnel')
|
||||
network = next(iter(networks))
|
||||
prefix = environment.project + '-readiness-' + uuid.uuid4().hex[:8]
|
||||
proxy, candidate = prefix + '-tunnel', prefix + '-api'
|
||||
stats_url = os.environ.get('STATS', 'https://localhost:' + environment.value('LB_STATS_PORT', '8404') + '/stats;csv')
|
||||
log = []
|
||||
|
||||
NO_PROXY_ENV="env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy"
|
||||
NO_PROXY_ENV="$NO_PROXY_ENV NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1"
|
||||
|
||||
cleanup() {
|
||||
docker rm -f "$CANDIDATE" "$PROXY" >/dev/null 2>&1 || true
|
||||
}
|
||||
def stats():
|
||||
with open_url(stats_url, operator=True) as response:
|
||||
rows = csv.DictReader(io.StringIO(response.read().decode().replace('# ', '', 1)))
|
||||
return {row['svname']: row['status'] for row in rows
|
||||
if row['pxname'].startswith('api') and row['svname'] not in ('BACKEND', 'FRONTEND')}
|
||||
|
||||
trap cleanup EXIT INT TERM
|
||||
cleanup
|
||||
|
||||
instances() {
|
||||
tries=${1:-$REQUESTS}
|
||||
i=0
|
||||
def local_status():
|
||||
result = environment.run(['docker', 'exec', candidate, 'wget', '-qO-', '-S', '-T', '3',
|
||||
'http://127.0.0.1:8084/health/ready'], check=False)
|
||||
matches = re.findall(r'HTTP/\S+\s+(\d{3})', result.stderr)
|
||||
return int(matches[-1]) if matches else None
|
||||
|
||||
while [ "$i" -lt "$tries" ]; do
|
||||
curl -fsS --noproxy '*' -D - -o /dev/null "$BASE_URL/health/live" 2>/dev/null \
|
||||
| awk 'tolower($1) == "x-instance-id:" { print $2 }'
|
||||
i=$((i + 1))
|
||||
done | sort | uniq -c
|
||||
}
|
||||
|
||||
stats() {
|
||||
curl -s --noproxy '*' "$STATS" | awk -F, '$1 ~ /^api/ { printf "%s=%s ", $2, $18 }'
|
||||
}
|
||||
def wait(predicate, description, seconds=60):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
value = predicate()
|
||||
if value:
|
||||
return value
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError(description)
|
||||
|
||||
readiness() {
|
||||
docker exec "$CANDIDATE" wget -qO- -S -T 3 http://127.0.0.1:8080/health/ready 2>&1 \
|
||||
| awk '/^ HTTP\//{print $2; exit}'
|
||||
}
|
||||
|
||||
wait_readiness() {
|
||||
want=$1
|
||||
attempt=0
|
||||
def observed():
|
||||
return Counter(client.call('GET', '/health/live', schema='Health')['headers']['X-Instance-Id']
|
||||
for _ in range(int(os.environ.get('REQUESTS', '40'))))
|
||||
|
||||
while [ "$attempt" -lt 30 ]; do
|
||||
[ "$(readiness)" = "$want" ] && return 0
|
||||
attempt=$((attempt + 1))
|
||||
sleep 1
|
||||
done
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
up_slots() {
|
||||
curl -s --noproxy '*' "$STATS" | awk -F, '$1 ~ /^api/ && $18 ~ /^UP/ && $2 != "BACKEND" { printf "%s ", $2 }'
|
||||
}
|
||||
|
||||
wait_new_up_slot() {
|
||||
before=$1
|
||||
attempt=0
|
||||
|
||||
while [ "$attempt" -lt 30 ]; do
|
||||
for slot in $(up_slots); do
|
||||
case " $before " in
|
||||
*" $slot "*) ;;
|
||||
*) echo "$slot"; return 0 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
attempt=$((attempt + 1))
|
||||
sleep 1
|
||||
done
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
wait_slot_status() {
|
||||
slot=$1
|
||||
want=$2
|
||||
attempt=0
|
||||
|
||||
while [ "$attempt" -lt 60 ]; do
|
||||
status=$(curl -s --noproxy '*' "$STATS" | awk -F, -v s="$slot" '$1 ~ /^api/ && $2 == s { print $18; exit }')
|
||||
|
||||
if [ "$status" = "$want" ]; then
|
||||
SWAIT_SECONDS=$((attempt / 2))
|
||||
return 0
|
||||
fi
|
||||
|
||||
attempt=$((attempt + 1))
|
||||
sleep 0.5
|
||||
done
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
{
|
||||
echo "# LB excludes a not-ready but reachable replica (lab5)"
|
||||
echo "# generated: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
echo "# lb: $(docker inspect -f '{{.Config.Image}}' "$(docker ps -q --filter label=com.docker.compose.service=lb)" 2>/dev/null)"
|
||||
echo
|
||||
echo "## 1. baseline: requests through LB by replica"
|
||||
instances
|
||||
baseline_slots=$(up_slots)
|
||||
echo " stats: $(stats)"
|
||||
echo
|
||||
echo "## 2. start a temporary TCP proxy to postgres and a candidate replica behind the same network alias"
|
||||
docker run -d --name "$PROXY" --network "$NET" alpine/socat@sha256:fb3862c949af7c79996d0e514ee96128644d840835ed5368eeecb14a869de361 \
|
||||
tcp-listen:5432,fork,reuseaddr tcp-connect:postgres:5432 >/dev/null
|
||||
docker run -d --name "$CANDIDATE" --network "$NET" --network-alias api-replica \
|
||||
-e APP_CONFIG=/etc/messenger/dev/config.yaml \
|
||||
-e POSTGRES_HOST="$PROXY" -e POSTGRES_PORT=5432 \
|
||||
-e POSTGRES_DATABASE="${POSTGRES_DATABASE:-messenger}" \
|
||||
-e POSTGRES_USER="${POSTGRES_USER:-messenger}" \
|
||||
-e POSTGRES_PASSWORD="${POSTGRES_PASSWORD:-messenger}" -e POSTGRES_SSL_MODE=disable \
|
||||
-e REDIS_ENABLED=true -e REDIS_HOST=redis -e CACHE_ENABLED=true \
|
||||
-e S3_ENDPOINT=http://seaweedfs:8333 -e S3_REGION="${S3_REGION:-us-east-1}" \
|
||||
-e S3_BUCKET="${S3_BUCKET:-messenger-attachments}" \
|
||||
-e S3_ACCESS_KEY_ID="${S3_ACCESS_KEY_ID:-lab4app}" \
|
||||
-e S3_SECRET_ACCESS_KEY="${S3_SECRET_ACCESS_KEY:-lab4app-secret}" \
|
||||
-e S3_USE_PATH_STYLE=true \
|
||||
"$IMAGE" >/dev/null
|
||||
|
||||
if ! wait_readiness 200; then
|
||||
echo " candidate did not become ready" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo " instance-id: $(docker inspect -f '{{.Config.Hostname}}' "$CANDIDATE"), readiness while its database is reachable: 200"
|
||||
|
||||
slot=$(wait_new_up_slot "$baseline_slots" || true)
|
||||
if [ -z "$slot" ]; then
|
||||
echo " candidate did not appear UP in the load balancer" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo " load balancer slot for the candidate: $slot, stats: $(stats)"
|
||||
echo
|
||||
echo "## 3. cut the candidate's database access (stop only the TCP proxy)"
|
||||
docker stop "$PROXY" >/dev/null
|
||||
|
||||
if ! wait_readiness 503; then
|
||||
echo " candidate readiness did not become 503" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo " candidate is still running: $(docker inspect -f '{{.State.Status}}' "$CANDIDATE"), readiness: 503"
|
||||
echo " waiting for the load balancer to mark $slot DOWN"
|
||||
|
||||
if wait_slot_status "$slot" DOWN; then
|
||||
echo " $slot went DOWN ${SWAIT_SECONDS}s after its database was cut (check: inter 2s fall 2)"
|
||||
else
|
||||
echo " FAIL: $slot is still not DOWN" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo " stats after failure: $(stats)"
|
||||
echo
|
||||
echo "## 4. ${REQUESTS} requests through LB while the candidate is not ready"
|
||||
instances
|
||||
echo " (the candidate must not appear above)"
|
||||
echo
|
||||
echo "## 5. business writes through LB during the exclusion"
|
||||
# shellcheck disable=SC2086
|
||||
$NO_PROXY_ENV python3 tests/load.py --base-url "$BASE_URL" --duration 5 --concurrency 2 \
|
||||
| grep -E '"successful_rps"|"failed_requests"|"error_ratio"'
|
||||
echo
|
||||
echo "## 6. cleanup"
|
||||
cleanup
|
||||
sleep 5
|
||||
echo " stats after cleanup: $(stats)"
|
||||
} > "$OUT" 2>&1
|
||||
|
||||
cat "$OUT"
|
||||
printf 'lb_readiness_check.sh: evidence in %s\n' "$OUT"
|
||||
with tempfile.TemporaryDirectory(prefix='lab7-readiness-') as temporary:
|
||||
try:
|
||||
baseline = stats()
|
||||
log.append('baseline instances: ' + json.dumps(observed()))
|
||||
# This network-only tunnel forwards encrypted PostgreSQL bytes unchanged.
|
||||
# It has no credentials, TLS termination, API listener or host-published ports.
|
||||
environment.run(['docker', 'run', '-d', '--name', proxy, '--network', network,
|
||||
'--cap-drop', 'ALL', '--security-opt', 'no-new-privileges:true', '--read-only',
|
||||
'alpine/socat@sha256:fb3862c949af7c79996d0e514ee96128644d840835ed5368eeecb14a869de361',
|
||||
'tcp-listen:5432,fork,reuseaddr', 'tcp-connect:postgres:5432'])
|
||||
proxy_networks = json.loads(environment.run(['docker', 'inspect', '--format',
|
||||
'{{json .NetworkSettings.Networks}}', proxy]).stdout)
|
||||
proxy_ip = proxy_networks[network]['IPAddress']
|
||||
override = Path(temporary) / 'compose.json'
|
||||
# Preserve the real postgres hostname/SAN and Bao-supplied role credentials.
|
||||
override.write_text(json.dumps({'services': {'api': {'extra_hosts': ['postgres:' + proxy_ip]}}}))
|
||||
environment.compose('-f', str(override), 'run', '-d', '--no-deps', '--use-aliases',
|
||||
'--name', candidate, 'api')
|
||||
wait(lambda: local_status() == 200, 'candidate did not become ready')
|
||||
slot = wait(lambda: next((name for name, status in stats().items()
|
||||
if status.startswith('UP') and not baseline.get(name, '').startswith('UP')), None),
|
||||
'candidate did not enter the LB rotation')
|
||||
hostname = environment.run(['docker', 'inspect', '--format', '{{.Config.Hostname}}', candidate]).stdout.strip()
|
||||
log.append('candidate ready: instance=' + hostname + ' slot=' + slot)
|
||||
environment.run(['docker', 'stop', proxy])
|
||||
wait(lambda: local_status() == 503, 'candidate did not become not-ready')
|
||||
state = environment.run(['docker', 'inspect', '--format', '{{.State.Status}}', candidate]).stdout.strip()
|
||||
if state != 'running':
|
||||
raise RuntimeError('candidate stopped instead of reporting not-ready')
|
||||
wait(lambda: stats().get(slot, '').startswith('DOWN'), 'LB did not exclude the not-ready candidate')
|
||||
after = observed()
|
||||
if hostname in after:
|
||||
raise RuntimeError('LB routed a request to the not-ready candidate')
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
for index in range(10):
|
||||
client.message(alice, chat, 'readiness-exclusion-' + str(index))
|
||||
log += ['candidate alive/readiness503; LB slot DOWN', 'during outage instances: ' + json.dumps(after),
|
||||
'business writes through remaining replicas: 10']
|
||||
finally:
|
||||
environment.run(['docker', 'rm', '-f', candidate, proxy], check=False)
|
||||
output.write_text('\n'.join(log) + '\n')
|
||||
print('\n'.join(log))
|
||||
PY
|
||||
|
||||
@@ -1,271 +0,0 @@
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
import matplotlib
|
||||
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
|
||||
def request(base_url, method, path, body=None, user_id=None):
|
||||
payload = json.dumps(body, ensure_ascii=False).encode() if body is not None else None
|
||||
headers = {"Content-Type": "application/json"} if payload else {}
|
||||
if user_id:
|
||||
headers["X-User-Id"] = user_id
|
||||
request = urllib.request.Request(
|
||||
base_url + path,
|
||||
data=payload,
|
||||
headers=headers,
|
||||
method=method,
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=3) as response:
|
||||
return json.loads(response.read())
|
||||
|
||||
|
||||
def wait_ready(base_url):
|
||||
deadline = time.monotonic() + 20
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
request(base_url, "GET", "/health/live")
|
||||
return
|
||||
except OSError:
|
||||
time.sleep(0.1)
|
||||
raise RuntimeError("container did not become ready")
|
||||
|
||||
|
||||
def process_alive(container):
|
||||
result = subprocess.run(
|
||||
["docker", "inspect", "--format", "{{.State.Running}}", container],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
return result.stdout.strip() == "true"
|
||||
|
||||
|
||||
def sample_stats(container, samples, stop):
|
||||
while not stop.is_set():
|
||||
result = subprocess.run(
|
||||
["docker", "stats", "--no-stream", "--format", "{{json .}}", container],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
if result.returncode == 0 and result.stdout.strip():
|
||||
try:
|
||||
value = json.loads(result.stdout)
|
||||
memory = value.get("MemUsage", "").split("/")[0].strip()
|
||||
if memory == "0B" or not process_alive(container):
|
||||
continue
|
||||
samples.append({
|
||||
"time_seconds": time.monotonic(),
|
||||
"memory": memory,
|
||||
"memory_mib": parse_memory(memory),
|
||||
})
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
stop.wait(0.1)
|
||||
|
||||
|
||||
def parse_memory(value):
|
||||
units = {"B": 1 / 1024 / 1024, "KiB": 1 / 1024, "MiB": 1, "GiB": 1024}
|
||||
for unit, factor in sorted(units.items(), key=lambda item: -len(item[0])):
|
||||
if value.endswith(unit):
|
||||
return float(value[:-len(unit)].strip()) * factor
|
||||
raise ValueError(value)
|
||||
|
||||
|
||||
def make_plot(data, output):
|
||||
samples = [sample for sample in data["memory_samples"] if sample["memory_mib"] > 0]
|
||||
start = samples[0]["time_seconds"] if samples else 0
|
||||
x = [sample["time_seconds"] - start for sample in samples]
|
||||
memory = [sample["memory_mib"] for sample in samples]
|
||||
|
||||
fig, memory_axis = plt.subplots(figsize=(11, 6))
|
||||
memory_axis.plot(x, memory, color="tab:red", label="RSS / container memory")
|
||||
memory_axis.axhline(data["memory_limit_mib"], color="black", linestyle="--", label="memory limit")
|
||||
memory_axis.set_xlabel("Time, seconds")
|
||||
memory_axis.set_ylabel("Memory, MiB")
|
||||
memory_axis.grid(True, alpha=0.25)
|
||||
|
||||
message_axis = memory_axis.twinx()
|
||||
message_axis.plot(
|
||||
data["message_points_x"],
|
||||
data["message_points_y"],
|
||||
color="tab:blue",
|
||||
label="successful messages",
|
||||
)
|
||||
message_axis.set_ylabel("Successful messages")
|
||||
|
||||
lines, labels = memory_axis.get_legend_handles_labels()
|
||||
other_lines, other_labels = message_axis.get_legend_handles_labels()
|
||||
memory_axis.legend(lines + other_lines, labels + other_labels, loc="upper left")
|
||||
memory_axis.set_title("In-memory messenger: memory exhaustion point")
|
||||
if data["oom_killed"] and data["failure_time_seconds"] is not None:
|
||||
memory_axis.axvline(
|
||||
data["failure_time_seconds"],
|
||||
color="tab:purple",
|
||||
linestyle=":",
|
||||
label="container OOMKilled",
|
||||
)
|
||||
memory_axis.annotate(
|
||||
"OOMKilled",
|
||||
(data["failure_time_seconds"], data["memory_limit_mib"]),
|
||||
xytext=(8, -18),
|
||||
textcoords="offset points",
|
||||
color="tab:purple",
|
||||
)
|
||||
fig.tight_layout()
|
||||
fig.savefig(output, dpi=160)
|
||||
plt.close(fig)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--image", required=True)
|
||||
parser.add_argument("--memory", default="32m")
|
||||
parser.add_argument("--output", default="evidence/memory-experiment.json")
|
||||
parser.add_argument("--plot", default="evidence/memory-experiment.png")
|
||||
parser.add_argument("--max-messages", type=int, default=100000)
|
||||
args = parser.parse_args()
|
||||
|
||||
container = "mtusi-memory-experiment-" + uuid.uuid4().hex[:8]
|
||||
port = 18081
|
||||
base_url = f"http://127.0.0.1:{port}"
|
||||
subprocess.run(
|
||||
[
|
||||
"docker", "run", "-d", "--name", container,
|
||||
"--memory", args.memory, "--memory-swap", args.memory,
|
||||
"-p", f"127.0.0.1:{port}:8080", args.image,
|
||||
],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
samples = []
|
||||
stop_sampling = threading.Event()
|
||||
sampler = threading.Thread(target=sample_stats, args=(container, samples, stop_sampling))
|
||||
successful = 0
|
||||
failures = 0
|
||||
fatal_error = None
|
||||
started = time.monotonic()
|
||||
message_points_x = []
|
||||
message_points_y = []
|
||||
failure_time = None
|
||||
oom_killed = False
|
||||
last_error = None
|
||||
last_state = {}
|
||||
logs = ""
|
||||
|
||||
try:
|
||||
wait_ready(base_url)
|
||||
user = request(base_url, "POST", "/api/v1/users", {
|
||||
"username": "memory_" + uuid.uuid4().hex[:16],
|
||||
"display_name": "Memory experiment",
|
||||
})
|
||||
chat = request(base_url, "POST", "/api/v1/chats", {
|
||||
"title": "Memory experiment",
|
||||
"member_ids": [user["id"]],
|
||||
}, user["id"])
|
||||
sampler.start()
|
||||
time.sleep(0.5)
|
||||
|
||||
body = "x" * 4000
|
||||
for index in range(args.max_messages):
|
||||
try:
|
||||
request(
|
||||
base_url,
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
{"text": body},
|
||||
user["id"],
|
||||
)
|
||||
successful += 1
|
||||
message_points_x.append(time.monotonic() - started)
|
||||
message_points_y.append(successful)
|
||||
except (OSError, urllib.error.HTTPError, ValueError) as exc:
|
||||
last_error = type(exc).__name__ + ": " + str(exc)
|
||||
failures += 1
|
||||
failure_time = time.monotonic() - started
|
||||
break
|
||||
|
||||
time.sleep(0.5)
|
||||
if not process_alive(container):
|
||||
failure_time = failure_time or (time.monotonic() - started)
|
||||
inspect = subprocess.run(
|
||||
["docker", "inspect", "--format", "{{json .State}}", container],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
state = json.loads(inspect.stdout) if inspect.stdout.strip() else {}
|
||||
if not state:
|
||||
state_result = subprocess.run(
|
||||
["docker", "inspect", "--format", "{{json .State}}", container],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
state = json.loads(state_result.stdout) if state_result.stdout.strip() else {}
|
||||
last_state = state
|
||||
logs_result = subprocess.run(["docker", "logs", container], capture_output=True, text=True, check=False)
|
||||
logs = logs_result.stdout + logs_result.stderr
|
||||
oom_killed = bool(state.get("OOMKilled"))
|
||||
if failure_time is None and failures:
|
||||
failure_time = time.monotonic() - started
|
||||
except Exception as exc:
|
||||
fatal_error = type(exc).__name__ + ": " + str(exc)
|
||||
failure_time = failure_time or (time.monotonic() - started)
|
||||
finally:
|
||||
stop_sampling.set()
|
||||
if sampler.is_alive():
|
||||
sampler.join(timeout=2)
|
||||
|
||||
memory_limit_mib = float(args.memory.rstrip("mM")) if args.memory.lower().endswith("m") else 0
|
||||
if not oom_killed:
|
||||
inspect = subprocess.run(
|
||||
["docker", "inspect", "--format", "{{json .State}}", container],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
state = json.loads(inspect.stdout) if inspect.stdout.strip() else {}
|
||||
last_state = state
|
||||
oom_killed = bool(state.get("OOMKilled"))
|
||||
|
||||
result = {
|
||||
"image": args.image,
|
||||
"memory_limit": args.memory,
|
||||
"memory_limit_mib": memory_limit_mib,
|
||||
"successful_messages": successful,
|
||||
"failed_requests": failures,
|
||||
"oom_killed": oom_killed,
|
||||
"last_error": last_error,
|
||||
"fatal_error": fatal_error,
|
||||
"container_state": last_state,
|
||||
"container_logs_tail": logs[-20000:],
|
||||
"failure_time_seconds": failure_time,
|
||||
"memory_samples": samples,
|
||||
"message_points_x": message_points_x,
|
||||
"message_points_y": message_points_y,
|
||||
"reason": "process stopped after the container memory limit was reached" if oom_killed else "request processing did not reach the memory limit",
|
||||
}
|
||||
with open(args.output, "w", encoding="utf-8") as output:
|
||||
json.dump(result, output, ensure_ascii=False, indent=2)
|
||||
make_plot(result, args.plot)
|
||||
print(json.dumps({key: result[key] for key in (
|
||||
"memory_limit", "successful_messages", "failed_requests", "oom_killed", "failure_time_seconds", "reason",
|
||||
)}, ensure_ascii=False, indent=2))
|
||||
subprocess.run(["docker", "rm", "-f", container], capture_output=True, check=False)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,68 +1,65 @@
|
||||
#!/bin/sh
|
||||
# Контроль пути «хост -> Colima VM -> LB»: тот же генератор и тот же профиль
|
||||
# запускаются дважды — с хоста через опубликованный порт и изнутри VM, где
|
||||
# клиент говорит с балансировщиком напрямую по docker-сети. Разница показывает
|
||||
# вклад этого пути в потолок closed-loop профиля, а не приписывает его по
|
||||
# догадке. Стенд должен быть поднят (`make up`).
|
||||
#
|
||||
# scripts/path_overhead_check.sh
|
||||
#
|
||||
# Артефакт: evidence/path-overhead/{inside,outside}.txt + summary.txt
|
||||
# Compare the same verified HTTPS load profile through host forwarding and LB namespace.
|
||||
set -eu
|
||||
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
exec "${PYTHON:-python3}" - "$@" <<'PY'
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
COMPOSE_BIN=${COMPOSE_BIN:-docker compose}
|
||||
OUT=${OUT:-evidence/path-overhead}
|
||||
DURATION=${DURATION:-60}
|
||||
CONCURRENCY=${CONCURRENCY:-8}
|
||||
WARMUP=${WARMUP:-15}
|
||||
CLIENT_IMAGE=${CLIENT_IMAGE:-python:3.12-alpine}
|
||||
sys.path.insert(0, str(Path.cwd() / 'scripts'))
|
||||
from lab7_environment import Environment, ROOT
|
||||
from lab7_http import BASE_URL, CA_FILE
|
||||
|
||||
compose() {
|
||||
# shellcheck disable=SC2086
|
||||
$COMPOSE_BIN --env-file .env -f compose.yaml "$@"
|
||||
}
|
||||
environment = Environment()
|
||||
output = Path(os.environ.get('OUT', 'evidence/path-overhead')).resolve()
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
duration = os.environ.get('DURATION', '60')
|
||||
concurrency = os.environ.get('CONCURRENCY', '8')
|
||||
warmup = os.environ.get('WARMUP', '15')
|
||||
image = os.environ.get('CLIENT_IMAGE', 'python:3.12-alpine')
|
||||
lbs = environment.compose('ps', '-q', 'lb').stdout.split()
|
||||
if len(lbs) != 1:
|
||||
raise SystemExit('expected one running Compose LB')
|
||||
ca = Path(CA_FILE).resolve(strict=True)
|
||||
|
||||
NO_PROXY_ENV="env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy"
|
||||
NO_PROXY_ENV="$NO_PROXY_ENV NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1"
|
||||
|
||||
mkdir -p "$OUT"
|
||||
def run_profile(location, seconds, destination=None):
|
||||
if location == 'outside':
|
||||
command = [sys.executable, str(ROOT / 'tests/load.py'), '--base-url', BASE_URL,
|
||||
'--ca-file', str(ca)]
|
||||
else:
|
||||
# Only public tests, contract and CA are mounted; no operator private key.
|
||||
command = ['docker', 'run', '--rm', '--network', 'container:' + lbs[0],
|
||||
'--cap-drop', 'ALL', '--security-opt', 'no-new-privileges:true',
|
||||
'--read-only', '--tmpfs', '/tmp',
|
||||
'--mount', f'type=bind,source={ROOT / "tests"},target=/repo/tests,readonly',
|
||||
'--mount', f'type=bind,source={ROOT / "contracts"},target=/repo/contracts,readonly',
|
||||
'--mount', f'type=bind,source={ROOT / "lab.json"},target=/repo/lab.json,readonly',
|
||||
'--mount', f'type=bind,source={ca},target=/ca.crt,readonly',
|
||||
'--mount', f'type=bind,source={output},target=/out',
|
||||
'-e', 'NO_PROXY=localhost,127.0.0.1', '-e', 'PYTHONDONTWRITEBYTECODE=1',
|
||||
image, 'python', '/repo/tests/load.py', '--base-url', 'https://localhost:8443',
|
||||
'--ca-file', '/ca.crt']
|
||||
command += ['--duration', seconds, '--concurrency', concurrency]
|
||||
if destination:
|
||||
command += ['--output', str(output / destination) if location == 'outside' else '/out/' + destination]
|
||||
return subprocess.run(command, cwd=ROOT, env=environment.process_env,
|
||||
capture_output=True, text=True, check=True)
|
||||
|
||||
network=$(docker inspect "$(compose ps -q api | head -1)" \
|
||||
--format '{{range $name, $network := .NetworkSettings.Networks}}{{$name}}{{end}}')
|
||||
|
||||
printf '# Контроль пути к балансировщику\n' > "$OUT/summary.txt"
|
||||
{
|
||||
printf '# generated: %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
printf '# profile: tests/load.py duration=%s concurrency=%s warmup=%s\n' "$DURATION" "$CONCURRENCY" "$WARMUP"
|
||||
printf '# docker network: %s\n' "$network"
|
||||
printf '# клиент в VM: %s\n\n' "$CLIENT_IMAGE"
|
||||
} >> "$OUT/summary.txt"
|
||||
|
||||
# Клиент с хоста: путь «хост -> проброс порта -> VM -> LB».
|
||||
printf '=== извне: клиент на хосте, http://127.0.0.1:8080 ===\n' | tee -a "$OUT/summary.txt"
|
||||
# shellcheck disable=SC2086
|
||||
$NO_PROXY_ENV python3 tests/load.py --base-url http://127.0.0.1:8080 \
|
||||
--duration "$WARMUP" --concurrency "$CONCURRENCY" >/dev/null
|
||||
# shellcheck disable=SC2086
|
||||
$NO_PROXY_ENV python3 tests/load.py --base-url http://127.0.0.1:8080 \
|
||||
--duration "$DURATION" --concurrency "$CONCURRENCY" \
|
||||
--output "$OUT/load-outside.json" | tee "$OUT/outside.txt" | tail -12
|
||||
|
||||
# Клиент внутри VM: тот же генератор и профиль, но без проброса порта и без
|
||||
# сетевого стека хоста. Генератор делит 2 vCPU VM со стендом, поэтому его
|
||||
# результат — нижняя оценка, а не потолок.
|
||||
printf '\n=== изнутри: клиент в VM, http://lb ===\n' | tee -a "$OUT/summary.txt"
|
||||
docker run --rm -i --network "$network" -v "$ROOT_DIR:/repo:ro" -v "$ROOT_DIR/$OUT:/out" \
|
||||
-e NO_PROXY='lb,localhost,127.0.0.1' -e no_proxy='lb,localhost,127.0.0.1' \
|
||||
"$CLIENT_IMAGE" python /repo/tests/load.py --base-url http://lb \
|
||||
--duration "$WARMUP" --concurrency "$CONCURRENCY" >/dev/null
|
||||
docker run --rm -i --network "$network" -v "$ROOT_DIR:/repo:ro" -v "$ROOT_DIR/$OUT:/out" \
|
||||
-e NO_PROXY='lb,localhost,127.0.0.1' -e no_proxy='lb,localhost,127.0.0.1' \
|
||||
"$CLIENT_IMAGE" python /repo/tests/load.py --base-url http://lb \
|
||||
--duration "$DURATION" --concurrency "$CONCURRENCY" \
|
||||
--output /out/load-inside.json | tee "$OUT/inside.txt" | tail -12
|
||||
|
||||
printf 'path_overhead_check.sh: артефакты в %s\n' "$OUT"
|
||||
summary = [time.strftime('# generated: %Y-%m-%dT%H:%M:%SZ', time.gmtime()),
|
||||
'host URL: ' + BASE_URL, 'inside URL: https://localhost:8443 (LB network namespace)',
|
||||
'client image: ' + image, 'VM generator shares the VM CPU budget with the stand']
|
||||
for location in ('outside', 'inside'):
|
||||
run_profile(location, warmup)
|
||||
result = run_profile(location, duration, 'load-' + location + '.json')
|
||||
(output / (location + '.txt')).write_text(result.stdout + result.stderr)
|
||||
summary.append(location + ': ' + json.dumps(json.loads((output / ('load-' + location + '.json')).read_text())))
|
||||
(output / 'summary.txt').write_text('\n'.join(summary) + '\n')
|
||||
print('\n'.join(summary))
|
||||
PY
|
||||
|
||||
@@ -15,21 +15,23 @@ import urllib.request
|
||||
import uuid
|
||||
import base64
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'student-tests'))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
|
||||
from tests_helpers import compose as compose_operator, redis
|
||||
from lab7_http import BASE_URL, open_url
|
||||
for proxy in ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy'):
|
||||
os.environ.pop(proxy, None)
|
||||
os.environ['NO_PROXY'] = 'localhost,127.0.0.1,::1'
|
||||
os.environ['no_proxy'] = os.environ['NO_PROXY']
|
||||
|
||||
BASE_URL = os.environ.get('BASE_URL', 'http://localhost:8080')
|
||||
COMPOSE = os.environ.get('COMPOSE_BIN', 'docker-compose')
|
||||
COMPOSE_FILE = 'docker-compose.local.yaml'
|
||||
BUDGET_MS = int(os.environ.get('OUTAGE_BUDGET_MS', '2000'))
|
||||
PARALLEL = int(os.environ.get('OUTAGE_PARALLEL', '30'))
|
||||
|
||||
|
||||
def compose(*args):
|
||||
subprocess.run([COMPOSE, '-f', COMPOSE_FILE, *args], check=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
return compose_operator(*args)
|
||||
|
||||
|
||||
def call(method, path, body=None, headers=None):
|
||||
@@ -41,8 +43,8 @@ def call(method, path, body=None, headers=None):
|
||||
req = urllib.request.Request(BASE_URL + path, data=data, headers=h, method=method)
|
||||
started = time.monotonic()
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=10)
|
||||
return resp.status, resp.read(), (time.monotonic() - started) * 1000
|
||||
with open_url(req, timeout=10) as resp:
|
||||
return resp.status, resp.read(), (time.monotonic() - started) * 1000
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code, exc.read(), (time.monotonic() - started) * 1000
|
||||
|
||||
@@ -106,22 +108,23 @@ def main():
|
||||
assert any(c['title'] == title for c in chats), 'new chat missing after recovery (stale cache)'
|
||||
print('after recovery: new chat visible, %.0fms' % ms)
|
||||
|
||||
stuck = subprocess.run(
|
||||
[COMPOSE, '-f', COMPOSE_FILE, 'exec', '-T', 'redis', 'redis-cli', '--scan', '--pattern', 'lock:*'],
|
||||
check=True, capture_output=True, text=True,
|
||||
).stdout.split()
|
||||
cursor = '0'
|
||||
stuck = set()
|
||||
while True:
|
||||
rows = redis('SCAN', cursor, 'MATCH', 'lock:*', 'COUNT', '1000').splitlines()
|
||||
assert rows and rows[0].isdigit(), 'operator Redis SCAN returned an invalid cursor'
|
||||
cursor = rows[0]
|
||||
stuck.update(rows[1:])
|
||||
if cursor == '0':
|
||||
break
|
||||
for key in stuck:
|
||||
ttl = subprocess.run(
|
||||
[COMPOSE, '-f', COMPOSE_FILE, 'exec', '-T', 'redis', 'redis-cli', 'ttl', key],
|
||||
check=True, capture_output=True, text=True,
|
||||
).stdout.strip()
|
||||
ttl = redis('ttl', key)
|
||||
assert ttl != '-1', 'stuck lock without TTL: %s' % key
|
||||
print('lock keys without TTL: 0')
|
||||
print('PASS: redis outage handled within budget')
|
||||
finally:
|
||||
for action in ('unpause', 'start'):
|
||||
subprocess.run([COMPOSE, '-f', COMPOSE_FILE, action, 'redis'],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
compose_operator(action, 'redis', check=False)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# TODO: copy to restart.sh and implement using YOUR compose/stack services.
|
||||
# Restart API and ALL used state stores (DB, sessions, S3, broker as applicable).
|
||||
# Preserve persistent volumes and schema/data; never down -v / flush / re-seed.
|
||||
# Allow operator unseal if required in lab7; do not print credentials.
|
||||
# Exit 0 only after the intended action; test waits for API readiness separately.
|
||||
printf '%s
|
||||
' 'TODO: implement restart.sh for your infrastructure' >&2
|
||||
exit 2
|
||||
+3
-55
@@ -1,58 +1,6 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Restart hook: bounce API replicas, worker/relay and every state store of the lab5 stand.
|
||||
#
|
||||
# scripts/restart.sh
|
||||
#
|
||||
# Persistent volumes are kept: no `down -v`, no flush, no re-seed. The one-shot
|
||||
# `migrate` service is not re-run (schema stays as it is, data and sessions
|
||||
# survive). The script exits 0 only after /health/ready answers through the LB.
|
||||
# No credentials are printed.
|
||||
# Operator restart preserves every data volume, unseals Bao from protected
|
||||
# operator-local state and recreates shared-namespace consumers explicitly.
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
|
||||
# .env определяет, на каком порту публикуется LB (compose.yaml) и какие креды у
|
||||
# хранилищ, поэтому значения берём оттуда же, а не из окружения вызывающего.
|
||||
if [ -f .env ]; then
|
||||
set -a
|
||||
# shellcheck disable=SC1091
|
||||
. ./.env
|
||||
set +a
|
||||
fi
|
||||
|
||||
COMPOSE_BIN=${COMPOSE_BIN:-docker compose}
|
||||
PORT=${SERVER_PORT:-8080}
|
||||
|
||||
# shellcheck disable=SC2086
|
||||
compose() {
|
||||
# shellcheck disable=SC2086
|
||||
$COMPOSE_BIN --env-file .env -f compose.yaml "$@"
|
||||
}
|
||||
|
||||
# 1. State stores and broker: restart the running ones, then make sure they are
|
||||
# healthy. Volumes are attached as before, nothing is dropped or re-seeded.
|
||||
compose up -d --wait postgres redis seaweedfs broker
|
||||
compose restart postgres redis seaweedfs broker
|
||||
compose up -d --wait postgres redis seaweedfs broker
|
||||
|
||||
# 2. API replicas, worker and relay: restart in place and bring back any replica
|
||||
# stopped by a fault-injection hook. The worker reconnects to the broker.
|
||||
compose restart api worker relay
|
||||
compose up -d --wait --no-deps api worker relay
|
||||
|
||||
# 3. Load balancer keeps its upstream; re-resolve in case addresses changed.
|
||||
compose restart lb
|
||||
|
||||
# 4. Wait for readiness through the public entry point.
|
||||
attempt=0
|
||||
while [ "$attempt" -lt 60 ]; do
|
||||
if curl -fsS --noproxy '*' -o /dev/null "http://127.0.0.1:${PORT}/health/ready"; then
|
||||
printf 'restart.sh: stack restarted, http://127.0.0.1:%s/health/ready is ready\n' "$PORT"
|
||||
exit 0
|
||||
fi
|
||||
attempt=$((attempt + 1))
|
||||
sleep 1
|
||||
done
|
||||
|
||||
printf 'restart.sh: /health/ready did not become ready through the LB\n' >&2
|
||||
exit 1
|
||||
exec python3 "$ROOT_DIR/scripts/securityctl.py" restart
|
||||
|
||||
+110
-220
@@ -1,231 +1,121 @@
|
||||
#!/bin/sh
|
||||
# Rolling update of the API replicas under load (lab3, level 4).
|
||||
#
|
||||
# Замена идёт «наплывом» и строго по одной реплике: сначала рядом поднимается
|
||||
# контейнер новой ревизии с тем же сетевым alias, затем снимается ОДИН старый.
|
||||
# Каждый шаг гейтится состоянием балансировщика: новый слот должен стать UP
|
||||
# (активная проверка /health/ready), снятый — перестать быть UP. Гейт по
|
||||
# статистике LB, а не по наблюдению X-Instance-Id в ответах, потому что HAProxy
|
||||
# переиспользует keepalive-соединения к уже работающим репликам и свежая реплика
|
||||
# может какое-то время не получать трафик, оставаясь при этом готовой.
|
||||
#
|
||||
# В конце стенд возвращается под управление compose: поднимаются штатные реплики
|
||||
# из новой ревизии, затем по одной снимаются временные контейнеры наплыва.
|
||||
#
|
||||
# scripts/rolling_update.sh # профиль лимитов берётся из .env/compose.yaml
|
||||
# DURATION=60 CONCURRENCY=8 scripts/rolling_update.sh
|
||||
# Secure Compose surge rollout: inherited API identity/config/hardening, one replica at a time.
|
||||
set -eu
|
||||
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
exec "${PYTHON:-python3}" - "$@" <<'PY'
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
|
||||
COMPOSE_BIN=${COMPOSE_BIN:-docker compose}
|
||||
PYTHON=${PYTHON:-python3}
|
||||
DURATION=${DURATION:-60}
|
||||
CONCURRENCY=${CONCURRENCY:-8}
|
||||
BASE_URL=${BASE_URL:-http://localhost:8080}
|
||||
OUT=${OUT:-evidence/rolling-update}
|
||||
IMAGE=${IMAGE:-mtusi-messenger:lab4}
|
||||
PROJECT=${COMPOSE_PROJECT_NAME:-mtusi-messenger-lab4}
|
||||
NET=${PROJECT}_default
|
||||
STATS=${STATS:-http://127.0.0.1:8404/stats;csv}
|
||||
PREFIX=lb-rollout
|
||||
sys.path.insert(0, str(Path.cwd() / 'scripts'))
|
||||
sys.path.insert(0, str(Path.cwd() / 'tests'))
|
||||
from lab7_environment import Environment, ROOT
|
||||
from lab7_http import BASE_URL, CA_FILE, open_url
|
||||
from client import Client
|
||||
|
||||
NO_PROXY_ENV="env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy"
|
||||
NO_PROXY_ENV="$NO_PROXY_ENV NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1"
|
||||
environment = Environment()
|
||||
output = Path(os.environ.get('OUT', 'evidence/rolling-update'))
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
image = os.environ.get('IMAGE', 'mtusi-messenger:lab7')
|
||||
stats_url = os.environ.get('STATS', 'https://localhost:' + environment.value('LB_STATS_PORT', '8404') + '/stats;csv')
|
||||
replicas = environment.compose('ps', '-q', 'api').stdout.split()
|
||||
if len(replicas) < 2:
|
||||
raise SystemExit('rolling update requires at least two running API replicas')
|
||||
environment.run(['docker', 'image', 'inspect', image])
|
||||
client = Client(BASE_URL, CA_FILE, timeout=5)
|
||||
log = []
|
||||
surge = []
|
||||
loader = None
|
||||
|
||||
mkdir -p "$OUT"
|
||||
rm -f "$OUT/load.json" "$OUT/load.txt"
|
||||
def rows():
|
||||
with open_url(stats_url, operator=True, ca_file=CA_FILE) as response:
|
||||
content = response.read().decode()
|
||||
return list(csv.DictReader(io.StringIO(content.replace('# ', '', 1))))
|
||||
|
||||
compose() {
|
||||
# shellcheck disable=SC2086
|
||||
$COMPOSE_BIN --env-file .env -f compose.yaml "$@"
|
||||
}
|
||||
def up_slots():
|
||||
return sum(row['pxname'] == 'api_backend' and row['svname'] not in ('BACKEND', 'FRONTEND')
|
||||
and row['status'].startswith('UP') for row in rows())
|
||||
|
||||
api_containers() {
|
||||
docker ps -q \
|
||||
--filter "label=com.docker.compose.project=$PROJECT" \
|
||||
--filter 'label=com.docker.compose.service=api'
|
||||
}
|
||||
def wait_slots(expected):
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
if up_slots() == expected:
|
||||
client.call('GET', '/health/ready', schema='Health')
|
||||
return
|
||||
time.sleep(1)
|
||||
raise RuntimeError('LB did not converge to %d healthy business slots' % expected)
|
||||
|
||||
rollout_containers() {
|
||||
docker ps -q --filter "name=^$PREFIX"
|
||||
}
|
||||
def wait_container(container):
|
||||
deadline = time.monotonic() + 90
|
||||
while time.monotonic() < deadline:
|
||||
result = environment.run(['docker', 'exec', container, 'wget', '-qO-', '-T', '3',
|
||||
'http://127.0.0.1:8084/health/ready'], check=False)
|
||||
if result.returncode == 0:
|
||||
return
|
||||
time.sleep(1)
|
||||
raise RuntimeError('surge replica did not become locally ready')
|
||||
|
||||
restarts() {
|
||||
for container in $(api_containers) $(rollout_containers); do
|
||||
printf '%s=%s ' "$(docker inspect --format '{{.Name}}' "$container" | sed 's|^/||')" \
|
||||
"$(docker inspect --format '{{.RestartCount}}' "$container")"
|
||||
done
|
||||
}
|
||||
|
||||
stats_rows() {
|
||||
curl -s --noproxy '*' "$STATS"
|
||||
}
|
||||
|
||||
# В CSV-выгрузке HAProxy колонка addr приходит пустой, поэтому привязка слота к
|
||||
# конкретному контейнеру идёт по двум наблюдаемым фактам: контейнер отвечает на
|
||||
# /health/ready, а число UP-слотов соответствует ожидаемому.
|
||||
container_ready() {
|
||||
docker exec "$1" wget -qO- -T 3 http://127.0.0.1:8080/health/ready 2>/dev/null | grep -q '"status":"ok"'
|
||||
}
|
||||
|
||||
wait_container_ready() {
|
||||
name=$1
|
||||
attempt=0
|
||||
|
||||
while [ "$attempt" -lt 45 ]; do
|
||||
container_ready "$name" && return 0
|
||||
attempt=$((attempt + 1))
|
||||
sleep 1
|
||||
done
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
up_slots() {
|
||||
stats_rows | awk -F, '
|
||||
NR == 1 { for (i = 1; i <= NF; i++) if ($i == "status") s = i; next }
|
||||
$1 ~ /^api/ && $s == "UP" { count++ } END { print count + 0 }'
|
||||
}
|
||||
|
||||
wait_up_slots() {
|
||||
want=$1
|
||||
attempt=0
|
||||
|
||||
while [ "$attempt" -lt 45 ]; do
|
||||
[ "$(up_slots)" -ge "$want" ] && return 0
|
||||
attempt=$((attempt + 1))
|
||||
sleep 1
|
||||
done
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
lb_5xx() {
|
||||
stats_rows | awk -F, '
|
||||
NR == 1 { for (i = 1; i <= NF; i++) if ($i == "hrsp_5xx") column = i; next }
|
||||
$1 == "http_front" && $2 == "FRONTEND" && column { print $column; exit }'
|
||||
}
|
||||
|
||||
{
|
||||
echo "# Rolling update under load (surge, one replica at a time)"
|
||||
echo "# generated: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
echo "# load: tolerant loader, duration=${DURATION}s concurrency=${CONCURRENCY}"
|
||||
echo "# проверки готовности LB: httpchk /health/ready, inter 2s fall 2 rise 2, timeout check 1s"
|
||||
echo
|
||||
|
||||
# Сборка пишет много строк; в артефакт они не нужны.
|
||||
compose build api >/dev/null 2>&1 || compose build api
|
||||
|
||||
before_containers=$(api_containers)
|
||||
replicas=$(printf '%s\n' "$before_containers" | wc -l | tr -d ' ')
|
||||
[ "$replicas" -ge 2 ] || { echo "нужно не менее двух API-реплик" >&2; exit 1; }
|
||||
|
||||
old_image=$(docker inspect --format '{{.Image}}' "$(printf '%s\n' "$before_containers" | head -1)")
|
||||
new_image=$(docker image inspect --format '{{.Id}}' "$IMAGE")
|
||||
echo "реплик до обновления: ${replicas}"
|
||||
echo "образ старых реплик: ${old_image}"
|
||||
echo "образ новой ревизии: ${new_image}"
|
||||
echo "ревизия меняется: $([ "$old_image" = "$new_image" ] && echo 'нет (образ не изменился)' || echo 'да')"
|
||||
echo "слотов UP до: $(up_slots); restarts до: $(restarts)"
|
||||
echo
|
||||
|
||||
envfile=$(mktemp)
|
||||
trap 'rm -f "$envfile"; docker rm -f $(rollout_containers) >/dev/null 2>&1 || true' EXIT INT TERM
|
||||
docker inspect --format '{{range .Config.Env}}{{println .}}{{end}}' \
|
||||
"$(printf '%s\n' "$before_containers" | head -1)" > "$envfile"
|
||||
|
||||
# Перед измерением убеждаемся, что все ожидаемые реплики видит сам LB: после
|
||||
# экспериментов с отказом хранилищ слоты могут быть в переходном состоянии.
|
||||
if ! wait_up_slots "$replicas"; then
|
||||
echo "перед обновлением LB видит меньше ${replicas} реплик" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
five_before=$(lb_5xx)
|
||||
# shellcheck disable=SC2086
|
||||
$NO_PROXY_ENV $PYTHON student-tests/rolling_update_load.py --base-url "$BASE_URL" \
|
||||
--duration "$DURATION" --concurrency "$CONCURRENCY" \
|
||||
--output "$OUT/load.json" > "$OUT/load.txt" 2>&1 &
|
||||
load_pid=$!
|
||||
|
||||
step=0
|
||||
for container in $before_containers; do
|
||||
step=$((step + 1))
|
||||
name="$PREFIX-$step"
|
||||
old_instance=$(docker inspect --format '{{.Config.Hostname}}' "$container")
|
||||
started=$(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
|
||||
# 1. поднять реплику новой ревизии рядом со старыми; дождаться, что она
|
||||
# сама готова и что LB видит на один слот больше
|
||||
docker run -d --name "$name" --network "$NET" --network-alias api-replica \
|
||||
--env-file "$envfile" "$IMAGE" >/dev/null
|
||||
new_instance=$(docker inspect --format '{{.Config.Hostname}}' "$name")
|
||||
new_container_image=$(docker inspect --format '{{.Image}}' "$name")
|
||||
|
||||
if ! wait_container_ready "$name"; then
|
||||
echo " step ${step}: реплика ${name} не стала готова" >&2
|
||||
echo " diagnostics: status=$(docker inspect --format '{{.State.Status}}' "$name" 2>&1); stats: $(stats_rows | awk -F, '$1 ~ /^api/ { printf "%s=%s ", $2, $18 }')" >&2
|
||||
docker logs --tail 20 "$name" >&2 2>&1 || true
|
||||
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! wait_up_slots "$((replicas + step))"; then
|
||||
echo " step ${step}: UP-слотов меньше ожидаемого ($(up_slots) вместо $((replicas + step)))" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 2. снять одну старую реплику и дождаться, что UP-слотов снова ровно
|
||||
# столько, сколько реплик должно остаться
|
||||
docker rm -f "$container" >/dev/null
|
||||
|
||||
if ! wait_up_slots "$((replicas + step - 1))"; then
|
||||
echo " step ${step}: после снятия UP-слотов больше ожидаемого" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
printf ' step %s: %s обслуживает (образ %s, instance %s), старый контейнер %s (%s) снят; UP-слотов %s; 5xx накоплено %s; старт шага %s\n' \
|
||||
"$step" "$name" "${new_container_image#sha256:}" "$new_instance" \
|
||||
"${container:0:12}" "$old_instance" "$(up_slots)" "$(lb_5xx)" "$started"
|
||||
done
|
||||
|
||||
wait "$load_pid" || true
|
||||
|
||||
five_after=$(lb_5xx)
|
||||
echo
|
||||
echo "load summary (tolerant generator):"
|
||||
cat "$OUT/load.txt"
|
||||
echo
|
||||
echo "5xx от LB за время обновления (hrsp_5xx frontend): $((${five_after:-0} - ${five_before:-0}))"
|
||||
echo "restarts после: $(restarts)"
|
||||
|
||||
# 3. вернуть стенд под управление compose и убрать временные контейнеры
|
||||
echo
|
||||
echo "возврат стенда под управление compose:"
|
||||
compose up -d --no-deps api
|
||||
wait_up_slots "$replicas" || true
|
||||
|
||||
remaining=$(printf '%s\n' $(rollout_containers) | wc -l | tr -d ' ')
|
||||
for container in $(rollout_containers); do
|
||||
docker rm -f "$container" >/dev/null
|
||||
remaining=$((remaining - 1))
|
||||
|
||||
if ! wait_up_slots "$((replicas + remaining))"; then
|
||||
echo " после снятия ${container} UP-слотов больше ожидаемого" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
echo "снято временных контейнеров наплыва: проверено"
|
||||
|
||||
echo "UP-слотов после: $(up_slots); restarts в конце: $(restarts)"
|
||||
echo "API containers после обновления:"
|
||||
docker ps --format '{{.Names}} {{.Status}}' \
|
||||
--filter "label=com.docker.compose.project=$PROJECT" \
|
||||
--filter 'label=com.docker.compose.service=api'
|
||||
} > "$OUT/rolling-update.txt" 2>&1
|
||||
|
||||
cat "$OUT/rolling-update.txt"
|
||||
printf 'rolling_update.sh: evidence in %s\n' "$OUT"
|
||||
with tempfile.TemporaryDirectory(prefix='lab7-rollout-') as temporary:
|
||||
override = Path(temporary) / 'compose.json'
|
||||
override.write_text(json.dumps({'services': {'api': {'image': image}}}))
|
||||
try:
|
||||
wait_slots(len(replicas))
|
||||
old_images = [environment.run(['docker', 'inspect', '--format', '{{.Image}}', container]).stdout.strip()
|
||||
for container in replicas]
|
||||
log.append('old image digests: ' + ', '.join(old_images))
|
||||
with (output / 'load.txt').open('w') as load_log:
|
||||
loader = subprocess.Popen(
|
||||
[sys.executable, str(ROOT / 'student-tests/rolling_update_load.py'),
|
||||
'--base-url', BASE_URL, '--ca-file', CA_FILE,
|
||||
'--duration', os.environ.get('DURATION', '60'),
|
||||
'--concurrency', os.environ.get('CONCURRENCY', '8'),
|
||||
'--output', str(output / 'load.json')],
|
||||
cwd=ROOT, env=environment.process_env, stdout=load_log, stderr=subprocess.STDOUT)
|
||||
for old in replicas:
|
||||
name = environment.project + '-rollout-' + uuid.uuid4().hex[:8]
|
||||
environment.compose('-f', str(override), 'run', '-d', '--no-deps', '--use-aliases',
|
||||
'--name', name, 'api')
|
||||
surge.append(name)
|
||||
wait_container(name)
|
||||
wait_slots(len(replicas) + 1)
|
||||
environment.run(['docker', 'stop', old])
|
||||
environment.run(['docker', 'rm', old])
|
||||
wait_slots(len(replicas))
|
||||
log.append('ready surge %s replaced %s; healthy slots=%d' % (name, old, up_slots()))
|
||||
result = loader.wait()
|
||||
if result:
|
||||
raise RuntimeError('load generator failed; inspect load.txt/load.json')
|
||||
environment.compose('-f', str(override), 'up', '-d', '--no-deps', '--scale',
|
||||
'api=' + str(len(replicas)), 'api')
|
||||
wait_slots(len(replicas) + len(surge))
|
||||
while surge:
|
||||
name = surge[0]
|
||||
environment.run(['docker', 'stop', name])
|
||||
environment.run(['docker', 'rm', name])
|
||||
surge.pop(0)
|
||||
wait_slots(len(replicas) + len(surge))
|
||||
log.append('Compose control restored; healthy slots=%d' % up_slots())
|
||||
finally:
|
||||
if loader is not None and loader.poll() is None:
|
||||
loader.terminate()
|
||||
loader.wait()
|
||||
# Restore regular replicas before removing any surviving surge capacity.
|
||||
environment.compose('-f', str(override), 'up', '-d', '--no-deps', '--scale',
|
||||
'api=' + str(len(replicas)), 'api', check=False)
|
||||
if surge:
|
||||
for container in environment.compose('ps', '-q', 'api').stdout.split():
|
||||
wait_container(container)
|
||||
for name in surge:
|
||||
environment.run(['docker', 'stop', name], check=False)
|
||||
environment.run(['docker', 'rm', name], check=False)
|
||||
(output / 'rolling-update.txt').write_text('\n'.join(log) + '\n')
|
||||
print('\n'.join(log))
|
||||
PY
|
||||
|
||||
Executable
+848
@@ -0,0 +1,848 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Reproducible operator bootstrap/renewal/rotation for the local lab7 stand.
|
||||
|
||||
Private root/unseal state is outside this checkout. No secret values are printed.
|
||||
All OpenBao calls verify CA and hostname; app roles authenticate independently.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from lab7_environment import BaoClient, Environment, OperationError, ROOT, ROLES, atomic_write
|
||||
from lab7_pki import PKI
|
||||
|
||||
GATEWAY_PAIRS = {
|
||||
'seaweedfs': ['s3'],
|
||||
'broker': ['broker-admin-tls'],
|
||||
'otel-collector': ['collector-tls'],
|
||||
'prometheus': ['prometheus-tls'],
|
||||
'loki': ['loki-tls'],
|
||||
'tempo': ['tempo-tls'],
|
||||
'grafana': ['grafana-tls'],
|
||||
}
|
||||
STORES = ['postgres', 'redis', 'seaweedfs', 'broker']
|
||||
TELEMETRY = ['otel-collector', 'prometheus', 'loki', 'tempo', 'grafana']
|
||||
|
||||
|
||||
def password_hash(password: str) -> str:
|
||||
salt = secrets.token_bytes(4)
|
||||
return base64.b64encode(salt + hashlib.sha256(salt + password.encode()).digest()).decode()
|
||||
|
||||
|
||||
def scram_verifier(password: str, iterations: int = 4096) -> str:
|
||||
"""Build a SCRAM-SHA-256 verifier so plaintext never enters SQL/logs."""
|
||||
salt = secrets.token_bytes(16)
|
||||
salted = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, iterations)
|
||||
client_key = hmac.new(salted, b'Client Key', hashlib.sha256).digest()
|
||||
stored_key = hashlib.sha256(client_key).digest()
|
||||
server_key = hmac.new(salted, b'Server Key', hashlib.sha256).digest()
|
||||
encode = lambda value: base64.b64encode(value).decode()
|
||||
return 'SCRAM-SHA-256$%d:%s$%s:%s' % (iterations, encode(salt), encode(stored_key), encode(server_key))
|
||||
|
||||
|
||||
def service_policy(role: str) -> str:
|
||||
rules = [f'''path "pki/issue/{role}" {{ capabilities = ["create", "update"] }}''',
|
||||
'''path "auth/token/lookup-self" { capabilities = ["read"] }
|
||||
path "auth/token/renew-self" { capabilities = ["update"] }
|
||||
path "auth/token/revoke-self" { capabilities = ["update"] }''']
|
||||
if role in ('api', 'worker', 'relay'):
|
||||
rules.append(f'''path "secret/data/{role}" {{ capabilities = ["read"] }}''')
|
||||
return '\n'.join(rules) + '\n'
|
||||
|
||||
|
||||
def operator_policy() -> str:
|
||||
paths = {
|
||||
'secret/data/*': ['create', 'read', 'update', 'delete', 'list'],
|
||||
'secret/metadata/*': ['read', 'list', 'delete'],
|
||||
'pki/*': ['create', 'read', 'update', 'delete', 'list', 'sudo'],
|
||||
'auth/cert/certs/*': ['create', 'read', 'update', 'delete', 'list'],
|
||||
'auth/cert/crls/*': ['create', 'read', 'update', 'delete', 'list'],
|
||||
'sys/policies/acl/lab7-*': ['create', 'read', 'update', 'delete', 'list'],
|
||||
'sys/mounts': ['read'], 'sys/mounts/pki': ['create', 'read', 'update', 'sudo'],
|
||||
'sys/mounts/secret': ['create', 'read', 'update', 'sudo'],
|
||||
'sys/auth': ['read'], 'sys/auth/cert': ['create', 'read', 'update', 'sudo'],
|
||||
'sys/audit': ['read', 'sudo'], 'sys/audit/file': ['read', 'sudo'],
|
||||
'sys/seal': ['update', 'sudo'], 'auth/token/lookup-self': ['read'],
|
||||
'auth/token/renew-self': ['update'], 'auth/token/revoke-self': ['update'],
|
||||
}
|
||||
return '\n'.join('path ' + json.dumps(path) + ' { capabilities = ' +
|
||||
json.dumps(capabilities) + ' }' for path, capabilities in paths.items()) + '\n'
|
||||
|
||||
|
||||
class Controller:
|
||||
def __init__(self) -> None:
|
||||
self.env = Environment()
|
||||
self.pki = PKI(self.env)
|
||||
self.credentials_path = self.env.secrets / 'backends/credentials.json'
|
||||
self.init_path = self.env.state / 'operator-unseal.json'
|
||||
|
||||
def credentials(self) -> dict:
|
||||
values = self.env.read_json(self.credentials_path)
|
||||
if not values:
|
||||
values = {
|
||||
'postgres': {
|
||||
'operator': {'username': 'lab_operator', 'password': secrets.token_hex(32)},
|
||||
**{role: {'username': 'messenger_' + role, 'password': secrets.token_hex(32)}
|
||||
for role in ('api', 'worker', 'relay')},
|
||||
},
|
||||
'redis': {role: {'username': role, 'password': secrets.token_hex(32)}
|
||||
for role in ('cache', 'operator', 'health')},
|
||||
's3': {role: {'access_key': 'lab7' + role + secrets.token_hex(8),
|
||||
'secret_key': secrets.token_hex(32)}
|
||||
for role in ('operator', 'api', 'worker')},
|
||||
'grafana': {'password': secrets.token_hex(32)},
|
||||
'broker': {'operator': {'password': secrets.token_hex(32)}},
|
||||
}
|
||||
self.env.private_json(self.credentials_path, values)
|
||||
for family in values.values():
|
||||
if isinstance(family, dict):
|
||||
for record in family.values():
|
||||
if isinstance(record, dict):
|
||||
self.env.redactions.update(str(value) for key, value in record.items()
|
||||
if key in ('password', 'secret_key', 'access_key'))
|
||||
self.env.redactions.add(values['grafana']['password'])
|
||||
return values
|
||||
|
||||
def write_file(self, relative: str, content: str) -> None:
|
||||
destination = self.env.secrets / relative
|
||||
destination.parent.mkdir(parents=True, exist_ok=True, mode=0o750)
|
||||
os.chmod(destination.parent, 0o750)
|
||||
atomic_write(destination, content, 0o640)
|
||||
|
||||
def backend_files(self) -> None:
|
||||
credentials = self.credentials()
|
||||
operator = credentials['postgres']['operator']
|
||||
self.write_file('bootstrap/migrate/postgres-password', operator['password'] + '\n')
|
||||
self.write_file('backends/postgres/operator-password', operator['password'] + '\n')
|
||||
for role, prefix in (('operator', 's3-admin'), ('api', 's3-app')):
|
||||
values = credentials['s3'][role]
|
||||
self.write_file('bootstrap/s3/' + prefix + '-access-key', values['access_key'] + '\n')
|
||||
self.write_file('bootstrap/s3/' + prefix + '-secret-key', values['secret_key'] + '\n')
|
||||
identity_config = json.loads((ROOT / 'infra/s3/s3.json').read_text())
|
||||
bucket = self.env.value('S3_BUCKET', 'messenger-attachments')
|
||||
for identity in identity_config['identities']:
|
||||
values = credentials['s3'][identity['name']]
|
||||
identity['credentials'] = [{'accessKey': values['access_key'], 'secretKey': values['secret_key']}]
|
||||
identity['actions'] = [action.replace('messenger-attachments', bucket)
|
||||
for action in identity['actions']]
|
||||
self.write_file('backends/s3/s3.json', json.dumps(identity_config, indent=2) + '\n')
|
||||
cache = credentials['redis']['cache']['password']
|
||||
operator_password = credentials['redis']['operator']['password']
|
||||
health = credentials['redis']['health']['password']
|
||||
acl = f'''user default off
|
||||
user cache on >{cache} ~chat_list:* ~lock:chat_list:* +get +set +del +ping +eval +evalsha +script|load
|
||||
user health on >{health} +ping
|
||||
user operator on >{operator_password} ~* &* +@all
|
||||
'''
|
||||
self.write_file('backends/redis/users.acl', acl)
|
||||
self.write_file('backends/redis/health-password', health + '\n')
|
||||
self.write_file('backends/redis/operator-password', operator_password + '\n')
|
||||
self.write_file('backends/grafana/admin-password', credentials['grafana']['password'] + '\n')
|
||||
users = [
|
||||
{'name': role, 'password_hash': password_hash(secrets.token_hex(32)),
|
||||
'hashing_algorithm': 'rabbit_password_hashing_sha256', 'tags': []}
|
||||
for role in ('worker', 'relay')
|
||||
]
|
||||
users.append({'name': 'operator',
|
||||
'password_hash': password_hash(credentials['broker']['operator']['password']),
|
||||
'hashing_algorithm': 'rabbit_password_hashing_sha256', 'tags': ['administrator']})
|
||||
definitions = {
|
||||
'users': users, 'vhosts': [{'name': 'messenger'}],
|
||||
'permissions': [
|
||||
{'user': 'relay', 'vhost': 'messenger', 'configure': '^$',
|
||||
'write': r'^attachments\.jobs$', 'read': '^$'},
|
||||
{'user': 'worker', 'vhost': 'messenger', 'configure': '^$',
|
||||
'write': '^$', 'read': r'^attachment\.process\.v1$'},
|
||||
{'user': 'operator', 'vhost': 'messenger', 'configure': '.*', 'write': '.*', 'read': '.*'},
|
||||
],
|
||||
'exchanges': [
|
||||
{'name': name, 'vhost': 'messenger', 'type': 'direct', 'durable': True,
|
||||
'auto_delete': False, 'internal': False, 'arguments': {}}
|
||||
for name in ('attachments.jobs', 'attachments.dlx')
|
||||
],
|
||||
'queues': [
|
||||
{'name': 'attachment.process.v1', 'vhost': 'messenger', 'durable': True,
|
||||
'auto_delete': False, 'arguments': {
|
||||
'x-queue-type': 'quorum', 'x-delivery-limit': 100,
|
||||
'x-delayed-retry-type': 'all', 'x-delayed-retry-min': 5000,
|
||||
'x-delayed-retry-max': 60000,
|
||||
'x-dead-letter-exchange': 'attachments.dlx',
|
||||
'x-dead-letter-routing-key': 'attachment.process.dead',
|
||||
'x-dead-letter-strategy': 'at-least-once',
|
||||
'x-overflow': 'reject-publish', 'x-max-length': 100000,
|
||||
'x-consumer-timeout': 300000,
|
||||
}},
|
||||
{'name': 'attachment.process.dead', 'vhost': 'messenger', 'durable': True,
|
||||
'auto_delete': False, 'arguments': {'x-queue-type': 'quorum', 'x-max-length': 100000,
|
||||
'x-overflow': 'reject-publish', 'x-message-ttl': 604800000}},
|
||||
],
|
||||
'bindings': [
|
||||
{'source': exchange, 'vhost': 'messenger', 'destination': queue,
|
||||
'destination_type': 'queue', 'routing_key': queue, 'arguments': {}}
|
||||
for exchange, queue in (('attachments.jobs', 'attachment.process.v1'),
|
||||
('attachments.dlx', 'attachment.process.dead'))
|
||||
],
|
||||
}
|
||||
self.write_file('backends/broker/definitions.json', json.dumps(definitions, indent=2) + '\n')
|
||||
self.env.group_access(self.env.secrets / 'backends')
|
||||
self.env.group_access(self.env.secrets / 'bootstrap')
|
||||
|
||||
def render_grafana(self) -> None:
|
||||
template = (ROOT / 'infra/grafana/provisioning/datasources/datasources.yaml').read_text()
|
||||
values = self.env.snapshot('grafana')
|
||||
replacements = {
|
||||
'__LAB7_CA_CERT__': values['ca.crt'],
|
||||
'__LAB7_CLIENT_CERT__': values['tls.crt'],
|
||||
'__LAB7_CLIENT_KEY__': values['tls.key'],
|
||||
}
|
||||
lines = []
|
||||
for line in template.splitlines():
|
||||
value = replacements.get(line.strip())
|
||||
if value is None:
|
||||
lines.append(line)
|
||||
else:
|
||||
indent = line[:len(line) - len(line.lstrip())]
|
||||
lines.extend(indent + item for item in value.rstrip().splitlines())
|
||||
self.write_file('backends/grafana/datasources/datasources.yaml', '\n'.join(lines) + '\n')
|
||||
self.write_file('backends/grafana/dashboards/dashboards.yaml',
|
||||
(ROOT / 'infra/grafana/provisioning/dashboards/dashboards.yaml').read_text())
|
||||
self.env.group_access(self.env.secrets / 'backends/grafana')
|
||||
|
||||
def prepare(self) -> dict:
|
||||
self.pki.prepare()
|
||||
self.backend_files()
|
||||
self.pki.recover_transport()
|
||||
self.render_grafana()
|
||||
metadata = {'project': self.env.project, 'pki_mount': 'pki',
|
||||
'api_replicas': int(self.env.value('API_REPLICAS', '2'))}
|
||||
self.env.private_json(self.env.secrets / 'metadata.json', metadata)
|
||||
return {'prepared': True, 'project': self.env.project}
|
||||
|
||||
def unseal(self) -> dict:
|
||||
deadline = time.monotonic() + 60
|
||||
client = BaoClient(self.env, None)
|
||||
while True:
|
||||
try:
|
||||
status = client.request('GET', 'sys/seal-status')
|
||||
break
|
||||
except OperationError:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(1)
|
||||
if not status.get('initialized'):
|
||||
response = client.request('POST', 'sys/init', {'secret_shares': 3, 'secret_threshold': 2}, timeout=60)
|
||||
material = {'keys': response['keys_base64'], 'root_token': response['root_token']}
|
||||
self.env.private_json(self.init_path, material)
|
||||
status = client.request('GET', 'sys/seal-status')
|
||||
material = self.env.read_json(self.init_path)
|
||||
if status.get('sealed'):
|
||||
keys = material.get('keys', [])
|
||||
if len(keys) < 2:
|
||||
raise OperationError('operator unseal state is missing; it must never be recovered from the container')
|
||||
for key in keys[:2]:
|
||||
self.env.redactions.add(key)
|
||||
status = client.request('POST', 'sys/unseal', {'key': key}, timeout=30)
|
||||
if status.get('sealed'):
|
||||
raise OperationError('operator unseal did not complete')
|
||||
while True:
|
||||
health = client.request('GET', 'sys/health', allowed=(200, 429, 472, 473, 501, 503))
|
||||
if health.get('initialized') and not health.get('sealed') and not health.get('standby'):
|
||||
break
|
||||
if time.monotonic() >= deadline:
|
||||
raise OperationError('unsealed OpenBao did not become the active node')
|
||||
time.sleep(0.2)
|
||||
return {'unsealed': True, 'project': self.env.project}
|
||||
|
||||
def seal(self) -> dict:
|
||||
client = BaoClient(self.env)
|
||||
client.request('POST', 'sys/seal', {}, client.login())
|
||||
status = client.request('GET', 'sys/seal-status')
|
||||
if not status.get('sealed'):
|
||||
raise OperationError('operator seal did not close OpenBao')
|
||||
return {'sealed': True, 'project': self.env.project}
|
||||
|
||||
def configure_auth(self, client: BaoClient, token: str) -> None:
|
||||
methods = client.request('GET', 'sys/auth', token=token)
|
||||
methods = methods.get('data', methods)
|
||||
if 'cert/' not in methods:
|
||||
client.request('POST', 'sys/auth/cert', {'type': 'cert'}, token)
|
||||
for role in ROLES:
|
||||
policy = operator_policy() if role == 'operator' else service_policy(role)
|
||||
client.request('PUT', 'sys/policies/acl/lab7-' + role, {'policy': policy}, token)
|
||||
client.request('POST', 'auth/cert/certs/' + role, {
|
||||
'certificate': self.pki.root_bundle(),
|
||||
'allowed_common_names': [role], 'allowed_uri_sans': ['spiffe://mtusi/' + role],
|
||||
'token_policies': ['lab7-' + role], 'token_ttl': '60s',
|
||||
'token_max_ttl': '300s', 'token_explicit_max_ttl': '300s',
|
||||
'token_no_default_policy': True,
|
||||
}, token)
|
||||
|
||||
def configure_kv(self, client: BaoClient, token: str) -> None:
|
||||
mounts = client.request('GET', 'sys/mounts', token=token)
|
||||
mounts = mounts.get('data', mounts)
|
||||
if 'secret/' not in mounts:
|
||||
client.request('POST', 'sys/mounts/secret', {'type': 'kv', 'options': {'version': '2'}}, token)
|
||||
values = self.credentials()
|
||||
for role in ('api', 'worker', 'relay'):
|
||||
data = {'POSTGRES_PASSWORD': values['postgres'][role]['password']}
|
||||
if role != 'relay':
|
||||
data.update({'S3_ACCESS_KEY_ID': values['s3'][role]['access_key'],
|
||||
'S3_SECRET_ACCESS_KEY': values['s3'][role]['secret_key']})
|
||||
if role == 'api':
|
||||
data['REDIS_PASSWORD'] = values['redis']['cache']['password']
|
||||
client.request('POST', 'secret/data/' + role, {'data': data}, token)
|
||||
|
||||
def provision_bao(self) -> None:
|
||||
material = self.env.read_json(self.init_path)
|
||||
root_token = material.get('root_token')
|
||||
if root_token:
|
||||
self.env.redactions.add(root_token)
|
||||
client = BaoClient(self.env, None)
|
||||
token = root_token
|
||||
else:
|
||||
client = BaoClient(self.env)
|
||||
token = client.login()
|
||||
audits = client.request('GET', 'sys/audit', token=token)
|
||||
audits = audits.get('data', audits)
|
||||
if 'file/' not in audits:
|
||||
raise OperationError('mandatory declarative audit device is not active')
|
||||
self.configure_auth(client, token)
|
||||
self.configure_kv(client, token)
|
||||
self.pki.provision(client, token)
|
||||
self.pki.sync_crls(client, token)
|
||||
if root_token:
|
||||
# Verify the separately scoped operator path before destroying initial root.
|
||||
operator = BaoClient(self.env)
|
||||
operator.login()
|
||||
client.request('POST', 'auth/token/revoke-self', {}, root_token)
|
||||
denied = client.request('GET', 'auth/token/lookup-self', token=root_token,
|
||||
allowed=(403,))
|
||||
if not denied.get('errors'):
|
||||
raise OperationError('root credential was not rejected after revocation')
|
||||
material.pop('root_token', None)
|
||||
material['root_token_revoked'] = True
|
||||
self.env.private_json(self.init_path, material)
|
||||
self.env.private_json(self.env.state / 'bootstrap-state.json', {'bao_provisioned': True})
|
||||
|
||||
def sql(self, sql: str, user: str = 'lab_operator', *, check: bool = True) -> str:
|
||||
result = self.env.compose('exec', '-T', 'postgres', 'psql', '-v', 'ON_ERROR_STOP=1',
|
||||
'-U', user, '-d', 'messenger', '-At', data=sql,
|
||||
check=check)
|
||||
return result.stdout if result.returncode == 0 else ''
|
||||
|
||||
def reconcile_roles(self) -> None:
|
||||
values = self.credentials()['postgres']
|
||||
existing = None
|
||||
for candidate in ('lab_operator', 'messenger', 'postgres'):
|
||||
if self.sql('SELECT current_user;\n', candidate, check=False).strip() == candidate:
|
||||
existing = candidate
|
||||
break
|
||||
if not existing:
|
||||
raise OperationError('no local operator database role is available')
|
||||
statements = []
|
||||
for role, record in values.items():
|
||||
name = record['username']
|
||||
statements.append(f"DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname='{name}') "
|
||||
f'THEN CREATE ROLE "{name}"; END IF; END $$;')
|
||||
privilege = 'SUPERUSER CREATEDB CREATEROLE' if role == 'operator' else 'NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT'
|
||||
statements.append(f'ALTER ROLE "{name}" WITH LOGIN {privilege} '
|
||||
f"PASSWORD '{scram_verifier(record['password'])}' CONNECTION LIMIT 32;")
|
||||
self.sql('\n'.join(statements), existing)
|
||||
|
||||
def grants(self) -> None:
|
||||
sql = '''
|
||||
REVOKE ALL ON DATABASE messenger FROM PUBLIC;
|
||||
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
|
||||
REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC;
|
||||
REVOKE ALL ON ALL SEQUENCES IN SCHEMA public FROM PUBLIC;
|
||||
GRANT CONNECT ON DATABASE messenger TO messenger_api, messenger_worker, messenger_relay;
|
||||
GRANT USAGE ON SCHEMA public TO messenger_api, messenger_worker, messenger_relay;
|
||||
REVOKE ALL ON ALL TABLES IN SCHEMA public FROM messenger_api, messenger_worker, messenger_relay;
|
||||
REVOKE ALL ON ALL SEQUENCES IN SCHEMA public FROM messenger_api, messenger_worker, messenger_relay;
|
||||
GRANT SELECT, INSERT, UPDATE ON users, chats, chat_members, messages, user_chat_versions,
|
||||
attachments, attachment_jobs, outbox_messages, attachment_job_events TO messenger_api;
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON sessions, message_idempotency, login_limits TO messenger_api;
|
||||
GRANT SELECT ON attachment_variants TO messenger_api;
|
||||
GRANT SELECT, INSERT ON message_attachments TO messenger_api;
|
||||
GRANT DELETE ON attachments TO messenger_api;
|
||||
GRANT SELECT, INSERT, UPDATE ON attachments, attachment_jobs, attachment_variants,
|
||||
outbox_messages, attachment_job_events TO messenger_worker;
|
||||
GRANT DELETE ON attachments TO messenger_worker;
|
||||
GRANT SELECT, UPDATE ON attachments, attachment_jobs TO messenger_relay;
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON outbox_messages TO messenger_relay;
|
||||
GRANT SELECT, INSERT ON attachment_job_events TO messenger_relay;
|
||||
GRANT USAGE, SELECT ON outbox_messages_id_seq, attachment_job_events_id_seq
|
||||
TO messenger_api, messenger_worker, messenger_relay;
|
||||
DO $$ DECLARE app_object record; object_type text; BEGIN
|
||||
IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname='messenger') THEN
|
||||
-- The initdb bootstrap principal owns pg_catalog objects that cannot be
|
||||
-- reassigned globally. Only the application's public objects move owners.
|
||||
FOR app_object IN
|
||||
SELECT c.relname, c.relkind FROM pg_class c
|
||||
JOIN pg_namespace n ON n.oid = c.relnamespace
|
||||
WHERE n.nspname = 'public'
|
||||
AND c.relowner = (SELECT oid FROM pg_roles WHERE rolname='messenger')
|
||||
AND c.relkind IN ('r', 'p', 'S', 'v', 'm')
|
||||
AND (c.relkind <> 'S' OR NOT EXISTS (
|
||||
SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_class'::regclass
|
||||
AND d.objid = c.oid AND d.deptype IN ('a', 'i')
|
||||
))
|
||||
LOOP
|
||||
object_type := CASE app_object.relkind
|
||||
WHEN 'S' THEN 'SEQUENCE' WHEN 'v' THEN 'VIEW'
|
||||
WHEN 'm' THEN 'MATERIALIZED VIEW' ELSE 'TABLE' END;
|
||||
EXECUTE format('ALTER %s public.%I OWNER TO lab_operator', object_type, app_object.relname);
|
||||
END LOOP;
|
||||
ALTER DATABASE messenger OWNER TO lab_operator;
|
||||
ALTER SCHEMA public OWNER TO lab_operator;
|
||||
-- PostgreSQL 18 requires the initdb bootstrap role to remain SUPERUSER.
|
||||
-- NOLOGIN plus removal of its password retires the legacy identity without
|
||||
-- rebuilding the cluster or changing user data.
|
||||
ALTER ROLE messenger NOLOGIN PASSWORD NULL NOCREATEDB NOCREATEROLE NOINHERIT;
|
||||
END IF;
|
||||
END $$;
|
||||
'''
|
||||
self.sql(sql)
|
||||
|
||||
def retire_broker_users(self) -> None:
|
||||
for user in ('messenger', 'guest'):
|
||||
self.env.compose('exec', '-T', 'broker', 'rabbitmqctl', 'delete_user', user, check=False)
|
||||
|
||||
def ensure_service_identities(self) -> dict:
|
||||
"""Reissue leafs that expired while the stand was stopped.
|
||||
|
||||
`prepare` only fills gaps and does not inspect leaf expiry. Recovery is
|
||||
operator-driven here; the running stand uses `make renewer`.
|
||||
"""
|
||||
replaced = self.pki.recover_transport()
|
||||
if replaced:
|
||||
self.env.compose('restart', 'openbao', timeout=60)
|
||||
self.unseal()
|
||||
renewed = []
|
||||
for role in ROLES:
|
||||
certificate = self.env.identity(role) / 'tls.crt'
|
||||
if not certificate.exists():
|
||||
continue
|
||||
valid = self.env.run(['openssl', 'x509', '-checkend', '120', '-noout',
|
||||
'-in', str(certificate)], check=False).returncode == 0
|
||||
if not valid:
|
||||
self.pki.issue(role)
|
||||
renewed.append(role)
|
||||
return {'renewed': renewed}
|
||||
|
||||
def bootstrap(self) -> dict:
|
||||
self.prepare()
|
||||
self.env.compose('up', '-d', '--no-build', 'volume-init', timeout=300)
|
||||
# volume-init is short-lived; consumers require successful completion.
|
||||
self.env.compose('up', '-d', '--no-build', 'openbao', timeout=300)
|
||||
self.unseal()
|
||||
self.provision_bao()
|
||||
# On the first successful bootstrap, transition from offline bootstrap
|
||||
# leaves to restricted OpenBao-issued, short-lived service identities.
|
||||
marker = self.env.state / 'service-leaves.json'
|
||||
if not marker.exists():
|
||||
leaves = [self.pki.issue(role) for role in ROLES if role != 'rogue']
|
||||
self.env.private_json(marker, {'issued': leaves})
|
||||
self.env.compose('restart', 'openbao', timeout=60)
|
||||
self.unseal()
|
||||
recovered = self.ensure_service_identities()
|
||||
self.render_grafana()
|
||||
self.env.compose('up', '-d', '--no-build', *STORES, 's3', timeout=300)
|
||||
self.wait_stores()
|
||||
self.reconcile_roles()
|
||||
self.env.compose('run', '--rm', '--no-deps', 'migrate', timeout=180)
|
||||
self.grants()
|
||||
self.env.compose('run', '--rm', '--no-deps', 's3-init', timeout=180)
|
||||
self.retire_broker_users()
|
||||
return {'bootstrapped': True, 'project': self.env.project,
|
||||
'expired_identities_renewed': recovered.get('renewed', []),
|
||||
'root_token_revoked': self.env.read_json(self.init_path).get('root_token_revoked', False)}
|
||||
|
||||
def wait_stores(self) -> None:
|
||||
deadline = time.monotonic() + 120
|
||||
for service in ('postgres', 'redis', 'broker', 'seaweedfs'):
|
||||
while True:
|
||||
result = self.env.compose('ps', '-q', service).stdout.strip()
|
||||
if result:
|
||||
state = self.env.run(['docker', 'inspect', '--format',
|
||||
'{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}',
|
||||
result]).stdout.strip()
|
||||
if state in ('healthy', 'running'):
|
||||
break
|
||||
if time.monotonic() >= deadline:
|
||||
raise OperationError(service + ' did not become ready')
|
||||
time.sleep(1)
|
||||
|
||||
def wait_s3(self, timeout: float = 120) -> None:
|
||||
"""Read old volume-backed bytes; never repair an established sentinel."""
|
||||
deadline = time.monotonic() + timeout
|
||||
marker = self.env.state / 's3-readiness.json'
|
||||
sentinel = self.env.read_json(marker)
|
||||
if not sentinel:
|
||||
sentinel = {'bucket': self.env.value('S3_BUCKET', 'messenger-attachments'),
|
||||
'key': 'operator-readiness/' + secrets.token_hex(16),
|
||||
'body': secrets.token_hex(32768), 'established': False}
|
||||
self.env.private_json(marker, sentinel)
|
||||
payload = sentinel['body'].encode()
|
||||
credential = self.credentials()['s3']['operator']
|
||||
host = 'localhost:' + self.env.value('S3_PORT', '8333')
|
||||
bucket_path = '/' + urllib.parse.quote(sentinel['bucket'], safe='')
|
||||
object_path = bucket_path + '/' + urllib.parse.quote(sentinel['key'], safe='/~')
|
||||
context = ssl.create_default_context(cafile=str(self.env.identity('operator') / 'ca.crt'))
|
||||
context.load_cert_chain(str(self.env.identity('operator') / 'tls.crt'),
|
||||
str(self.env.identity('operator') / 'tls.key'))
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect(),
|
||||
urllib.request.HTTPSHandler(context=context))
|
||||
|
||||
def request(method: str, path: str, body: bytes = b'') -> bytes:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError()
|
||||
stamp = time.strftime('%Y%m%dT%H%M%SZ', time.gmtime())
|
||||
day = stamp[:8]
|
||||
digest = hashlib.sha256(body).hexdigest()
|
||||
headers = {'host': host, 'x-amz-content-sha256': digest, 'x-amz-date': stamp}
|
||||
signed = ';'.join(sorted(headers))
|
||||
canonical_headers = ''.join(name + ':' + headers[name] + '\n' for name in sorted(headers))
|
||||
canonical = '\n'.join((method, path, '', canonical_headers, signed, digest))
|
||||
scope = day + '/us-east-1/s3/aws4_request'
|
||||
to_sign = 'AWS4-HMAC-SHA256\n' + stamp + '\n' + scope + '\n' + hashlib.sha256(canonical.encode()).hexdigest()
|
||||
signing_key = ('AWS4' + credential['secret_key']).encode()
|
||||
for part in (day, 'us-east-1', 's3', 'aws4_request'):
|
||||
signing_key = hmac.new(signing_key, part.encode(), hashlib.sha256).digest()
|
||||
signature = hmac.new(signing_key, to_sign.encode(), hashlib.sha256).hexdigest()
|
||||
headers['Authorization'] = ('AWS4-HMAC-SHA256 Credential=' + credential['access_key'] +
|
||||
'/' + scope + ', SignedHeaders=' + signed + ', Signature=' + signature)
|
||||
req = urllib.request.Request('https://' + host + path, method=method, headers=headers,
|
||||
data=body if method == 'PUT' else None)
|
||||
with opener.open(req, timeout=min(5, remaining)) as response:
|
||||
chunks = bytearray()
|
||||
while len(chunks) <= len(payload):
|
||||
if time.monotonic() >= deadline:
|
||||
raise TimeoutError()
|
||||
chunk = response.read1(min(8192, len(payload) + 1 - len(chunks)))
|
||||
if not chunk:
|
||||
break
|
||||
chunks.extend(chunk)
|
||||
return bytes(chunks)
|
||||
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
if not sentinel['established']:
|
||||
# Only this operator-owned key is written on first initialization.
|
||||
request('PUT', object_path, payload)
|
||||
if request('GET', object_path) != payload:
|
||||
raise OperationError('persistent S3 readiness sentinel bytes changed')
|
||||
if not sentinel['established']:
|
||||
sentinel['established'] = True
|
||||
self.env.private_json(marker, sentinel)
|
||||
return
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code not in (404, 408, 429, 500, 502, 503, 504):
|
||||
raise OperationError('S3 readiness request rejected (HTTP ' + str(exc.code) + ')') from None
|
||||
except (urllib.error.URLError, TimeoutError, ConnectionError):
|
||||
pass
|
||||
time.sleep(min(1, max(0, deadline - time.monotonic())))
|
||||
raise OperationError('CA-verified persistent S3 body readiness deadline exceeded')
|
||||
|
||||
def wait_ready(self, timeout: float = 120) -> None:
|
||||
deadline = time.monotonic() + timeout
|
||||
self.wait_s3(timeout=timeout)
|
||||
context = ssl.create_default_context(cafile=str(self.env.identity('operator') / 'ca.crt'))
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}),
|
||||
urllib.request.HTTPSHandler(context=context))
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with opener.open(self.env.base_url + '/health/ready', timeout=5) as response:
|
||||
if response.status == 200:
|
||||
return
|
||||
except (urllib.error.URLError, TimeoutError):
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise OperationError('CA-verified public HTTPS readiness deadline exceeded')
|
||||
|
||||
def up(self) -> dict:
|
||||
result = self.bootstrap()
|
||||
self.env.compose('up', '-d', '--no-build', timeout=300)
|
||||
# Apply current credentials/trust/CRLs even when owners were reused.
|
||||
# Namespace consumers are recreated against the current owner ID.
|
||||
gateways = [child for children in GATEWAY_PAIRS.values()
|
||||
for child in children if child != 's3']
|
||||
self.env.compose('up', '-d', '--no-build', '--no-deps', '--force-recreate',
|
||||
*gateways, timeout=180)
|
||||
self.env.compose('restart', 'lb', timeout=60)
|
||||
self.wait_ready()
|
||||
self.reset_grafana_admin()
|
||||
return {**result, 'ready': True, 'base_url': self.env.base_url}
|
||||
|
||||
def wait_container_health(self, container: str, timeout: float = 120) -> None:
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
state = self.env.run(['docker', 'inspect', '--format',
|
||||
'{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}',
|
||||
container], check=False).stdout.strip()
|
||||
if state in ('healthy', 'running'):
|
||||
return
|
||||
if time.monotonic() >= deadline:
|
||||
raise OperationError(container + ' did not become healthy after restart: ' + state)
|
||||
time.sleep(1)
|
||||
|
||||
def rolling_restart(self, service: str) -> None:
|
||||
containers = [item for item in self.env.compose('ps', '-q', service).stdout.split() if item]
|
||||
for container in containers:
|
||||
self.env.run(['docker', 'restart', container], timeout=120)
|
||||
self.wait_container_health(container)
|
||||
|
||||
def restart_consumers(self, *, stores: bool = True, apps: bool = True) -> None:
|
||||
if stores:
|
||||
# Establish/read the sentinel before stopping the old volume owner.
|
||||
self.wait_s3()
|
||||
self.env.compose('restart', 'openbao', timeout=60)
|
||||
self.unseal()
|
||||
self.env.compose('restart', *STORES, *TELEMETRY, timeout=180)
|
||||
self.wait_stores()
|
||||
# A shared-network consumer is tied to a concrete owner container ID.
|
||||
# Recreate consumers explicitly even if an owner was replaced.
|
||||
consumers = [consumer for values in GATEWAY_PAIRS.values() for consumer in values]
|
||||
self.env.compose('up', '-d', '--no-build', '--force-recreate', '--no-deps',
|
||||
*consumers, timeout=180)
|
||||
self.wait_s3()
|
||||
if apps:
|
||||
# One replica at a time: the surviving API serves while the peer
|
||||
# reloads the new leaf/trust bundle. LB is restarted last.
|
||||
for service in ('api', 'worker', 'relay'):
|
||||
self.rolling_restart(service)
|
||||
self.env.compose('restart', 'lb', timeout=60)
|
||||
self.wait_ready()
|
||||
|
||||
def rotate_secret(self, role: str) -> dict:
|
||||
if role not in ('api', 'worker'):
|
||||
raise OperationError('the completed secret rotation experiment targets an S3 application identity')
|
||||
values = self.credentials()
|
||||
old = values['s3'][role]
|
||||
self.env.private_json(self.env.state / ('retired-' + role + '-s3.json'), old)
|
||||
values['s3'][role] = {'access_key': 'lab7' + role + secrets.token_hex(8),
|
||||
'secret_key': secrets.token_hex(32)}
|
||||
self.env.private_json(self.credentials_path, values)
|
||||
self.backend_files()
|
||||
client = BaoClient(self.env)
|
||||
self.configure_kv(client, client.login())
|
||||
self.env.compose('restart', 's3', timeout=60)
|
||||
self.env.compose('restart', role, timeout=60)
|
||||
self.wait_ready()
|
||||
return {'role': role, 'secret_rotated': True, 'old_key_retired': True,
|
||||
'images_rebuilt': False}
|
||||
|
||||
def rollover(self, phase: str) -> dict:
|
||||
if phase == 'prepare':
|
||||
result = self.pki.prepare_rollover()
|
||||
elif phase == 'issue':
|
||||
result = self.pki.switch_issuer()
|
||||
else:
|
||||
result = self.pki.retire_issuer()
|
||||
client = BaoClient(self.env)
|
||||
self.configure_auth(client, client.login())
|
||||
self.render_grafana()
|
||||
# Go reloads leaves on new handshakes: during issue the trust bundle is
|
||||
# unchanged (overlap from prepare), so only native owners restart.
|
||||
# Prepare distributes trust and retire removes it; both need app reload.
|
||||
self.restart_consumers(apps=phase != 'issue')
|
||||
return {**result, 'all_consumers_reloaded': True, 'images_rebuilt': False,
|
||||
'application_reload': phase != 'issue'}
|
||||
|
||||
def reset_grafana_admin(self) -> None:
|
||||
context = ssl.create_default_context(cafile=str(self.env.identity('operator') / 'ca.crt'))
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}),
|
||||
urllib.request.HTTPSHandler(context=context))
|
||||
endpoint = 'https://localhost:' + self.env.value('GRAFANA_PORT', '3000') + '/api/health'
|
||||
deadline = time.monotonic() + 60
|
||||
while True:
|
||||
try:
|
||||
with opener.open(endpoint, timeout=5) as response:
|
||||
if response.status == 200:
|
||||
break
|
||||
except (urllib.error.URLError, TimeoutError):
|
||||
if time.monotonic() >= deadline:
|
||||
raise OperationError('Grafana verified TLS health deadline exceeded')
|
||||
time.sleep(1)
|
||||
self.env.compose('exec', '-T', 'grafana', 'grafana', 'cli',
|
||||
'--homepath', '/usr/share/grafana', 'admin',
|
||||
'reset-admin-password', '--password-from-stdin',
|
||||
data=self.credentials()['grafana']['password'] + '\n')
|
||||
|
||||
def redis(self, arguments: list[str]) -> str:
|
||||
# Read the operator credential inside its own backend mount, never argv.
|
||||
result = self.env.compose('exec', '-T', 'redis', 'sh', '-ec',
|
||||
'export REDISCLI_AUTH="$(cat /run/backend/operator-password)"; '
|
||||
'exec redis-cli --tls --cacert /run/identity/current/ca.crt '
|
||||
'--user operator "$@"', '--', *arguments)
|
||||
return result.stdout
|
||||
|
||||
def jobctl(self, arguments: list[str]) -> str:
|
||||
return self.env.compose('run', '--rm', '--no-deps', 'jobctl', *arguments).stdout
|
||||
|
||||
def reload_identity(self, role: str) -> None:
|
||||
if role in ('api', 'operator', 'rogue'):
|
||||
# Go reloads complete versions on new handshakes; its manager notices
|
||||
# actual current leaf expiry independently of the token renewal.
|
||||
return
|
||||
if role == 'openbao':
|
||||
self.env.compose('restart', 'openbao', timeout=60)
|
||||
self.unseal()
|
||||
return
|
||||
if role == 's3':
|
||||
self.env.compose('restart', 'seaweedfs', timeout=60)
|
||||
self.env.compose('up', '-d', '--no-build', '--force-recreate', '--no-deps', 's3', timeout=90)
|
||||
return
|
||||
owner = 'otel-collector' if role == 'collector' else role
|
||||
if role == 'grafana':
|
||||
self.render_grafana()
|
||||
self.env.compose('restart', owner, timeout=90)
|
||||
children = GATEWAY_PAIRS.get(owner, [])
|
||||
if children:
|
||||
self.env.compose('up', '-d', '--no-build', '--force-recreate', '--no-deps', *children, timeout=90)
|
||||
|
||||
def revoke_identity(self, role: str, serial: str) -> dict:
|
||||
result = self.pki.revoke(role, serial)
|
||||
# Go reads current CRLs per handshake; native gateways hold startup
|
||||
# CRLs and must drain old sessions before revocation returns success.
|
||||
gateways = ['lb', *[child for children in GATEWAY_PAIRS.values()
|
||||
for child in children if child != 's3']]
|
||||
self.env.compose('restart', *gateways, timeout=180)
|
||||
return {**result, 'native_gateway_crls_reloaded': True, 'old_connections_drained': True}
|
||||
|
||||
def recover_identity(self, role: str) -> dict:
|
||||
transport_replaced = self.pki.recover_transport()
|
||||
if transport_replaced or role == 'openbao':
|
||||
self.env.compose('restart', 'openbao', timeout=60)
|
||||
self.unseal()
|
||||
issued = self.pki.issue(role)
|
||||
self.reload_identity(role)
|
||||
if role in ('api', 'worker', 'relay'):
|
||||
self.env.compose('up', '-d', '--no-build', '--no-deps', role, timeout=90)
|
||||
return {**issued, 'recovered_by_operator': True}
|
||||
|
||||
def sync_crls(self) -> dict:
|
||||
client = BaoClient(self.env)
|
||||
token = client.login()
|
||||
republished = self.pki.sync_crls(client, token)
|
||||
return {'crls_updated': True, 'identities_republished': republished}
|
||||
|
||||
def audit_summary(self) -> dict:
|
||||
result = self.env.compose('exec', '-T', 'openbao', 'cat', '/openbao/audit/audit.log')
|
||||
counts = {}
|
||||
for line in result.stdout.splitlines():
|
||||
try:
|
||||
record = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
request = record.get('request', {})
|
||||
path = request.get('path', '')
|
||||
operation = request.get('operation', '')
|
||||
if path.startswith(('pki/issue/', 'pki/revoke', 'auth/token/renew-self', 'auth/cert/login')):
|
||||
key = operation + ' ' + path
|
||||
counts[key] = counts.get(key, 0) + 1
|
||||
return {'audit_events': counts, 'raw_credentials_exported': False}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
commands = parser.add_subparsers(dest='command', required=True)
|
||||
for name in ('prepare', 'bootstrap', 'up', 'unseal', 'seal', 'restart', 'sync-crls', 'audit-summary', 'status'):
|
||||
commands.add_parser(name)
|
||||
for name in ('issue', 'renew'):
|
||||
sub = commands.add_parser(name)
|
||||
sub.add_argument('role', choices=ROLES)
|
||||
sub.add_argument('--ttl', default='1h')
|
||||
if name == 'renew':
|
||||
sub.add_argument('--watch', action='store_true')
|
||||
sub.add_argument('--interval', type=float, default=1)
|
||||
sub = commands.add_parser('revoke')
|
||||
sub.add_argument('role', choices=ROLES)
|
||||
sub.add_argument('--serial', required=True)
|
||||
sub = commands.add_parser('rotate-secret')
|
||||
sub.add_argument('role', choices=('api', 'worker'))
|
||||
sub = commands.add_parser('ca-rollover')
|
||||
sub.add_argument('--phase', choices=('prepare', 'issue', 'retire'), required=True)
|
||||
sub = commands.add_parser('recover')
|
||||
sub.add_argument('role', choices=ROLES)
|
||||
commands.add_parser('psql')
|
||||
for name in ('redis', 'jobctl'):
|
||||
command = commands.add_parser(name)
|
||||
command.add_argument('arguments', nargs=argparse.REMAINDER)
|
||||
args = parser.parse_args()
|
||||
control = Controller()
|
||||
if args.command == 'psql':
|
||||
print(control.sql(sys.stdin.read()), end='')
|
||||
return
|
||||
if args.command == 'redis':
|
||||
print(control.redis(args.arguments), end='')
|
||||
return
|
||||
if args.command == 'jobctl':
|
||||
print(control.jobctl(args.arguments), end='')
|
||||
return
|
||||
if args.command == 'prepare':
|
||||
result = control.prepare()
|
||||
elif args.command == 'bootstrap':
|
||||
result = control.bootstrap()
|
||||
elif args.command == 'up':
|
||||
result = control.up()
|
||||
elif args.command == 'unseal':
|
||||
result = control.unseal()
|
||||
elif args.command == 'seal':
|
||||
result = control.seal()
|
||||
elif args.command == 'restart':
|
||||
control.restart_consumers()
|
||||
result = {'restarted': True, 'volumes_preserved': True}
|
||||
elif args.command == 'sync-crls':
|
||||
result = control.sync_crls()
|
||||
elif args.command == 'issue':
|
||||
result = control.pki.issue(args.role, args.ttl)
|
||||
control.reload_identity(args.role)
|
||||
elif args.command == 'renew':
|
||||
if args.watch:
|
||||
control.pki.renew_watch(args.role, args.ttl, args.interval, control.reload_identity)
|
||||
return
|
||||
result = control.pki.issue(args.role, args.ttl, service_auth=True)
|
||||
control.reload_identity(args.role)
|
||||
elif args.command == 'recover':
|
||||
result = control.recover_identity(args.role)
|
||||
elif args.command == 'revoke':
|
||||
result = control.revoke_identity(args.role, args.serial)
|
||||
elif args.command == 'rotate-secret':
|
||||
result = control.rotate_secret(args.role)
|
||||
elif args.command == 'ca-rollover':
|
||||
result = control.rollover(args.phase)
|
||||
elif args.command == 'audit-summary':
|
||||
result = control.audit_summary()
|
||||
else:
|
||||
result = {'project': control.env.project, 'base_url': control.env.base_url,
|
||||
'pki': control.pki.state}
|
||||
print(json.dumps(result, ensure_ascii=False), flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except (OperationError, OSError, TimeoutError, subprocess.TimeoutExpired) as error:
|
||||
print('FAIL: ' + str(error), file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
@@ -2,5 +2,4 @@
|
||||
set -eu
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
COMPOSE_BIN=${COMPOSE_BIN:-docker compose}
|
||||
$COMPOSE_BIN --env-file .env -f compose.yaml up -d --wait --no-deps broker
|
||||
exec python3 student-tests/tests_helpers.py compose up -d --wait --no-deps broker broker-admin-tls
|
||||
|
||||
@@ -2,5 +2,4 @@
|
||||
set -eu
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
COMPOSE_BIN=${COMPOSE_BIN:-docker compose}
|
||||
$COMPOSE_BIN --env-file .env -f compose.yaml up -d --wait --no-deps worker
|
||||
exec python3 student-tests/tests_helpers.py compose up -d --wait --no-deps worker
|
||||
|
||||
@@ -2,5 +2,4 @@
|
||||
set -eu
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
COMPOSE_BIN=${COMPOSE_BIN:-docker compose}
|
||||
$COMPOSE_BIN --env-file .env -f compose.yaml stop broker
|
||||
exec python3 student-tests/tests_helpers.py compose stop broker-admin-tls broker
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# TODO: copy to stop-one.sh, map TARGET_INSTANCE_ID to ONE API container/task.
|
||||
# Stop that instance and leave it stopped; no stop of DB/LB/volumes.
|
||||
# Return quickly (within 10 s); the test sends requests during this script.
|
||||
# Restore the replica explicitly after the test. Never print credentials.
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
printf '%s
|
||||
' 'TODO: implement stop-one.sh for your infrastructure' >&2
|
||||
exit 2
|
||||
+7
-4
@@ -1,5 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
# Fault-injection hook: stop exactly ONE api replica of the lab5 stand.
|
||||
#
|
||||
# TARGET_INSTANCE_ID=<hostname|container name|short id> scripts/stop-one.sh
|
||||
@@ -15,18 +17,19 @@ set -eu
|
||||
|
||||
PROJECT=${COMPOSE_PROJECT_NAME:-mtusi-messenger-lab6}
|
||||
|
||||
candidates=$(docker ps -q \
|
||||
--filter "label=com.docker.compose.project=${PROJECT}" \
|
||||
--filter "label=com.docker.compose.service=api")
|
||||
candidates=$(python3 student-tests/tests_helpers.py compose ps -q api)
|
||||
|
||||
if [ -z "$candidates" ]; then
|
||||
printf 'stop-one.sh: no api containers of project %s are running\n' "$PROJECT" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
set -- $candidates
|
||||
PROJECT=$(docker inspect --format '{{index .Config.Labels "com.docker.compose.project"}}' "$1")
|
||||
|
||||
# Matches the requested alias against every reasonable identifier of a replica:
|
||||
# container hostname (= X-Instance-Id), full/short container id, full container
|
||||
# name (mtusi-messenger-lab4-api-1) and the service-local suffix (api-1).
|
||||
# name (project-api-1) and the service-local suffix (api-1).
|
||||
match_replica() {
|
||||
target=$1
|
||||
full_id=$2
|
||||
|
||||
@@ -3,5 +3,4 @@ set -eu
|
||||
# Fault-injection hook: stop the lab5 worker and leave it stopped.
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
COMPOSE_BIN=${COMPOSE_BIN:-docker compose}
|
||||
$COMPOSE_BIN --env-file .env -f compose.yaml stop worker
|
||||
exec python3 student-tests/tests_helpers.py compose stop worker
|
||||
|
||||
@@ -12,16 +12,20 @@
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
from lab7_environment import read_env
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DEFAULT_DIR = ROOT / 'evidence/track1'
|
||||
# Стенд трека 1 — только контейнеры своего проекта: параллельно поднятый стенд
|
||||
# другой лаборатории (тот же Docker-host) иначе попадал бы в те же колонки
|
||||
# (mtusi-messenger-lab2-postgres-1 -> postgres) и искажал бюджет и CPU.
|
||||
DEFAULT_PREFIX = 'mtusi-messenger-lab3-'
|
||||
DEFAULT_PREFIX = os.environ.get('COMPOSE_PROJECT_NAME', read_env(ROOT / '.env').get(
|
||||
'COMPOSE_PROJECT_NAME', 'mtusi-messenger-lab6')) + '-'
|
||||
MEMORY_UNITS = {'B': 1 / 1024 / 1024, 'KiB': 1 / 1024, 'MiB': 1, 'GiB': 1024}
|
||||
|
||||
|
||||
|
||||
+34
-31
@@ -12,7 +12,6 @@ set -eu
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
|
||||
COMPOSE_BIN=${COMPOSE_BIN:-docker compose}
|
||||
PYTHON=${PYTHON:-python3}
|
||||
REPLICAS=${REPLICAS:-"1 2 4"}
|
||||
TOTAL_CPU=${TOTAL_CPU:-2.0}
|
||||
@@ -20,7 +19,8 @@ TOTAL_MEM_MB=${TOTAL_MEM_MB:-1024}
|
||||
DURATION=${DURATION:-60}
|
||||
CONCURRENCY=${CONCURRENCY:-16}
|
||||
WARMUP=${WARMUP:-15}
|
||||
BASE_URL=${BASE_URL:-http://localhost:8080}
|
||||
BASE_URL=$("$PYTHON" -c 'import sys; sys.path.insert(0, "scripts"); from lab7_http import BASE_URL; print(BASE_URL)')
|
||||
CA_FILE=$("$PYTHON" -c 'import sys; sys.path.insert(0, "scripts"); from lab7_http import CA_FILE; print(CA_FILE)')
|
||||
LABEL=${LABEL:-}
|
||||
OUT=${OUT:-evidence/track1}
|
||||
|
||||
@@ -74,14 +74,13 @@ NO_PROXY_ENV="$NO_PROXY_ENV NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,
|
||||
mkdir -p "$OUT"
|
||||
|
||||
compose() {
|
||||
# shellcheck disable=SC2086
|
||||
$COMPOSE_BIN --env-file .env -f compose.yaml "$@"
|
||||
"$PYTHON" student-tests/tests_helpers.py compose "$@"
|
||||
}
|
||||
|
||||
wait_ready() {
|
||||
attempt=0
|
||||
while [ "$attempt" -lt 90 ]; do
|
||||
if curl -fsS --noproxy '*' -o /dev/null "$BASE_URL/health/ready"; then
|
||||
if curl -fsS --noproxy '*' --cacert "$CA_FILE" -o /dev/null "$BASE_URL/health/ready"; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
@@ -106,42 +105,47 @@ container_of() {
|
||||
compose ps -q "$1"
|
||||
}
|
||||
|
||||
# Сеть стенда: клиент внутри VM обращается к балансировщику по ней, без проброса
|
||||
# порта и без сетевого стека хоста.
|
||||
stand_network() {
|
||||
docker inspect "$(container_of api | head -1)" \
|
||||
--format '{{range $name, $network := .NetworkSettings.Networks}}{{$name}}{{end}}'
|
||||
# The VM client shares the LB namespace but mounts only public tests and CA.
|
||||
lb_container() {
|
||||
container_of lb
|
||||
}
|
||||
|
||||
# $1 — длительность, $2 — путь к JSON-метрикам (необязательно).
|
||||
load_client() {
|
||||
if [ "$CLIENT" = vm ]; then
|
||||
network=$(stand_network)
|
||||
|
||||
lb=$(lb_container)
|
||||
ca=$("$PYTHON" -c 'import pathlib,sys; print(pathlib.Path(sys.argv[1]).resolve(strict=True))' "$CA_FILE")
|
||||
out=$("$PYTHON" -c 'import pathlib,sys; print(pathlib.Path(sys.argv[1]).resolve())' "$OUT")
|
||||
set -- "$1" "$2"
|
||||
if [ -n "$2" ]; then
|
||||
# shellcheck disable=SC2086
|
||||
docker run --rm -i --network "$network" -v "$ROOT_DIR:/repo:ro" -v "$ROOT_DIR/$OUT:/out" \
|
||||
-e NO_PROXY='lb,localhost,127.0.0.1' -e no_proxy='lb,localhost,127.0.0.1' \
|
||||
"$CLIENT_IMAGE" python /repo/tests/load.py --base-url http://lb \
|
||||
--duration "$1" --concurrency "$CONCURRENCY" --output "/out/$(basename "$2")"
|
||||
destination="/out/$(basename "$2")"
|
||||
set -- "$1" --output "$destination"
|
||||
else
|
||||
# shellcheck disable=SC2086
|
||||
docker run --rm -i --network "$network" -v "$ROOT_DIR:/repo:ro" \
|
||||
-e NO_PROXY='lb,localhost,127.0.0.1' -e no_proxy='lb,localhost,127.0.0.1' \
|
||||
"$CLIENT_IMAGE" python /repo/tests/load.py --base-url http://lb \
|
||||
--duration "$1" --concurrency "$CONCURRENCY"
|
||||
set -- "$1"
|
||||
fi
|
||||
seconds=$1
|
||||
shift
|
||||
docker run --rm --network "container:$lb" \
|
||||
--cap-drop ALL --security-opt no-new-privileges:true --read-only --tmpfs /tmp \
|
||||
--mount "type=bind,source=$ROOT_DIR/tests,target=/repo/tests,readonly" \
|
||||
--mount "type=bind,source=$ROOT_DIR/contracts,target=/repo/contracts,readonly" \
|
||||
--mount "type=bind,source=$ROOT_DIR/lab.json,target=/repo/lab.json,readonly" \
|
||||
--mount "type=bind,source=$ca,target=/ca.crt,readonly" \
|
||||
--mount "type=bind,source=$out,target=/out" \
|
||||
-e NO_PROXY=localhost,127.0.0.1 -e PYTHONDONTWRITEBYTECODE=1 \
|
||||
"$CLIENT_IMAGE" python /repo/tests/load.py --base-url https://localhost:8443 \
|
||||
--ca-file /ca.crt --duration "$seconds" --concurrency "$CONCURRENCY" "$@"
|
||||
|
||||
return
|
||||
fi
|
||||
|
||||
if [ -n "$2" ]; then
|
||||
# shellcheck disable=SC2086
|
||||
$NO_PROXY_ENV $PYTHON tests/load.py --base-url "$BASE_URL" \
|
||||
$NO_PROXY_ENV $PYTHON tests/load.py --base-url "$BASE_URL" --ca-file "$CA_FILE" \
|
||||
--duration "$1" --concurrency "$CONCURRENCY" --output "$2"
|
||||
else
|
||||
# shellcheck disable=SC2086
|
||||
$NO_PROXY_ENV $PYTHON tests/load.py --base-url "$BASE_URL" \
|
||||
$NO_PROXY_ENV $PYTHON tests/load.py --base-url "$BASE_URL" --ca-file "$CA_FILE" \
|
||||
--duration "$1" --concurrency "$CONCURRENCY"
|
||||
fi
|
||||
}
|
||||
@@ -161,8 +165,7 @@ container_mem() {
|
||||
wait_postgres_ready() {
|
||||
attempt=0
|
||||
while [ "$attempt" -lt 90 ]; do
|
||||
if compose exec -T postgres pg_isready -U "${POSTGRES_USER:-messenger}" \
|
||||
-d "${POSTGRES_DB:-messenger}" >/dev/null 2>&1; then
|
||||
if printf 'SELECT 1;' | "$PYTHON" student-tests/tests_helpers.py psql >/dev/null 2>&1; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
@@ -216,7 +219,7 @@ if [ ! -f "$SUMMARY" ]; then
|
||||
echo "# each profile line below records the budget it was run with"
|
||||
docker version --format 'docker engine {{.Server.Version}}'
|
||||
# shellcheck disable=SC2086
|
||||
$COMPOSE_BIN version
|
||||
compose version
|
||||
echo
|
||||
} > "$SUMMARY"
|
||||
fi
|
||||
@@ -236,7 +239,7 @@ for replicas in $REPLICAS; do
|
||||
|
||||
apply_store_limits
|
||||
|
||||
API_REPLICAS="$replicas" API_CPU_LIMIT="$cpu" API_MEM_LIMIT="$mem" compose up -d --no-deps api
|
||||
API_REPLICAS="$replicas" API_CPU_LIMIT="$cpu" API_MEM_LIMIT="$mem" compose up -d --no-deps --scale "api=$replicas" api
|
||||
wait_ready
|
||||
|
||||
# Warm up caches, connection pools and the JIT-free query plans; the warmup
|
||||
@@ -289,11 +292,11 @@ for replicas in $REPLICAS; do
|
||||
|
||||
# Shared-dependency view right after the run: connections, pool pressure and
|
||||
# how much history the profile wrote into.
|
||||
compose exec -T postgres psql -U "${POSTGRES_USER:-messenger}" -d "${POSTGRES_DB:-messenger}" -Atc \
|
||||
"SELECT 'postgres_connections=' || count(*) FROM pg_stat_activity;
|
||||
printf '%s\n' "SELECT 'postgres_connections=' || count(*) FROM pg_stat_activity;
|
||||
SELECT 'postgres_max_connections=' || current_setting('max_connections');
|
||||
SELECT 'messages_rows=' || count(*) FROM messages;
|
||||
SELECT 'idempotency_rows=' || count(*) FROM message_idempotency;" | tee -a "$SUMMARY"
|
||||
SELECT 'idempotency_rows=' || count(*) FROM message_idempotency;" \
|
||||
| "$PYTHON" student-tests/tests_helpers.py psql | tee -a "$SUMMARY"
|
||||
|
||||
printf '\n' >> "$SUMMARY"
|
||||
done
|
||||
|
||||
Reference in New Issue
Block a user