Реализовать лабораторную 7
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
import json
|
||||
import resource
|
||||
import statistics
|
||||
import time
|
||||
|
||||
from argon2 import PasswordHasher, Type
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
hasher = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1, type=Type.ID)
|
||||
samples = []
|
||||
for _ in range(20):
|
||||
started = time.perf_counter()
|
||||
value = hasher.hash("Synthetic benchmark password")
|
||||
hasher.verify(value, "Synthetic benchmark password")
|
||||
samples.append(time.perf_counter() - started)
|
||||
ordered = sorted(samples)
|
||||
print(json.dumps({
|
||||
"samples": len(samples), "operation": "hash_plus_verify", "memory_kib": 19456,
|
||||
"time_cost": 2, "parallelism": 1,
|
||||
"p50_seconds": round(statistics.median(samples), 4),
|
||||
"p95_seconds": round(ordered[18], 4),
|
||||
"peak_rss_bytes": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * 1024,
|
||||
"server_max_parallel_hashes": 2,
|
||||
}))
|
||||
@@ -0,0 +1,42 @@
|
||||
import base64
|
||||
import json
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import time
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
context = ssl.create_default_context(cafile=str(ROOT / "secrets/operator/ca.pem"))
|
||||
password = (ROOT / "secrets/grafana_password").read_text().strip()
|
||||
auth = base64.b64encode(("admin:" + password).encode()).decode()
|
||||
paths = {
|
||||
"Prometheus": "/api/datasources/uid/prometheus/health",
|
||||
"Loki": "/api/datasources/uid/loki/health",
|
||||
"Tempo": "/api/datasources/proxy/uid/tempo/api/search",
|
||||
}
|
||||
for name, path in paths.items():
|
||||
deadline = time.monotonic() + 90
|
||||
while True:
|
||||
request = Request("https://localhost:13007" + path,
|
||||
headers={"Authorization": "Basic " + auth})
|
||||
try:
|
||||
with urlopen(request, context=context, timeout=15) as response:
|
||||
result = json.load(response)
|
||||
if name == "Tempo":
|
||||
assert isinstance(result.get("traces"), list)
|
||||
else:
|
||||
assert result.get("status") == "OK"
|
||||
print("PASS: Grafana queries " + name + " through verified mTLS", flush=True)
|
||||
break
|
||||
except (HTTPError, URLError, TimeoutError, AssertionError):
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,39 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, check
|
||||
|
||||
|
||||
def compose(*args):
|
||||
subprocess.run(["docker", "compose", *args], check=True, timeout=90,
|
||||
stdout=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def main():
|
||||
client = Client()
|
||||
owner, member, _, chat = client.bootstrap()
|
||||
compose("stop", "worker", "dispatcher")
|
||||
attachment, original = client.attachment(owner, chat)
|
||||
client.message(owner, chat, "", attachments=[attachment["id"]])
|
||||
path = "/api/v1/attachments/" + attachment["id"]
|
||||
client.call("GET", path + "/content", 409, actor=owner)
|
||||
compose("restart", "api-a", "api-b", "broker")
|
||||
compose("start", "dispatcher", "worker")
|
||||
ready = client.wait_ready(member, attachment)
|
||||
check(client.call("GET", path + "/content", actor=member)["bytes"] == original,
|
||||
"original changed")
|
||||
check({v["name"] for v in ready["variants"]} == {"thumbnail", "crop", "optimized"},
|
||||
"missing variants")
|
||||
for variant in ready["variants"]:
|
||||
downloaded = client.call("GET", path + "/content?variant=" + variant["name"], actor=member)
|
||||
import hashlib
|
||||
check(hashlib.sha256(downloaded["bytes"]).hexdigest() == variant["sha256"], "variant checksum")
|
||||
print("PASS: queued attachment survives API/broker restart, 3 variants ready")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,73 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, check
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.check_output(["docker", "compose", *args], text=True, timeout=90).strip()
|
||||
|
||||
|
||||
def recreate(service, setting):
|
||||
env = dict(os.environ)
|
||||
env.update(setting)
|
||||
subprocess.run(["docker", "compose", "up", "-d", "--no-deps", "--force-recreate", service],
|
||||
env=env, check=True, timeout=90, stdout=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def job_for(attachment):
|
||||
code = f"""
|
||||
from storage import Store
|
||||
s = Store()
|
||||
try:
|
||||
with s.pool.connection() as db:
|
||||
print(db.execute('SELECT id FROM jobs WHERE attachment_id=%s',
|
||||
('{attachment["id"]}',)).fetchone()['id'])
|
||||
finally:
|
||||
s.close()
|
||||
"""
|
||||
return compose("exec", "-T", "-w", "/app/src", "api-a", "python", "-c", code)
|
||||
|
||||
|
||||
def main():
|
||||
c = Client()
|
||||
actor, _, _, chat = c.bootstrap()
|
||||
recreate("dispatcher", {"CRASH_BEFORE_PUBLISH": "1"})
|
||||
attachment, _ = c.attachment(actor, chat)
|
||||
try:
|
||||
time.sleep(1)
|
||||
check(compose("ps", "-q", "--status", "running", "dispatcher") == "", "dispatcher did not crash")
|
||||
finally:
|
||||
recreate("dispatcher", {})
|
||||
c.wait_ready(actor, attachment)
|
||||
print("PASS: COMMIT/publish crash recovered from outbox", flush=True)
|
||||
|
||||
recreate("worker", {"CRASH_AFTER_OBJECTS": "1"})
|
||||
attachment, _ = c.attachment(actor, chat)
|
||||
try:
|
||||
deadline = time.monotonic() + 30
|
||||
while compose("ps", "-q", "--status", "running", "worker"):
|
||||
check(time.monotonic() < deadline, "worker did not crash")
|
||||
time.sleep(0.5)
|
||||
finally:
|
||||
recreate("worker", {})
|
||||
time.sleep(72)
|
||||
c.wait_ready(actor, attachment)
|
||||
job_id = job_for(attachment)
|
||||
payload = {"schema_version": 1, "job_id": job_id, "attachment_id": attachment["id"],
|
||||
"pipeline_version": 1, "attempt": 1, "type": "attachment.process.v1",
|
||||
"created_at": "2026-11-30T00:00:00Z"}
|
||||
compose("exec", "-T", "broker", "redis-cli", "XADD", "images", "*", "payload", json.dumps(payload))
|
||||
time.sleep(1)
|
||||
ready = c.wait_ready(actor, attachment)
|
||||
check(len(ready["variants"]) == 3, "duplicate variants")
|
||||
print("PASS: crash after S3 effect, lease recovery and duplicate delivery", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,38 @@
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, check
|
||||
from check_recovery import compose, job_for
|
||||
|
||||
|
||||
def main():
|
||||
c = Client()
|
||||
actor, _, _, chat = c.bootstrap()
|
||||
compose("stop", "worker")
|
||||
attachment, _ = c.attachment(actor, chat)
|
||||
job_id = job_for(attachment)
|
||||
code = f"""
|
||||
from storage import Store
|
||||
s = Store()
|
||||
try:
|
||||
with s.pool.connection() as db:
|
||||
db.execute('UPDATE attachments SET status=%s,error_code=%s WHERE id=%s',
|
||||
('failed','processing_failed','{attachment["id"]}'))
|
||||
db.execute('UPDATE jobs SET finished=true WHERE id=%s', ('{job_id}',))
|
||||
finally:
|
||||
s.close()
|
||||
"""
|
||||
try:
|
||||
compose("exec", "-T", "-w", "/app/src", "api-a", "python", "-c", code)
|
||||
compose("exec", "-T", "api-a", "python", "src/replay_job.py", job_id)
|
||||
finally:
|
||||
compose("start", "worker")
|
||||
ready = c.wait_ready(actor, attachment)
|
||||
check(ready["status"] == "ready", "replay failed")
|
||||
print("PASS: explicit failed-job replay completes original attachment")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,124 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from urllib.error import HTTPError, URLError
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
from client import Client, Failure, check
|
||||
import bao_operator
|
||||
|
||||
|
||||
def compose(*args, input=None):
|
||||
result = subprocess.run(["docker", "compose", *args], cwd=ROOT, input=input,
|
||||
text=True, check=True, timeout=90,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def ready(client):
|
||||
deadline = time.monotonic() + 45
|
||||
while True:
|
||||
try:
|
||||
client.call("GET", "/health/ready", schema="Health")
|
||||
return
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, "stack did not recover")
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def main():
|
||||
client = Client("https://localhost:18443", str(ROOT / "secrets/operator/ca.pem"))
|
||||
actor = client.user("rotation")
|
||||
old_url = json.loads((ROOT / "secrets/operator/kv-bootstrap.json").read_text())["api-a"]["DATABASE_URL"]
|
||||
image = compose("images", "-q", "api-a")
|
||||
subprocess.run([sys.executable, "scripts/rotate.py", "secret"], cwd=ROOT, check=True, timeout=90)
|
||||
ready(client)
|
||||
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
code = f"""
|
||||
import psycopg
|
||||
try:
|
||||
connection=psycopg.connect({old_url!r},connect_timeout=3)
|
||||
except psycopg.OperationalError as error:
|
||||
assert "password authentication failed" in str(error)
|
||||
print("PASS: old DB credential rejected on new connection")
|
||||
else:
|
||||
connection.close()
|
||||
raise AssertionError("old DB credential accepted")
|
||||
"""
|
||||
print(compose("exec", "-T", "api-a", "python", "-", input=code), flush=True)
|
||||
check(compose("images", "-q", "api-a") == image, "image changed during secret rotation")
|
||||
|
||||
subprocess.run([sys.executable, "scripts/rotate.py", "certificate"], cwd=ROOT, check=True, timeout=90)
|
||||
ready(client)
|
||||
code = """
|
||||
import sys
|
||||
sys.path.insert(0,"/checks")
|
||||
from check_security import exchange,denied,request
|
||||
payload=b"POST /v1/traces HTTP/1.0\\r\\nHost: otel-collector\\r\\nContent-Length: 0\\r\\n\\r\\n"
|
||||
denied(lambda: exchange("otel-collector",4319,"revoked-api-a",payload))
|
||||
try:
|
||||
request("https://openbao:8200/v1/auth/cert/login","revoked-api-a",{"name":"api-a"})
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("revoked certificate authenticated to OpenBao")
|
||||
print("PASS: revoked leaf rejected by Collector and OpenBao")
|
||||
"""
|
||||
print(compose("run", "--rm", "--no-deps", "-T", "security-check", "-", input=code), flush=True)
|
||||
check(compose("images", "-q", "api-a") == image, "image changed during certificate rotation")
|
||||
|
||||
state = json.loads((ROOT / "secrets/operator/bao-init.json").read_text())
|
||||
bao_operator.request("auth/cert/certs/api-a", {
|
||||
"certificate": (ROOT / "secrets/operator/ca.pem").read_text(),
|
||||
"allowed_dns_sans": ["api-a"], "token_policies": ["api-a"],
|
||||
"token_ttl": 2, "token_max_ttl": 2,
|
||||
}, state["root_token"])
|
||||
try:
|
||||
code = """
|
||||
import sys,time
|
||||
sys.path.insert(0,"/checks")
|
||||
from check_security import credentials,request
|
||||
from urllib.error import HTTPError
|
||||
values,auth=credentials("api-a")
|
||||
assert auth["lease_duration"]<=2
|
||||
time.sleep(3)
|
||||
try:
|
||||
request("https://openbao:8200/v1/secret/data/api-a","api-a",token=auth["client_token"])
|
||||
except HTTPError as error:
|
||||
assert error.code==403
|
||||
else:
|
||||
raise AssertionError("expired service token accepted")
|
||||
print("PASS: expired OpenBao service token rejected")
|
||||
"""
|
||||
print(compose("run", "--rm", "--no-deps", "-T", "security-check", "-", input=code), flush=True)
|
||||
finally:
|
||||
bao_operator.main()
|
||||
bao_operator.request("sys/seal", {}, state["root_token"], "PUT")
|
||||
try:
|
||||
code = """
|
||||
import sys
|
||||
sys.path.insert(0,"/checks")
|
||||
from check_security import request
|
||||
from urllib.error import HTTPError
|
||||
try:
|
||||
request("https://openbao:8200/v1/auth/cert/login","api-a",{"name":"api-a"})
|
||||
except HTTPError as error:
|
||||
assert error.code==503
|
||||
else:
|
||||
raise AssertionError("sealed OpenBao issued credentials")
|
||||
print("PASS: sealed OpenBao refuses service authentication")
|
||||
"""
|
||||
print(compose("run", "--rm", "--no-deps", "-T", "security-check", "-", input=code), flush=True)
|
||||
finally:
|
||||
bao_operator.main()
|
||||
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
print("PASS: original session valid after credential/certificate rotation and unseal")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,202 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import ssl
|
||||
import sys
|
||||
import time
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import Request, urlopen
|
||||
from urllib.parse import urlencode
|
||||
from uuid import uuid4
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
import psycopg
|
||||
import redis
|
||||
|
||||
sys.path.insert(0, "/tests")
|
||||
from client import Client, check
|
||||
|
||||
CA = "/tls/ca.pem"
|
||||
|
||||
|
||||
def tls_context(role=None):
|
||||
context = ssl.create_default_context(cafile=CA)
|
||||
if role:
|
||||
context.load_cert_chain(f"/identities/{role}/cert.pem", f"/identities/{role}/key.pem")
|
||||
return context
|
||||
|
||||
|
||||
def request(url, role, data=None, token=None, method=None):
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Vault-Token"] = token
|
||||
req = Request(url, data=json.dumps(data).encode() if data is not None else None,
|
||||
headers=headers, method=method)
|
||||
with urlopen(req, context=tls_context(role), timeout=5) as response:
|
||||
return json.load(response) if response.status != 204 else {}
|
||||
|
||||
|
||||
def credentials(role):
|
||||
auth = request("https://openbao:8200/v1/auth/cert/login", role, {"name": role})["auth"]
|
||||
values = request(f"https://openbao:8200/v1/secret/data/{role}", role,
|
||||
token=auth["client_token"])["data"]["data"]
|
||||
return values, auth
|
||||
|
||||
|
||||
def exchange(host, port, role, data):
|
||||
with socket.create_connection((host, port), timeout=4) as sock:
|
||||
with tls_context(role).wrap_socket(sock, server_hostname=host) as secured:
|
||||
secured.sendall(data)
|
||||
return secured.recv(1024)
|
||||
|
||||
|
||||
def denied(call):
|
||||
try:
|
||||
result = call()
|
||||
except (OSError, URLError, BotoCoreError, ClientError, psycopg.Error, redis.RedisError):
|
||||
return
|
||||
check(not result, "unauthorized connection succeeded")
|
||||
|
||||
|
||||
def main():
|
||||
client = Client("https://lb:8443", CA)
|
||||
actor, _, outsider, chat = client.bootstrap()
|
||||
attachment, _ = client.attachment(actor, chat)
|
||||
client.wait_ready(actor, attachment)
|
||||
client.call("GET", "/api/v1/attachments/" + attachment["id"], 404, actor=outsider)
|
||||
client.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": actor["id"]})
|
||||
print("PASS: HTTPS API, asynchronous images and cross-user ACL", flush=True)
|
||||
|
||||
try:
|
||||
urlopen("https://lb:8443/health/live", context=ssl.create_default_context(), timeout=5)
|
||||
except URLError as error:
|
||||
check(isinstance(error.reason, ssl.SSLCertVerificationError), "wrong CA test was not a trust failure")
|
||||
else:
|
||||
raise AssertionError("untrusted CA accepted")
|
||||
try:
|
||||
with socket.create_connection(("lb", 8443), timeout=5) as sock:
|
||||
tls_context().wrap_socket(sock, server_hostname="wrong.invalid")
|
||||
except ssl.SSLCertVerificationError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("wrong hostname accepted")
|
||||
print("PASS: server CA and hostname verification", flush=True)
|
||||
|
||||
get = b"GET /health/ready HTTP/1.0\r\nHost: api-a\r\n\r\n"
|
||||
for target in ("api-a", "api-b"):
|
||||
check(b"200" in exchange(target, 8443, "lb", get), "valid LB identity failed")
|
||||
for role in (None, "foreign", "untrusted", "expired"):
|
||||
denied(lambda: exchange(target, 8443, role, get))
|
||||
denied(lambda: socket.create_connection((target, 8080), timeout=2))
|
||||
print("PASS: both API replicas require allowed LB certificate; plaintext bypass closed", flush=True)
|
||||
|
||||
worker, _ = credentials("worker")
|
||||
dispatcher, _ = credentials("dispatcher")
|
||||
for role, values in (("worker", worker), ("dispatcher", dispatcher)):
|
||||
broker = redis.Redis.from_url(values["BROKER_URL"], ssl_ca_certs=CA,
|
||||
ssl_certfile=f"/identities/{role}/cert.pem", ssl_keyfile=f"/identities/{role}/key.pem",
|
||||
socket_timeout=3)
|
||||
check(broker.ping(), "authorized broker identity failed")
|
||||
if role == "worker":
|
||||
denied(lambda: broker.xadd("images", {"payload": "forbidden"}))
|
||||
else:
|
||||
denied(lambda: broker.xread({"images": "0"}))
|
||||
broker.close()
|
||||
for role in (None, "foreign", "untrusted"):
|
||||
denied(lambda: exchange("broker", 6380, role, b"*1\r\n$4\r\nPING\r\n"))
|
||||
print("PASS: broker mTLS identity and separate producer/consumer ACL", flush=True)
|
||||
|
||||
payload = b"POST /v1/traces HTTP/1.0\r\nHost: otel-collector\r\nContent-Type: application/x-protobuf\r\nContent-Length: 0\r\n\r\n"
|
||||
for role in ("api-a", "worker"):
|
||||
check(b"200" in exchange("otel-collector", 4319, role, payload),
|
||||
"authorized Collector ingest failed")
|
||||
for role in (None, "foreign", "untrusted"):
|
||||
denied(lambda: exchange("otel-collector", 4319, role, payload))
|
||||
print("PASS: Collector requires allowed service identities", flush=True)
|
||||
|
||||
api, auth = credentials("api-a")
|
||||
check(auth["lease_duration"] <= 120, "OpenBao token TTL too long")
|
||||
for path in ("secret/data/worker", "sys/policies/acl"):
|
||||
try:
|
||||
request("https://openbao:8200/v1/" + path, "api-a", token=auth["client_token"])
|
||||
except HTTPError as error:
|
||||
check(error.code == 403, "expected policy denial")
|
||||
else:
|
||||
raise AssertionError("OpenBao policy leaked another service secret")
|
||||
print("PASS: OpenBao scoped read, cross-service and policy access denied, token TTL bounded", flush=True)
|
||||
|
||||
with psycopg.connect(api["DATABASE_URL"], connect_timeout=3) as connection:
|
||||
check(connection.execute("SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()").fetchone()[0],
|
||||
"PostgreSQL connection is plaintext")
|
||||
user = connection.execute("SELECT password_hash FROM users WHERE id=%s", (actor["id"],)).fetchone()[0]
|
||||
check(user.startswith(b"$argon2id$"), "registration did not use Argon2id")
|
||||
denied(lambda: psycopg.connect(api["DATABASE_URL"], sslmode="disable", connect_timeout=3))
|
||||
with psycopg.connect(worker["DATABASE_URL"], connect_timeout=3) as connection:
|
||||
try:
|
||||
connection.execute("DELETE FROM users")
|
||||
except psycopg.errors.InsufficientPrivilege:
|
||||
connection.rollback()
|
||||
else:
|
||||
raise AssertionError("worker modified users")
|
||||
print("PASS: PostgreSQL TLS, Argon2id and least-privilege worker role", flush=True)
|
||||
password = actor["registration"]["password"]
|
||||
salt = bytes(range(16))
|
||||
legacy = salt + hashlib.scrypt(password.encode(),salt=salt,n=2**15,r=8,p=1,
|
||||
maxmem=64*1024**2,dklen=32)
|
||||
with psycopg.connect(api["DATABASE_URL"],connect_timeout=3) as connection:
|
||||
connection.execute("UPDATE users SET password_hash=%s WHERE id=%s",(legacy,actor["id"]))
|
||||
valid = base64.b64encode((actor["user"]["username"]+":"+password).encode()).decode()
|
||||
client.call("POST","/api/v1/auth/sessions",201,headers={"Authorization":"Basic "+valid},schema="Session")
|
||||
with psycopg.connect(api["DATABASE_URL"],connect_timeout=3) as connection:
|
||||
stored = connection.execute("SELECT password_hash FROM users WHERE id=%s",(actor["id"],)).fetchone()[0]
|
||||
check(stored.startswith(b"$argon2id$"),"legacy hash was not rehashed")
|
||||
print("PASS: successful login upgrades legacy scrypt hash to Argon2id",flush=True)
|
||||
|
||||
s3 = boto3.client("s3", endpoint_url="https://s3:9002", region_name="us-east-1",
|
||||
verify=CA, aws_access_key_id=api["S3_ACCESS_KEY_ID"],
|
||||
aws_secret_access_key=api["S3_SECRET_ACCESS_KEY"],
|
||||
config=Config(client_cert=("/identities/api-a/cert.pem","/identities/api-a/key.pem"),
|
||||
retries={"total_max_attempts": 1}, connect_timeout=2,read_timeout=3,
|
||||
request_checksum_calculation="when_required", s3={"addressing_style":"path"}))
|
||||
denied(lambda: s3.put_object(Bucket="messenger-attachments", Key="attachments/forbidden-"+uuid4().hex, Body=b"x"))
|
||||
print("PASS: API S3 identity cannot write final-object prefix", flush=True)
|
||||
|
||||
basic = base64.b64encode((actor["user"]["username"] + ":wrong-password").encode()).decode()
|
||||
observed = set()
|
||||
rate_limited = False
|
||||
for _ in range(12):
|
||||
result = client.call("POST", "/api/v1/auth/sessions", [401,429],
|
||||
headers={"Authorization":"Basic " + basic})
|
||||
observed.add(result["headers"]["X-Instance-Id"])
|
||||
if result["status"] == 429:
|
||||
rate_limited = True
|
||||
check(result["headers"].get("Retry-After"), "missing Retry-After")
|
||||
break
|
||||
check(rate_limited and len(observed) >= 2, "shared login rate limit did not cover both replicas")
|
||||
print("PASS: shared login limit across both replicas with 429/Retry-After", flush=True)
|
||||
deadline = time.monotonic()+60
|
||||
while True:
|
||||
try:
|
||||
with urlopen("https://loki:3101/ready",context=tls_context("operator"),timeout=5) as response:
|
||||
if response.status==200:
|
||||
break
|
||||
except (OSError,URLError):
|
||||
pass
|
||||
check(time.monotonic()<deadline,"Loki did not become ready")
|
||||
time.sleep(1)
|
||||
query = urlencode({"query":'{service_name=~"messenger-api|messenger-worker"}',"limit":1000})
|
||||
logs = request("https://loki:3101/loki/api/v1/query_range?"+query,"operator")
|
||||
check(logs["data"]["result"],"no application logs through TLS path")
|
||||
serialized = json.dumps(logs)
|
||||
check(actor["token"] not in serialized and password not in serialized,"secret found in telemetry")
|
||||
metrics = request("https://prometheus:9091/api/v1/query?"+urlencode({"query":"http_requests_total"}),"operator")
|
||||
check(metrics["data"]["result"],"no application metrics through TLS path")
|
||||
print("PASS: TLS telemetry query succeeds and logs exclude test password/session token",flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user