forked from mtusi2026/mtusi2026lab7
test(security): automate lifecycle and login budget measurements
This commit is contained in:
+2
-2
@@ -44,7 +44,7 @@ services:
|
|||||||
image: valkey/valkey:8.1.12@sha256:5032c4dd7abe08d6fd9382054608183e2bf1f7e3895ef619b8784698454325f7
|
image: valkey/valkey:8.1.12@sha256:5032c4dd7abe08d6fd9382054608183e2bf1f7e3895ef619b8784698454325f7
|
||||||
command:
|
command:
|
||||||
- valkey-server
|
- valkey-server
|
||||||
- /run/secrets/valkey.conf
|
- /run/secrets/cache.conf
|
||||||
secrets:
|
secrets:
|
||||||
- source: cache_config
|
- source: cache_config
|
||||||
target: cache.conf
|
target: cache.conf
|
||||||
@@ -1499,7 +1499,7 @@ services:
|
|||||||
entrypoint:
|
entrypoint:
|
||||||
- python
|
- python
|
||||||
- -m
|
- -m
|
||||||
- src.operator
|
- src.operator_runtime
|
||||||
user: 10001:10001
|
user: 10001:10001
|
||||||
environment:
|
environment:
|
||||||
IDENTITY_ENABLED: '1'
|
IDENTITY_ENABLED: '1'
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ def prepare():
|
|||||||
values = {
|
values = {
|
||||||
"DATABASE_URL": "postgresql://messenger:"
|
"DATABASE_URL": "postgresql://messenger:"
|
||||||
+ quote(raw["postgres_password"], safe="")
|
+ quote(raw["postgres_password"], safe="")
|
||||||
+ "@postgres:5443/messenger?sslmode=verify-full&gssencmode=disable&sslrootcert=/trust/ca.pem&sslcert=/run/identity/current/cert.pem&sslkey=/run/identity/current/key.pem",
|
+ "@postgres:5443/messenger?sslmode=verify-full&gssencmode=disable&sslrootcert=/trust/ca.pem&sslcert=/run/identity/current/cert.pem&sslkey=/tmp/operator-client.key",
|
||||||
"BROKER_URL": "rediss://admin:"
|
"BROKER_URL": "rediss://admin:"
|
||||||
+ raw["broker_admin"]
|
+ raw["broker_admin"]
|
||||||
+ "@broker:6380/0",
|
+ "@broker:6380/0",
|
||||||
|
|||||||
@@ -0,0 +1,339 @@
|
|||||||
|
"""Measured PKI lifecycle under bounded public HTTPS message/upload load."""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import csv
|
||||||
|
import json
|
||||||
|
import socket
|
||||||
|
import ssl
|
||||||
|
import time
|
||||||
|
from collections import Counter
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from urllib.parse import urlsplit
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
from scripts import pki
|
||||||
|
from scripts.bao_operator import Operator
|
||||||
|
from scripts.bootstrap_security import TRUST
|
||||||
|
from scripts.credentials import repair, rotate_s3
|
||||||
|
from scripts.research_slo import Workload
|
||||||
|
from scripts.stand import BASE, ROOT, actor, auth, command, compose, ready
|
||||||
|
from scripts.tls_client import FreshTrustTransport
|
||||||
|
|
||||||
|
|
||||||
|
def images():
|
||||||
|
ids = compose("ps", "-q").split()
|
||||||
|
return {
|
||||||
|
c["Name"]: c["Image"]
|
||||||
|
for c in json.loads(command(["docker", "inspect", *ids]))
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--output", default="evidence/pki-research-first.json")
|
||||||
|
args = parser.parse_args()
|
||||||
|
output = ROOT / args.output
|
||||||
|
assert not output.exists(), "Choose a new receipt path"
|
||||||
|
output.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
report = {
|
||||||
|
"date": datetime.now(UTC).isoformat(),
|
||||||
|
"source_commit": command(["git", "rev-parse", "HEAD"]),
|
||||||
|
"complete": False,
|
||||||
|
"profile": {
|
||||||
|
"messages_per_second": 4,
|
||||||
|
"upload_every_seconds": 5,
|
||||||
|
"max_inflight": 16,
|
||||||
|
},
|
||||||
|
"phases": [],
|
||||||
|
}
|
||||||
|
started = time.time()
|
||||||
|
load = None
|
||||||
|
lb_stopped = False
|
||||||
|
bao_sealed = False
|
||||||
|
with httpx.Client(
|
||||||
|
base_url=BASE,
|
||||||
|
transport=FreshTrustTransport(),
|
||||||
|
timeout=8,
|
||||||
|
trust_env=False,
|
||||||
|
) as client:
|
||||||
|
|
||||||
|
def save():
|
||||||
|
report["elapsed_seconds"] = round(time.time() - started, 3)
|
||||||
|
output.write_text(
|
||||||
|
json.dumps(report, ensure_ascii=False, indent=2) + "\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
def phase(name, action):
|
||||||
|
load.phase = name
|
||||||
|
entry = {"name": name, "started_at": time.time()}
|
||||||
|
report["phases"].append(entry)
|
||||||
|
save()
|
||||||
|
try:
|
||||||
|
entry["result"] = action()
|
||||||
|
finally:
|
||||||
|
entry["ended_at"] = time.time()
|
||||||
|
entry["seconds"] = round(
|
||||||
|
entry["ended_at"] - entry["started_at"], 3
|
||||||
|
)
|
||||||
|
save()
|
||||||
|
|
||||||
|
try:
|
||||||
|
ready(timeout=90)
|
||||||
|
report["images_before"] = images()
|
||||||
|
user, _, session = actor(client)
|
||||||
|
headers = auth(session)
|
||||||
|
r = client.post(
|
||||||
|
"/api/v1/chats",
|
||||||
|
headers=headers,
|
||||||
|
json={"title": "PKI lifecycle", "member_ids": [user["id"]]},
|
||||||
|
)
|
||||||
|
assert r.status_code == 201
|
||||||
|
chat = r.json()["id"]
|
||||||
|
load = Workload(client, headers, chat)
|
||||||
|
load.start()
|
||||||
|
|
||||||
|
def renewal():
|
||||||
|
before = pki.metadata()
|
||||||
|
time.sleep(100)
|
||||||
|
after = pki.metadata()
|
||||||
|
roles = set(before) - {"migrate"}
|
||||||
|
assert roles and all(
|
||||||
|
before[r]["serial"] != after[r]["serial"] for r in roles
|
||||||
|
)
|
||||||
|
events = compose(
|
||||||
|
"logs",
|
||||||
|
"--no-color",
|
||||||
|
"--since",
|
||||||
|
datetime.fromtimestamp(started, UTC).isoformat(),
|
||||||
|
"identity-api",
|
||||||
|
)
|
||||||
|
assert '"event":"identity.token_renewed"' in events
|
||||||
|
return {
|
||||||
|
"before": before,
|
||||||
|
"after": after,
|
||||||
|
"all_active_serials_changed": True,
|
||||||
|
"api_token_renewed": True,
|
||||||
|
}
|
||||||
|
|
||||||
|
phase("automatic_renewal", renewal)
|
||||||
|
|
||||||
|
def secret_rotation():
|
||||||
|
operator = Operator()
|
||||||
|
try:
|
||||||
|
return rotate_s3(operator)
|
||||||
|
finally:
|
||||||
|
operator.close()
|
||||||
|
|
||||||
|
phase("working_s3_key_rotation", secret_rotation)
|
||||||
|
|
||||||
|
def revocation():
|
||||||
|
operator = Operator()
|
||||||
|
try:
|
||||||
|
repair(operator, "lb")
|
||||||
|
old = pki.preserve_lb()
|
||||||
|
repair(operator, "lb")
|
||||||
|
pki.fixture_check("lb")
|
||||||
|
return pki.revoke(operator, old)
|
||||||
|
finally:
|
||||||
|
operator.close()
|
||||||
|
|
||||||
|
phase("leaf_reissue_and_revocation", revocation)
|
||||||
|
|
||||||
|
def expiry():
|
||||||
|
nonlocal lb_stopped
|
||||||
|
compose("stop", "identity-lb")
|
||||||
|
lb_stopped = True
|
||||||
|
leaf = pki.metadata()["lb"]
|
||||||
|
wait_seconds = max(0, leaf["expires_at"] - time.time() + 3)
|
||||||
|
time.sleep(wait_seconds)
|
||||||
|
target = urlsplit(BASE)
|
||||||
|
context = ssl.create_default_context(cafile=TRUST / "ca.pem")
|
||||||
|
try:
|
||||||
|
with socket.create_connection(
|
||||||
|
(target.hostname, target.port), timeout=5
|
||||||
|
) as raw:
|
||||||
|
with context.wrap_socket(
|
||||||
|
raw, server_hostname=target.hostname
|
||||||
|
):
|
||||||
|
pass
|
||||||
|
except ssl.SSLCertVerificationError as error:
|
||||||
|
assert error.verify_code == 10, (
|
||||||
|
"Expected expired certificate"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
raise AssertionError(
|
||||||
|
"Expired server certificate was accepted"
|
||||||
|
)
|
||||||
|
recovery = time.monotonic()
|
||||||
|
operator = Operator()
|
||||||
|
try:
|
||||||
|
repair(operator, "lb")
|
||||||
|
finally:
|
||||||
|
operator.close()
|
||||||
|
compose("up", "-d", "--no-deps", "identity-lb")
|
||||||
|
lb_stopped = False
|
||||||
|
ready(timeout=60)
|
||||||
|
return {
|
||||||
|
"leaf": leaf,
|
||||||
|
"waited_seconds": round(wait_seconds, 3),
|
||||||
|
"expired_certificate_verified_denied": True,
|
||||||
|
"recovery_seconds": round(time.monotonic() - recovery, 3),
|
||||||
|
}
|
||||||
|
|
||||||
|
phase("expiry_without_plaintext_fallback", expiry)
|
||||||
|
|
||||||
|
def sealed():
|
||||||
|
nonlocal bao_sealed
|
||||||
|
operator = Operator()
|
||||||
|
try:
|
||||||
|
operator.authorized("POST", "sys/seal", {})
|
||||||
|
bao_sealed = True
|
||||||
|
finally:
|
||||||
|
operator.close()
|
||||||
|
time.sleep(70)
|
||||||
|
status, error_type = None, None
|
||||||
|
try:
|
||||||
|
status = client.get(
|
||||||
|
"/api/v1/users/me", headers=headers
|
||||||
|
).status_code
|
||||||
|
assert status == 503, (
|
||||||
|
"Expired secret snapshot must fail closed"
|
||||||
|
)
|
||||||
|
except httpx.HTTPError as error:
|
||||||
|
error_type = type(error).__name__
|
||||||
|
recovery = time.monotonic()
|
||||||
|
pki.recover_bao()
|
||||||
|
bao_sealed = False
|
||||||
|
ready(timeout=120)
|
||||||
|
return {
|
||||||
|
"sealed_seconds": 70,
|
||||||
|
"status_after_secret_expiry": status,
|
||||||
|
"tls_transport_failure": error_type,
|
||||||
|
"recovery_seconds": round(time.monotonic() - recovery, 3),
|
||||||
|
"explicit_operator_recovery": True,
|
||||||
|
}
|
||||||
|
|
||||||
|
phase("sealed_openbao_bounded_cache", sealed)
|
||||||
|
phase("dual_trust_ca_rollover", pki.rollover)
|
||||||
|
phase("recovered_steady", lambda: time.sleep(30))
|
||||||
|
load.close()
|
||||||
|
load.stop.set()
|
||||||
|
# Preserve every observed acknowledgement; ambiguous requests are
|
||||||
|
# counted separately and never presented as acknowledged writes.
|
||||||
|
messages = {row[5] for row in load.requests if row[2] == 201}
|
||||||
|
found, cursor = set(), None
|
||||||
|
while True:
|
||||||
|
r = client.get(
|
||||||
|
f"/api/v1/chats/{chat}/messages",
|
||||||
|
headers=headers,
|
||||||
|
params={
|
||||||
|
"limit": 100,
|
||||||
|
**({"cursor": cursor} if cursor else {}),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert r.status_code == 200
|
||||||
|
page = r.json()
|
||||||
|
found.update(item["id"] for item in page["items"])
|
||||||
|
cursor = page["next_cursor"]
|
||||||
|
if not cursor:
|
||||||
|
break
|
||||||
|
assert messages <= found
|
||||||
|
accepted = [row for row in load.uploads if row[2] == 202]
|
||||||
|
pending = {row[3] for row in accepted}
|
||||||
|
deadline = time.monotonic() + 120
|
||||||
|
failed = set()
|
||||||
|
while pending and time.monotonic() < deadline:
|
||||||
|
for identity in list(pending):
|
||||||
|
r = client.get(
|
||||||
|
"/api/v1/attachments/" + identity, headers=headers
|
||||||
|
)
|
||||||
|
assert r.status_code == 200
|
||||||
|
state = r.json()["status"]
|
||||||
|
if state == "ready":
|
||||||
|
pending.remove(identity)
|
||||||
|
elif state == "failed":
|
||||||
|
failed.add(identity)
|
||||||
|
if failed:
|
||||||
|
# Replay is an explicit audited operator action after the
|
||||||
|
# seal experiment; never change DB job state directly.
|
||||||
|
from scripts.operator_task import run
|
||||||
|
|
||||||
|
for identity in failed:
|
||||||
|
from scripts.stand import sql
|
||||||
|
|
||||||
|
job = sql(
|
||||||
|
"SELECT id FROM jobs WHERE attachment_id='"
|
||||||
|
+ identity
|
||||||
|
+ "' ORDER BY pipeline_version DESC LIMIT 1"
|
||||||
|
)
|
||||||
|
run(
|
||||||
|
"replay",
|
||||||
|
"--job-id",
|
||||||
|
job,
|
||||||
|
"--operator",
|
||||||
|
"synthetic-research",
|
||||||
|
"--reason",
|
||||||
|
"PKI research recovery after controlled seal",
|
||||||
|
)
|
||||||
|
failed.clear()
|
||||||
|
time.sleep(1)
|
||||||
|
assert not pending, "Accepted upload not ready after recovery"
|
||||||
|
for row in accepted[:: max(1, len(accepted) // 5)]:
|
||||||
|
r = client.get(
|
||||||
|
"/api/v1/attachments/" + row[3] + "/content",
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
assert r.status_code == 200 and r.content == load.raw
|
||||||
|
report["preservation"] = {
|
||||||
|
"acknowledged_messages": len(messages),
|
||||||
|
"accepted_uploads": len(accepted),
|
||||||
|
"all_acknowledged_messages_present": True,
|
||||||
|
"all_accepted_uploads_ready": True,
|
||||||
|
"sampled_original_bytes_unchanged": True,
|
||||||
|
}
|
||||||
|
report["images_after"] = images()
|
||||||
|
assert report["images_before"] == report["images_after"], (
|
||||||
|
"Lifecycle must not rebuild/replace images"
|
||||||
|
)
|
||||||
|
report["complete"] = True
|
||||||
|
except BaseException as error:
|
||||||
|
report["failure_type"] = type(error).__name__
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
if load is not None:
|
||||||
|
load.close()
|
||||||
|
report["request_statuses"] = dict(
|
||||||
|
Counter(str(row[2]) for row in load.requests)
|
||||||
|
)
|
||||||
|
report["upload_statuses"] = dict(
|
||||||
|
Counter(str(row[2]) for row in load.uploads)
|
||||||
|
)
|
||||||
|
with output.with_name(output.stem + "-requests.csv").open(
|
||||||
|
"w"
|
||||||
|
) as stream:
|
||||||
|
writer = csv.writer(stream)
|
||||||
|
writer.writerow(
|
||||||
|
[
|
||||||
|
"started_at",
|
||||||
|
"phase",
|
||||||
|
"status",
|
||||||
|
"duration_seconds",
|
||||||
|
"trace_id",
|
||||||
|
"message_id",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
writer.writerows(load.requests)
|
||||||
|
report["uploads"] = load.uploads
|
||||||
|
save()
|
||||||
|
if lb_stopped:
|
||||||
|
compose("up", "-d", "--no-deps", "identity-lb")
|
||||||
|
if bao_sealed:
|
||||||
|
pki.recover_bao()
|
||||||
|
print(
|
||||||
|
"PASS: measured renewal, working-key/leaf rotation, revocation, expiry, seal recovery and CA rollover"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
+2
-31
@@ -87,8 +87,8 @@ def sql(query, *, database="messenger"):
|
|||||||
|
|
||||||
def cache(command_name, *args):
|
def cache(command_name, *args):
|
||||||
script = (
|
script = (
|
||||||
'export REDISCLI_AUTH="$(cat /run/secrets/cache_password)"; '
|
'export REDISCLI_AUTH="$(cat /run/secrets/cache_admin)"; '
|
||||||
'exec valkey-cli "$@"'
|
'exec valkey-cli --user admin "$@"'
|
||||||
)
|
)
|
||||||
return compose(
|
return compose(
|
||||||
"exec", "-T", "cache", "sh", "-c", script, "sh", command_name, *args
|
"exec", "-T", "cache", "sh", "-c", script, "sh", command_name, *args
|
||||||
@@ -137,35 +137,6 @@ def auth(session):
|
|||||||
return {"Authorization": "Bearer " + session["token"]}
|
return {"Authorization": "Bearer " + session["token"]}
|
||||||
|
|
||||||
|
|
||||||
def extra_api(*, ttl=3600, pool_size=1):
|
|
||||||
name = "mtusi-lab6-test-" + uuid4().hex[:10]
|
|
||||||
compose(
|
|
||||||
"run",
|
|
||||||
"-d",
|
|
||||||
"--no-deps",
|
|
||||||
"--name",
|
|
||||||
name,
|
|
||||||
"-e",
|
|
||||||
"SESSION_TTL_SECONDS=" + str(ttl),
|
|
||||||
"-e",
|
|
||||||
"DB_POOL_SIZE=" + str(pool_size),
|
|
||||||
"-p",
|
|
||||||
"127.0.0.1::8080",
|
|
||||||
"api",
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
info = json.loads(command(["docker", "inspect", name]))[0]
|
|
||||||
base = (
|
|
||||||
"http://127.0.0.1:"
|
|
||||||
+ info["NetworkSettings"]["Ports"]["8080/tcp"][0]["HostPort"]
|
|
||||||
)
|
|
||||||
ready(base)
|
|
||||||
return name, base
|
|
||||||
except Exception:
|
|
||||||
command(["docker", "rm", "-f", name])
|
|
||||||
raise
|
|
||||||
|
|
||||||
|
|
||||||
def instances():
|
def instances():
|
||||||
data = {}
|
data = {}
|
||||||
for role in ["api", "postgres", "cache"]:
|
for role in ["api", "postgres", "cache"]:
|
||||||
|
|||||||
+125
-20
@@ -37,23 +37,57 @@ def save_incomplete():
|
|||||||
atexit.register(save_incomplete)
|
atexit.register(save_incomplete)
|
||||||
|
|
||||||
|
|
||||||
def run(args, *, cwd, env, expected=0):
|
def redact(text, cwd):
|
||||||
result = subprocess.run(
|
def values(value):
|
||||||
args, cwd=cwd, env=env, capture_output=True, text=True
|
if isinstance(value, dict):
|
||||||
)
|
for item in value.values():
|
||||||
|
yield from values(item)
|
||||||
|
elif isinstance(value, list):
|
||||||
|
for item in value:
|
||||||
|
yield from values(item)
|
||||||
|
elif isinstance(value, str) and len(value) >= 12:
|
||||||
|
yield value
|
||||||
|
|
||||||
def redact(text):
|
for folder in [cwd / "secrets", cwd / "operator"]:
|
||||||
|
for path in folder.rglob("*"):
|
||||||
|
if not path.is_file():
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
raw = path.read_text().strip()
|
||||||
|
except UnicodeDecodeError:
|
||||||
|
continue
|
||||||
|
if path.suffix == ".json":
|
||||||
|
try:
|
||||||
|
for value in values(json.loads(raw)):
|
||||||
|
text = text.replace(value, "<private-value>")
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
if len(raw) >= 12:
|
||||||
|
text = text.replace(raw, "<private-file>")
|
||||||
return (
|
return (
|
||||||
text.replace(str(cwd), "<clean-clone>")
|
text.replace(str(cwd), "<clean-clone>")
|
||||||
.replace(str(ROOT), "<repository>")
|
.replace(str(ROOT), "<repository>")
|
||||||
.replace(str(Path.home()), "<home>")
|
.replace(str(Path.home()), "<home>")
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def run(args, *, cwd, env, expected=0):
|
||||||
|
print("CHECK: " + redact(" ".join(args[:3]), cwd), flush=True)
|
||||||
|
result = subprocess.run(
|
||||||
|
args, cwd=cwd, env=env, capture_output=True, text=True
|
||||||
|
)
|
||||||
|
|
||||||
if result.returncode != expected:
|
if result.returncode != expected:
|
||||||
if "receipt" in PROGRESS:
|
if "receipt" in PROGRESS:
|
||||||
PROGRESS["receipt"]["failed_action"] = redact(" ".join(args))
|
PROGRESS["receipt"]["failed_action"] = redact(" ".join(args), cwd)
|
||||||
raise RuntimeError(redact(result.stdout + result.stderr))
|
raise RuntimeError(redact(result.stdout + result.stderr, cwd))
|
||||||
return redact(result.stdout.strip())
|
return redact(result.stdout.strip(), cwd)
|
||||||
|
|
||||||
|
|
||||||
|
def free_port():
|
||||||
|
with socket.socket() as reservation:
|
||||||
|
reservation.bind(("127.0.0.1", 0))
|
||||||
|
return reservation.getsockname()[1]
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
@@ -70,7 +104,7 @@ def main():
|
|||||||
["git", "rev-parse", "HEAD"], cwd=ROOT, text=True
|
["git", "rev-parse", "HEAD"], cwd=ROOT, text=True
|
||||||
).strip()
|
).strip()
|
||||||
identity = uuid4().hex[:10]
|
identity = uuid4().hex[:10]
|
||||||
project = "mtusi-lab6-clean-" + identity
|
project = "mtusi-lab7-clean-" + identity
|
||||||
with socket.socket() as reservation:
|
with socket.socket() as reservation:
|
||||||
reservation.bind(("127.0.0.1", 0))
|
reservation.bind(("127.0.0.1", 0))
|
||||||
public_port = str(reservation.getsockname()[1])
|
public_port = str(reservation.getsockname()[1])
|
||||||
@@ -80,9 +114,12 @@ def main():
|
|||||||
env = {
|
env = {
|
||||||
**os.environ,
|
**os.environ,
|
||||||
"COMPOSE_PROJECT_NAME": project,
|
"COMPOSE_PROJECT_NAME": project,
|
||||||
"API_IMAGE": "mtusi-messenger:lab6-clean-" + identity,
|
"API_IMAGE": "mtusi-messenger:lab7-clean-" + identity,
|
||||||
"PUBLIC_PORT": public_port,
|
"PUBLIC_PORT": public_port,
|
||||||
"GRAFANA_PORT": grafana_port,
|
"GRAFANA_PORT": grafana_port,
|
||||||
|
"BASE_URL": "https://localhost:" + public_port,
|
||||||
|
"BAO_PORT": str(free_port()),
|
||||||
|
"S3_ADMIN_PORT": str(free_port()),
|
||||||
"VCS_REF": sha,
|
"VCS_REF": sha,
|
||||||
"COMPOSE_FILE": "compose.yaml:compose.test.yaml",
|
"COMPOSE_FILE": "compose.yaml:compose.test.yaml",
|
||||||
"NO_PROXY": "localhost,127.0.0.1",
|
"NO_PROXY": "localhost,127.0.0.1",
|
||||||
@@ -96,8 +133,8 @@ def main():
|
|||||||
"fixed_host_port_for_restart": int(public_port),
|
"fixed_host_port_for_restart": int(public_port),
|
||||||
}
|
}
|
||||||
PROGRESS.update(receipt=receipt, output=output)
|
PROGRESS.update(receipt=receipt, output=output)
|
||||||
with tempfile.TemporaryDirectory(prefix="mtusi-lab6-clean-") as temporary:
|
with tempfile.TemporaryDirectory(prefix="mtusi-lab7-clean-") as temporary:
|
||||||
clone = Path(temporary) / "lab6"
|
clone = Path(temporary) / "lab7"
|
||||||
run(
|
run(
|
||||||
[
|
[
|
||||||
"git",
|
"git",
|
||||||
@@ -123,11 +160,12 @@ def main():
|
|||||||
run(["make", "bootstrap"], cwd=clone, env=env)
|
run(["make", "bootstrap"], cwd=clone, env=env)
|
||||||
try:
|
try:
|
||||||
run(
|
run(
|
||||||
["docker", "compose", "up", "-d", "--build", "--wait"],
|
[".venv/bin/python", "-m", "scripts.up_security", "--build"],
|
||||||
cwd=clone,
|
cwd=clone,
|
||||||
env=env,
|
env=env,
|
||||||
)
|
)
|
||||||
env["BASE_URL"] = "http://127.0.0.1:" + public_port
|
env["BASE_URL"] = "https://localhost:" + public_port
|
||||||
|
env["CA_FILE"] = str(clone / "trust/ca.pem")
|
||||||
receipt["smoke"] = run(
|
receipt["smoke"] = run(
|
||||||
["make", "test", "BASE_URL=" + env["BASE_URL"]],
|
["make", "test", "BASE_URL=" + env["BASE_URL"]],
|
||||||
cwd=clone,
|
cwd=clone,
|
||||||
@@ -136,18 +174,40 @@ def main():
|
|||||||
receipt["http_tests"] = run(
|
receipt["http_tests"] = run(
|
||||||
[".venv/bin/pytest", "student-tests", "-q"], cwd=clone, env=env
|
[".venv/bin/pytest", "student-tests", "-q"], cwd=clone, env=env
|
||||||
)
|
)
|
||||||
|
receipt["login_budget"] = run(
|
||||||
|
[
|
||||||
|
".venv/bin/python",
|
||||||
|
"-m",
|
||||||
|
"scripts.verify_login_budget",
|
||||||
|
"--output",
|
||||||
|
"evidence/clean-login-budget.json",
|
||||||
|
],
|
||||||
|
cwd=clone,
|
||||||
|
env=env,
|
||||||
|
)
|
||||||
|
receipt["public_security"] = run(
|
||||||
|
[
|
||||||
|
"make",
|
||||||
|
"test-security",
|
||||||
|
"PYTHON=.venv/bin/python",
|
||||||
|
"BASE_URL=" + env["BASE_URL"],
|
||||||
|
],
|
||||||
|
cwd=clone,
|
||||||
|
env=env,
|
||||||
|
)
|
||||||
for module, extra in [
|
for module, extra in [
|
||||||
|
("verify_security", []),
|
||||||
("verify_telemetry", []),
|
("verify_telemetry", []),
|
||||||
(
|
(
|
||||||
"verify_observability_persistence",
|
"verify_observability_persistence",
|
||||||
["--causal-evidence", "evidence/clean-telemetry.json"],
|
["--causal-evidence", "evidence/clean-telemetry.json"],
|
||||||
),
|
),
|
||||||
]:
|
]:
|
||||||
name = (
|
name = {
|
||||||
"telemetry"
|
"verify_security": "security",
|
||||||
if module == "verify_telemetry"
|
"verify_telemetry": "telemetry",
|
||||||
else "observability-persistence"
|
"verify_observability_persistence": "observability-persistence",
|
||||||
)
|
}[module]
|
||||||
run(
|
run(
|
||||||
[
|
[
|
||||||
".venv/bin/python",
|
".venv/bin/python",
|
||||||
@@ -267,8 +327,53 @@ def main():
|
|||||||
["git", "fsck", "--full"], cwd=clone, env=env
|
["git", "fsck", "--full"], cwd=clone, env=env
|
||||||
)
|
)
|
||||||
receipt["checks_completed"] = True
|
receipt["checks_completed"] = True
|
||||||
|
except BaseException:
|
||||||
|
receipt["partial_evidence"] = {}
|
||||||
|
for name in [
|
||||||
|
"security",
|
||||||
|
"login-budget",
|
||||||
|
"telemetry",
|
||||||
|
"observability-persistence",
|
||||||
|
"cluster",
|
||||||
|
"pipeline",
|
||||||
|
"cleanup",
|
||||||
|
"gc-seed",
|
||||||
|
]:
|
||||||
|
partial = clone / "evidence" / ("clean-" + name + ".json")
|
||||||
|
if partial.exists():
|
||||||
|
receipt["partial_evidence"][name] = json.loads(
|
||||||
|
redact(partial.read_text(), clone)
|
||||||
|
)
|
||||||
|
receipt["failure_diagnostics"] = {}
|
||||||
|
for label, arguments in [
|
||||||
|
("services", ["ps", "-a", "--format", "json"]),
|
||||||
|
(
|
||||||
|
"logs",
|
||||||
|
[
|
||||||
|
"logs",
|
||||||
|
"--no-color",
|
||||||
|
"--tail",
|
||||||
|
"60",
|
||||||
|
"api",
|
||||||
|
"s3",
|
||||||
|
"migrate",
|
||||||
|
"cache",
|
||||||
|
],
|
||||||
|
),
|
||||||
|
]:
|
||||||
|
diagnostic = subprocess.run(
|
||||||
|
["docker", "compose", *arguments],
|
||||||
|
cwd=clone,
|
||||||
|
env=env,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
receipt["failure_diagnostics"][label] = redact(
|
||||||
|
diagnostic.stdout + diagnostic.stderr, clone
|
||||||
|
)
|
||||||
|
raise
|
||||||
finally:
|
finally:
|
||||||
assert project.startswith("mtusi-lab6-clean-")
|
assert project.startswith("mtusi-lab7-clean-")
|
||||||
run(
|
run(
|
||||||
["docker", "compose", "down", "--volumes", "--remove-orphans"],
|
["docker", "compose", "down", "--volumes", "--remove-orphans"],
|
||||||
cwd=clone,
|
cwd=clone,
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import httpx
|
|||||||
|
|
||||||
from scripts import cluster
|
from scripts import cluster
|
||||||
from scripts.stand import BASE, ROOT, actor, auth, command, compose, ready, sql
|
from scripts.stand import BASE, ROOT, actor, auth, command, compose, ready, sql
|
||||||
|
from scripts.tls_client import FreshTrustTransport
|
||||||
|
|
||||||
|
|
||||||
def snapshot():
|
def snapshot():
|
||||||
@@ -148,7 +149,12 @@ def main():
|
|||||||
apis = [c for c in initial if c["role"] == "api"]
|
apis = [c for c in initial if c["role"] == "api"]
|
||||||
assert len(apis) == 2 and len({c["pid"] for c in apis}) == 2
|
assert len(apis) == 2 and len({c["pid"] for c in apis}) == 2
|
||||||
report["before"] = initial
|
report["before"] = initial
|
||||||
with httpx.Client(base_url=BASE, trust_env=False, timeout=8) as client:
|
with httpx.Client(
|
||||||
|
base_url=BASE,
|
||||||
|
trust_env=False,
|
||||||
|
timeout=8,
|
||||||
|
transport=FreshTrustTransport(),
|
||||||
|
) as client:
|
||||||
user, _, session = actor(client)
|
user, _, session = actor(client)
|
||||||
r = client.post(
|
r = client.post(
|
||||||
"/api/v1/chats",
|
"/api/v1/chats",
|
||||||
@@ -165,7 +171,10 @@ def main():
|
|||||||
|
|
||||||
def repeat(_):
|
def repeat(_):
|
||||||
with httpx.Client(
|
with httpx.Client(
|
||||||
base_url=BASE, trust_env=False, timeout=8
|
base_url=BASE,
|
||||||
|
trust_env=False,
|
||||||
|
timeout=8,
|
||||||
|
transport=FreshTrustTransport(),
|
||||||
) as c:
|
) as c:
|
||||||
r = c.post(
|
r = c.post(
|
||||||
path,
|
path,
|
||||||
@@ -321,6 +330,8 @@ def main():
|
|||||||
hook,
|
hook,
|
||||||
"--base-url",
|
"--base-url",
|
||||||
BASE,
|
BASE,
|
||||||
|
"--ca-file",
|
||||||
|
str(ROOT / "trust/ca.pem"),
|
||||||
],
|
],
|
||||||
cwd=ROOT,
|
cwd=ROOT,
|
||||||
env=env,
|
env=env,
|
||||||
|
|||||||
@@ -0,0 +1,227 @@
|
|||||||
|
"""Real old-hash migration and shared login admission/resource measurement."""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import statistics
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from collections import Counter
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
from argon2 import PasswordHasher
|
||||||
|
|
||||||
|
from scripts.stand import BASE, ROOT, command, compose, ready, sql
|
||||||
|
from scripts.tls_client import FreshTrustTransport
|
||||||
|
|
||||||
|
|
||||||
|
def resources():
|
||||||
|
ids = compose("ps", "-q", "api").split()
|
||||||
|
result = []
|
||||||
|
for cid in ids:
|
||||||
|
raw = command(
|
||||||
|
[
|
||||||
|
"docker",
|
||||||
|
"exec",
|
||||||
|
cid,
|
||||||
|
"python",
|
||||||
|
"-c",
|
||||||
|
"import json,pathlib;p=pathlib.Path('/sys/fs/cgroup');print(json.dumps({'memory_current':int((p/'memory.current').read_text()),'cpu_stat':dict(line.split() for line in (p/'cpu.stat').read_text().splitlines())}))",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
info = json.loads(command(["docker", "inspect", cid]))[0]
|
||||||
|
result.append(
|
||||||
|
{
|
||||||
|
"container": cid[:12],
|
||||||
|
"cpu_nano": info["HostConfig"]["NanoCpus"],
|
||||||
|
"memory_limit": info["HostConfig"]["Memory"],
|
||||||
|
**json.loads(raw),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
assert len(result) == 2
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--output", default="evidence/login-budget-first.json")
|
||||||
|
args = parser.parse_args()
|
||||||
|
output = ROOT / args.output
|
||||||
|
assert not output.exists(), "Choose a new receipt path"
|
||||||
|
output.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
report = {
|
||||||
|
"date": datetime.now(UTC).isoformat(),
|
||||||
|
"source_commit": command(["git", "rev-parse", "HEAD"]),
|
||||||
|
"complete": False,
|
||||||
|
"measurements": [],
|
||||||
|
}
|
||||||
|
with httpx.Client(
|
||||||
|
base_url=BASE,
|
||||||
|
transport=FreshTrustTransport(),
|
||||||
|
trust_env=False,
|
||||||
|
timeout=12,
|
||||||
|
) as client:
|
||||||
|
try:
|
||||||
|
ready(timeout=90)
|
||||||
|
username = "legacy_" + uuid4().hex[:20]
|
||||||
|
password = "Synthetic-password-" + uuid4().hex
|
||||||
|
r = client.post(
|
||||||
|
"/api/v1/users",
|
||||||
|
json={
|
||||||
|
"username": username,
|
||||||
|
"display_name": "Synthetic migration",
|
||||||
|
"password": password,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert r.status_code == 201
|
||||||
|
uid = r.json()["id"]
|
||||||
|
previous = PasswordHasher(
|
||||||
|
time_cost=2, memory_cost=19456, parallelism=1
|
||||||
|
).hash(password)
|
||||||
|
sql(
|
||||||
|
"UPDATE users SET password_hash='"
|
||||||
|
+ previous
|
||||||
|
+ "' WHERE id='"
|
||||||
|
+ uid
|
||||||
|
+ "'"
|
||||||
|
)
|
||||||
|
r = client.post(
|
||||||
|
"/api/v1/auth/sessions",
|
||||||
|
auth=httpx.BasicAuth(username, password + "-wrong"),
|
||||||
|
)
|
||||||
|
assert r.status_code == 401
|
||||||
|
assert (
|
||||||
|
sql("SELECT password_hash FROM users WHERE id='" + uid + "'")
|
||||||
|
== previous
|
||||||
|
)
|
||||||
|
began = time.monotonic()
|
||||||
|
r = client.post(
|
||||||
|
"/api/v1/auth/sessions",
|
||||||
|
auth=httpx.BasicAuth(username, password),
|
||||||
|
)
|
||||||
|
assert r.status_code == 201
|
||||||
|
elapsed = time.monotonic() - began
|
||||||
|
current = sql(
|
||||||
|
"SELECT password_hash FROM users WHERE id='" + uid + "'"
|
||||||
|
)
|
||||||
|
assert current != previous and "$m=65536,t=3,p=4$" in current
|
||||||
|
assert PasswordHasher().verify(current, password)
|
||||||
|
report["rehash"] = {
|
||||||
|
"old_parameters": "argon2id m=19456KiB,t=2,p=1",
|
||||||
|
"new_parameters": "argon2id m=65536KiB,t=3,p=4",
|
||||||
|
"wrong_password_kept_old_hash": True,
|
||||||
|
"valid_login_updated_hash": True,
|
||||||
|
"valid_login_seconds_including_rehash": round(elapsed, 6),
|
||||||
|
}
|
||||||
|
# Operator resets only synthetic limiter state to define a known
|
||||||
|
# initial burst. No API/rate configuration is changed for the test.
|
||||||
|
sql("TRUNCATE login_buckets")
|
||||||
|
report["before"] = resources()
|
||||||
|
stop = threading.Event()
|
||||||
|
health = []
|
||||||
|
|
||||||
|
def healthy():
|
||||||
|
while not stop.is_set():
|
||||||
|
t = time.monotonic()
|
||||||
|
response = client.get("/health/ready")
|
||||||
|
health.append(
|
||||||
|
{
|
||||||
|
"status": response.status_code,
|
||||||
|
"seconds": time.monotonic() - t,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
stop.wait(0.25)
|
||||||
|
|
||||||
|
observer = threading.Thread(target=healthy)
|
||||||
|
observer.start()
|
||||||
|
started = time.monotonic()
|
||||||
|
|
||||||
|
def login(i):
|
||||||
|
name = (
|
||||||
|
"absent_"
|
||||||
|
+ hashlib.sha256((username + str(i)).encode()).hexdigest()[
|
||||||
|
:20
|
||||||
|
]
|
||||||
|
)
|
||||||
|
t = time.monotonic()
|
||||||
|
r = client.post(
|
||||||
|
"/api/v1/auth/sessions",
|
||||||
|
auth=httpx.BasicAuth(name, password),
|
||||||
|
)
|
||||||
|
result = {
|
||||||
|
"status": r.status_code,
|
||||||
|
"seconds": time.monotonic() - t,
|
||||||
|
"instance": r.headers.get("x-instance-id"),
|
||||||
|
"retry_after": r.headers.get("retry-after"),
|
||||||
|
}
|
||||||
|
assert r.status_code in {401, 429}
|
||||||
|
if r.status_code == 429:
|
||||||
|
assert int(r.headers["retry-after"]) >= 1
|
||||||
|
return result
|
||||||
|
|
||||||
|
try:
|
||||||
|
with ThreadPoolExecutor(max_workers=12) as pool:
|
||||||
|
report["measurements"] = list(pool.map(login, range(72)))
|
||||||
|
finally:
|
||||||
|
stop.set()
|
||||||
|
observer.join(15)
|
||||||
|
duration = time.monotonic() - started
|
||||||
|
report["after"] = resources()
|
||||||
|
admitted = [
|
||||||
|
x for x in report["measurements"] if x["status"] == 401
|
||||||
|
]
|
||||||
|
limited = [x for x in report["measurements"] if x["status"] == 429]
|
||||||
|
assert limited and admitted
|
||||||
|
assert len(admitted) <= 8 + int(2 * duration) + 1
|
||||||
|
assert len({x["instance"] for x in report["measurements"]}) == 2
|
||||||
|
assert health and all(x["status"] == 200 for x in health)
|
||||||
|
buckets = int(
|
||||||
|
sql(
|
||||||
|
"SELECT count(*) FROM login_buckets WHERE bucket<>'global'"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
assert buckets == len(admitted), (
|
||||||
|
"Rejected random accounts must not allocate buckets"
|
||||||
|
)
|
||||||
|
report["flood"] = {
|
||||||
|
"requests": 72,
|
||||||
|
"concurrency": 12,
|
||||||
|
"seconds": round(duration, 6),
|
||||||
|
"statuses": dict(
|
||||||
|
Counter(str(x["status"]) for x in report["measurements"])
|
||||||
|
),
|
||||||
|
"both_replicas_observed": True,
|
||||||
|
"new_account_buckets": buckets,
|
||||||
|
"shared_admission_bound": 8 + int(2 * duration) + 1,
|
||||||
|
"limited_median_seconds": statistics.median(
|
||||||
|
x["seconds"] for x in limited
|
||||||
|
),
|
||||||
|
"admitted_median_seconds": statistics.median(
|
||||||
|
x["seconds"] for x in admitted
|
||||||
|
),
|
||||||
|
"health": health,
|
||||||
|
"cpu_usage_seconds": sum(
|
||||||
|
int(a["cpu_stat"]["usage_usec"])
|
||||||
|
- int(b["cpu_stat"]["usage_usec"])
|
||||||
|
for a, b in zip(
|
||||||
|
report["after"], report["before"], strict=True
|
||||||
|
)
|
||||||
|
)
|
||||||
|
/ 1e6,
|
||||||
|
"memory_measurement": "cgroup current before/after, not a peak measurement",
|
||||||
|
}
|
||||||
|
report["complete"] = True
|
||||||
|
finally:
|
||||||
|
output.write_text(
|
||||||
|
json.dumps(report, ensure_ascii=False, indent=2) + "\n"
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
"PASS: old-hash upgrade, shared pre-KDF rate limit and measured login resource budget"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -21,6 +21,8 @@ os.environ.setdefault("no_proxy", "localhost,127.0.0.1")
|
|||||||
from scripts.stand import BASE, ROOT, actor, auth, command, compose, ready
|
from scripts.stand import BASE, ROOT, actor, auth, command, compose, ready
|
||||||
|
|
||||||
PREFIX = """import io,json,hashlib,time,urllib.request
|
PREFIX = """import io,json,hashlib,time,urllib.request
|
||||||
|
from src.operator_runtime import prepare_key
|
||||||
|
prepare_key()
|
||||||
from uuid import UUID,uuid4
|
from uuid import UUID,uuid4
|
||||||
from psycopg.types.json import Jsonb
|
from psycopg.types.json import Jsonb
|
||||||
from src.pipeline import database,broker,envelope,STREAM,GROUP
|
from src.pipeline import database,broker,envelope,STREAM,GROUP
|
||||||
@@ -32,6 +34,9 @@ db,store,queue=database(),ObjectStore(),broker()
|
|||||||
|
|
||||||
|
|
||||||
def inside(code):
|
def inside(code):
|
||||||
|
from scripts.operator_task import prepare
|
||||||
|
|
||||||
|
prepare()
|
||||||
cid = compose("ps", "-q", "controller").split()[0]
|
cid = compose("ps", "-q", "controller").split()[0]
|
||||||
return json.loads(
|
return json.loads(
|
||||||
command(
|
command(
|
||||||
|
|||||||
@@ -2,9 +2,11 @@
|
|||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
import json
|
import json
|
||||||
|
import subprocess
|
||||||
from datetime import UTC, datetime
|
from datetime import UTC, datetime
|
||||||
|
|
||||||
from scripts.bootstrap_security import (
|
from scripts.bootstrap_security import (
|
||||||
|
OPERATOR,
|
||||||
SECRET,
|
SECRET,
|
||||||
key_bytes,
|
key_bytes,
|
||||||
make_root,
|
make_root,
|
||||||
@@ -12,7 +14,8 @@ from scripts.bootstrap_security import (
|
|||||||
sign_leaf,
|
sign_leaf,
|
||||||
write_private,
|
write_private,
|
||||||
)
|
)
|
||||||
from scripts.stand import ROOT, command, compose
|
from scripts.stand import ROOT, command
|
||||||
|
from scripts.verify_clean import redact
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
@@ -32,23 +35,43 @@ def main():
|
|||||||
mode=0o644,
|
mode=0o644,
|
||||||
)
|
)
|
||||||
write_private(fixture / "foreign/key.pem", key_bytes(key), mode=0o644)
|
write_private(fixture / "foreign/key.pem", key_bytes(key), mode=0o644)
|
||||||
result = json.loads(
|
for name in ["cert.pem", "key.pem"]:
|
||||||
compose(
|
write_private(
|
||||||
|
fixture / "operator" / name,
|
||||||
|
(OPERATOR / "client" / name).read_bytes(),
|
||||||
|
mode=0o644,
|
||||||
|
)
|
||||||
|
process = subprocess.run(
|
||||||
|
[
|
||||||
|
"docker",
|
||||||
|
"compose",
|
||||||
"--profile",
|
"--profile",
|
||||||
"operator",
|
"operator",
|
||||||
"run",
|
"run",
|
||||||
"--rm",
|
"--rm",
|
||||||
"--no-deps",
|
"--no-deps",
|
||||||
"operator-probe",
|
"operator-probe",
|
||||||
|
],
|
||||||
|
cwd=ROOT,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
)
|
)
|
||||||
)
|
try:
|
||||||
|
result = json.loads(process.stdout)
|
||||||
|
except ValueError:
|
||||||
|
result = {"complete": False}
|
||||||
|
result["probe_exit_code"] = process.returncode
|
||||||
|
if process.returncode:
|
||||||
|
result["failure"] = redact(process.stderr, ROOT)
|
||||||
result.update(
|
result.update(
|
||||||
date=datetime.now(UTC).isoformat(),
|
date=datetime.now(UTC).isoformat(),
|
||||||
source_commit=command(["git", "rev-parse", "HEAD"]),
|
source_commit=command(["git", "rev-parse", "HEAD"]),
|
||||||
)
|
)
|
||||||
output.parent.mkdir(parents=True, exist_ok=True)
|
output.parent.mkdir(parents=True, exist_ok=True)
|
||||||
output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
|
output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
|
||||||
assert result["complete"]
|
assert process.returncode == 0 and result["complete"], (
|
||||||
|
"Security probe failed; see saved receipt"
|
||||||
|
)
|
||||||
print(
|
print(
|
||||||
"PASS: real mTLS identities, server CA/hostname, closed plaintext boundaries and worker least privilege"
|
"PASS: real mTLS identities, server CA/hostname, closed plaintext boundaries and worker least privilege"
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
"""Prepare an owner-only libpq key inside the explicit operator task tmpfs."""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import runpy
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def prepare_key():
|
||||||
|
# Docker Desktop bind ownership differs from the rootless container UID.
|
||||||
|
# The source stays beneath the host operator directory; only this explicit
|
||||||
|
# task mounts it. libpq receives an owned 0600 file in ephemeral tmpfs.
|
||||||
|
target = Path("/tmp/operator-client.key")
|
||||||
|
temporary = target.with_name(target.name + "." + str(os.getpid()))
|
||||||
|
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||||
|
try:
|
||||||
|
with os.fdopen(fd, "wb") as stream:
|
||||||
|
stream.write(Path("/run/identity/current/key.pem").read_bytes())
|
||||||
|
temporary.replace(target)
|
||||||
|
finally:
|
||||||
|
temporary.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
prepare_key()
|
||||||
|
runpy.run_module("src.operator", run_name="__main__")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
+14
-5
@@ -32,7 +32,7 @@ def context(role=None, *, foreign=False, wrong_ca=False):
|
|||||||
if foreign
|
if foreign
|
||||||
else (
|
else (
|
||||||
Path("/probe-fixtures") / role
|
Path("/probe-fixtures") / role
|
||||||
if role in {"revoked-lb", "retired-ca-lb"}
|
if role in {"revoked-lb", "retired-ca-lb", "operator"}
|
||||||
else Path("/identities") / role / "current"
|
else Path("/identities") / role / "current"
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -77,8 +77,10 @@ def values(role):
|
|||||||
|
|
||||||
def main():
|
def main():
|
||||||
report = {"complete": False, "tls": [], "bypass": [], "database": {}}
|
report = {"complete": False, "tls": [], "bypass": [], "database": {}}
|
||||||
|
try:
|
||||||
request = (
|
request = (
|
||||||
b"GET /health/live HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n"
|
b"GET /health/live HTTP/1.1\r\nHost: api\r\n"
|
||||||
|
b"Connection: close\r\n\r\n"
|
||||||
)
|
)
|
||||||
addresses = sorted(
|
addresses = sorted(
|
||||||
{
|
{
|
||||||
@@ -219,7 +221,9 @@ def main():
|
|||||||
headers["X-Vault-Token"] = token
|
headers["X-Vault-Token"] = token
|
||||||
request = urllib.request.Request(
|
request = urllib.request.Request(
|
||||||
"https://openbao:8200/v1/" + path,
|
"https://openbao:8200/v1/" + path,
|
||||||
data=json.dumps(payload).encode() if payload is not None else None,
|
data=json.dumps(payload).encode()
|
||||||
|
if payload is not None
|
||||||
|
else None,
|
||||||
method=method,
|
method=method,
|
||||||
headers=headers,
|
headers=headers,
|
||||||
)
|
)
|
||||||
@@ -308,7 +312,9 @@ def main():
|
|||||||
"api_staging_write": True,
|
"api_staging_write": True,
|
||||||
"worker_source_read": True,
|
"worker_source_read": True,
|
||||||
"worker_derived_write": True,
|
"worker_derived_write": True,
|
||||||
"api_derived_write_denied": s3_denied(lambda: put("api", derived)),
|
"api_derived_write_denied": s3_denied(
|
||||||
|
lambda: put("api", derived)
|
||||||
|
),
|
||||||
"worker_staging_write_denied": s3_denied(
|
"worker_staging_write_denied": s3_denied(
|
||||||
lambda: put("worker", staging)
|
lambda: put("worker", staging)
|
||||||
),
|
),
|
||||||
@@ -316,7 +322,9 @@ def main():
|
|||||||
lambda: clients["worker"].list_buckets()
|
lambda: clients["worker"].list_buckets()
|
||||||
),
|
),
|
||||||
"worker_delete_denied": s3_denied(
|
"worker_delete_denied": s3_denied(
|
||||||
lambda: clients["worker"].remove_object("messenger", derived)
|
lambda: clients["worker"].remove_object(
|
||||||
|
"messenger", derived
|
||||||
|
)
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
finally:
|
finally:
|
||||||
@@ -325,6 +333,7 @@ def main():
|
|||||||
for pool in pools:
|
for pool in pools:
|
||||||
pool.clear()
|
pool.clear()
|
||||||
report["complete"] = True
|
report["complete"] = True
|
||||||
|
finally:
|
||||||
print(json.dumps(report))
|
print(json.dumps(report))
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user