Implement Lab 7 service security
This commit is contained in:
@@ -0,0 +1,186 @@
|
||||
"""Verify the provisioned Grafana data sources on the dedicated local Lab 7 stack."""
|
||||
|
||||
import argparse
|
||||
from base64 import b64encode
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import time
|
||||
from urllib.error import HTTPError
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import HTTPSHandler, ProxyHandler, Request, build_opener
|
||||
from uuid import uuid4
|
||||
|
||||
from queue_recovery import ROOT, Client, check, check_retry_limit, compose, wait_for
|
||||
|
||||
|
||||
class Grafana:
|
||||
def __init__(self, base, ca_file, password):
|
||||
self.base = base.rstrip("/")
|
||||
self.authorization = "Basic " + b64encode(("admin:" + password).encode()).decode("ascii")
|
||||
context = ssl.create_default_context(cafile=ca_file)
|
||||
self.http = build_opener(ProxyHandler({}), HTTPSHandler(context=context))
|
||||
|
||||
def get(self, path, **params):
|
||||
query = "?" + urlencode(params) if params else ""
|
||||
try:
|
||||
request = Request(self.base + path + query, headers={"Authorization": self.authorization})
|
||||
with self.http.open(request, timeout=5) as response:
|
||||
return json.load(response)
|
||||
except HTTPError as error:
|
||||
if error.code == 401:
|
||||
raise RuntimeError("Grafana rejected the configured admin credentials") from None
|
||||
return None
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
|
||||
def source(self, name, path, **params):
|
||||
return self.get(f"/api/datasources/proxy/uid/lab-{name}{path}", **params)
|
||||
|
||||
def logs(self, service, **fields):
|
||||
query = f'{{service_name="{service}"}} | json'
|
||||
for key, value in fields.items():
|
||||
query += f" | {key} = {json.dumps(value)}"
|
||||
result = self.source("loki", "/loki/api/v1/query_range", query=query,
|
||||
start=str(time.time_ns() - 15 * 60 * 10**9), limit=50)
|
||||
entries = []
|
||||
for stream in (result or {}).get("data", {}).get("result", []):
|
||||
for record in stream["values"]:
|
||||
entries.append(json.loads(record[1]))
|
||||
return entries
|
||||
|
||||
def metric(self, expression):
|
||||
result = self.source("prometheus", "/api/v1/query", query=expression)
|
||||
samples = (result or {}).get("data", {}).get("result", [])
|
||||
return float(samples[0]["value"][1]) if samples else None
|
||||
|
||||
|
||||
def spans(value):
|
||||
if isinstance(value, dict):
|
||||
if "spanId" in value and "name" in value:
|
||||
yield value
|
||||
else:
|
||||
for child in value.values():
|
||||
yield from spans(child)
|
||||
if isinstance(value, list):
|
||||
for child in value:
|
||||
yield from spans(child)
|
||||
|
||||
|
||||
def correlated(grafana, service, span_name, **fields):
|
||||
entries = wait_for(lambda: grafana.logs(service, **fields), f"Missing log for {service}: {fields}")
|
||||
entry = entries[0]
|
||||
trace_id, span_id = entry["trace_id"], entry["span_id"]
|
||||
check(len(trace_id) == 32 and len(span_id) == 16, "Malformed trace identifiers")
|
||||
trace = wait_for(lambda: grafana.source("tempo", "/api/traces/" + trace_id),
|
||||
f"Trace missing in Tempo: {trace_id}")
|
||||
span = next((span for span in spans(trace) if span["name"] == span_name), None)
|
||||
check(span is not None, f"Span missing in Tempo: {span_name}")
|
||||
for field, identifier in (("spanId", span_id), ("traceId", trace_id)):
|
||||
encoded = b64encode(bytes.fromhex(identifier)).decode("ascii")
|
||||
check(span[field] in (identifier, encoded), f"Log and trace {field} differ")
|
||||
expected_kind = 2 if service == "messenger-api" else 5
|
||||
expected_name = "SPAN_KIND_SERVER" if expected_kind == 2 else "SPAN_KIND_CONSUMER"
|
||||
check(span["kind"] in (expected_kind, expected_name), "Unexpected span kind")
|
||||
attributes = {item["key"]: next(iter(item["value"].values())) for item in span.get("attributes", [])}
|
||||
return {"log": entry, "trace": {"name": span_name, "kind": span["kind"], "attributes": attributes,
|
||||
"events": [event["name"] for event in span.get("events", [])]}}
|
||||
|
||||
|
||||
def postgres_incident():
|
||||
code = """
|
||||
import json
|
||||
import ssl
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import urlopen
|
||||
context = ssl.create_default_context(cafile='/run/tls/ca.crt')
|
||||
context.load_cert_chain('/run/tls/lb-ingress.pem')
|
||||
try:
|
||||
urlopen('https://api1:8080/health/ready', timeout=12, context=context)
|
||||
except HTTPError as error:
|
||||
print(json.dumps({'status': error.code, 'request_id': error.headers.get('X-Request-Id')}))
|
||||
"""
|
||||
try:
|
||||
compose("stop", "db")
|
||||
observed = json.loads(compose("run", "--rm", "--no-deps", "-T", "probe", "python", "-c", code))
|
||||
check(observed["status"] == 503 and observed["request_id"], "Database outage did not yield API 503")
|
||||
return observed
|
||||
finally:
|
||||
compose("start", "db")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="https://localhost:8443")
|
||||
parser.add_argument("--grafana-url", default="https://localhost:13407")
|
||||
parser.add_argument("--ca-file", default=str(ROOT / "secrets/pki/ca.crt"))
|
||||
parser.add_argument("--output", type=Path)
|
||||
args = parser.parse_args()
|
||||
password = (ROOT / "secrets/grafana_password").read_text(encoding="ascii").strip()
|
||||
grafana = Grafana(args.grafana_url, args.ca_file, password)
|
||||
dashboard = wait_for(lambda: grafana.get("/api/dashboards/uid/lab-messenger"),
|
||||
"Grafana dashboard was not provisioned")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
marker = "lab7_content_" + uuid4().hex
|
||||
message = client.message(alice, chat, marker)
|
||||
request_id = message["headers"]["X-Request-Id"]
|
||||
request = correlated(grafana, "messenger-api", "POST /api/v1/chats/{chat_id}/messages",
|
||||
request_id=request_id)
|
||||
attachment, _ = client.attachment(alice, chat)
|
||||
client.wait_ready(bob, attachment)
|
||||
delivery = correlated(grafana, "messenger-worker", "attachment.process.v1 process",
|
||||
attachment_id=attachment["id"], outcome="ready")
|
||||
|
||||
database = postgres_incident()
|
||||
wait_for(lambda: client.call("GET", "/health/ready", schema="Health"), "API did not recover")
|
||||
outage = correlated(grafana, "messenger-api", "GET /health/ready", request_id=database["request_id"])
|
||||
check("postgresql.unavailable" in outage["trace"]["events"], "Trace does not diagnose the PostgreSQL outage")
|
||||
|
||||
try:
|
||||
staging = check_retry_limit(client, alice, bob, chat)
|
||||
failed = correlated(grafana, "messenger-worker", "attachment.process.v1 process",
|
||||
attachment_id=staging["attachment_id"], outcome="failed")
|
||||
check(failed["trace"]["attributes"]["job.reason"] == "staging_unavailable",
|
||||
"Worker trace does not diagnose the staging failure")
|
||||
finally:
|
||||
compose("start", "worker")
|
||||
|
||||
try:
|
||||
compose("stop", "tempo")
|
||||
during_tempo_stop = client.message(alice, chat, "Проверка работы при остановленном Tempo")
|
||||
check(during_tempo_stop["status"] == 201, "Tempo outage stopped business requests")
|
||||
finally:
|
||||
compose("start", "tempo")
|
||||
|
||||
metrics = {}
|
||||
expressions = (
|
||||
"sum(messenger_http_requests_total)",
|
||||
'sum(messenger_http_requests_total{http_status_class="5xx"})',
|
||||
"sum(messenger_http_duration_seconds_count)",
|
||||
'sum(messenger_job_deliveries_total{job_outcome="ready"})',
|
||||
'sum(messenger_job_deliveries_total{job_outcome="failed"})',
|
||||
"sum(messenger_job_duration_seconds_count)",
|
||||
)
|
||||
for expression in expressions:
|
||||
metrics[expression] = wait_for(lambda: grafana.metric(expression), f"Missing metric: {expression}")
|
||||
check(marker not in json.dumps(grafana.logs("messenger-api", request_id=request_id)),
|
||||
"Message content leaked into the API log")
|
||||
check(marker not in json.dumps(request["trace"]), "Message content leaked into the API trace")
|
||||
report = {
|
||||
"dashboard": dashboard["dashboard"]["uid"], "metrics": metrics,
|
||||
"api_correlation": request, "worker_correlation": delivery,
|
||||
"postgresql_incident": outage, "staging_incident": failed, "staging_attempts": staging["attempts"],
|
||||
"message_status_with_tempo_stopped": during_tempo_stop["status"], "message_marker_absent": True,
|
||||
}
|
||||
rendered = json.dumps(report, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
args.output.write_text(rendered + "\n", encoding="utf-8")
|
||||
print("PASS: metrics, structured logs and correlated traces for API and worker, plus two incidents.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
for variable in ("NO_PROXY", "no_proxy"):
|
||||
os.environ[variable] = ",".join(filter(None, (os.environ.get(variable), "127.0.0.1", "localhost")))
|
||||
main()
|
||||
@@ -0,0 +1,172 @@
|
||||
"""Exercise the dedicated local Compose project using synthetic attachments."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, check
|
||||
from image_probe import jpeg_size
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, text=True, encoding="utf-8")
|
||||
|
||||
|
||||
def wait_for(action, description):
|
||||
deadline = time.monotonic() + 70
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
result = action()
|
||||
if result:
|
||||
return result
|
||||
except (Failure, subprocess.CalledProcessError):
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
raise Failure(description)
|
||||
|
||||
|
||||
def queue_depth():
|
||||
output = subprocess.check_output(
|
||||
["docker", "compose", "exec", "-T", "broker", "rabbitmqctl", "-q", "list_queues",
|
||||
"name", "messages_ready", "messages_unacknowledged"],
|
||||
cwd=ROOT, text=True, encoding="utf-8", stderr=subprocess.PIPE,
|
||||
)
|
||||
for line in output.splitlines():
|
||||
fields = line.split()
|
||||
if fields and fields[0] == "attachment.process.v1":
|
||||
return tuple(map(int, fields[1:]))
|
||||
return None
|
||||
|
||||
|
||||
def api_instances(client):
|
||||
instances = {client.call("GET", "/health/ready", schema="Health")["headers"]["X-Instance-Id"]
|
||||
for _ in range(4)}
|
||||
return instances if len(instances) == 2 else None
|
||||
|
||||
|
||||
def duplicate(attachment_id):
|
||||
code = """
|
||||
import sys
|
||||
from src.jobs import broker, database, publish
|
||||
with database() as db, broker() as connection:
|
||||
job = db.execute('SELECT * FROM attachment_jobs WHERE attachment_id=%s', (sys.argv[1],)).fetchone()
|
||||
channel = connection.channel()
|
||||
channel.confirm_delivery()
|
||||
publish(channel, job, job['attempts'])
|
||||
"""
|
||||
compose("exec", "-T", "dispatcher", "python", "-c", code, attachment_id)
|
||||
|
||||
|
||||
def check_retry_limit(client, alice, bob, chat):
|
||||
compose("stop", "worker")
|
||||
attachment, _ = client.attachment(alice, chat)
|
||||
path = "/api/v1/attachments/" + attachment["id"]
|
||||
# Remove only the staging object created for this synthetic case.
|
||||
code = """
|
||||
import sys
|
||||
from uuid import UUID
|
||||
from src.objects import Objects
|
||||
objects = Objects()
|
||||
try:
|
||||
objects.delete('staging/' + UUID(sys.argv[1]).hex)
|
||||
finally:
|
||||
objects.close()
|
||||
"""
|
||||
compose("run", "--rm", "--no-deps", "-T", "worker", "python", "-c", code, attachment["id"])
|
||||
compose("start", "worker")
|
||||
|
||||
def failed():
|
||||
result = client.call("GET", path, actor=bob, schema="Attachment")["json"]
|
||||
return result if result["status"] == "failed" else None
|
||||
|
||||
terminal = wait_for(failed, "Missing staging object did not reach failed")
|
||||
check(terminal["error_code"] == "retry_exhausted", "Unexpected final error")
|
||||
client.call("GET", path + "/content", 409, actor=bob)
|
||||
code = """
|
||||
import sys
|
||||
from src.jobs import MAX_ATTEMPTS, database
|
||||
with database() as db:
|
||||
job = db.execute('SELECT attempts,publish_at FROM attachment_jobs WHERE attachment_id=%s',
|
||||
(sys.argv[1],)).fetchone()
|
||||
assert job['attempts'] == MAX_ATTEMPTS and job['publish_at'] is None
|
||||
print(job['attempts'])
|
||||
"""
|
||||
attempts = int(compose("exec", "-T", "worker", "python", "-c", code, attachment["id"]).strip())
|
||||
return {"attachment_id": attachment["id"], "attempts": attempts,
|
||||
"status": terminal["status"], "error_code": terminal["error_code"]}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="https://localhost:8443")
|
||||
parser.add_argument("--ca-file", default=str(ROOT / "secrets/pki/ca.crt"))
|
||||
parser.add_argument("--output", type=Path)
|
||||
args = parser.parse_args()
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
compose("stop", "worker")
|
||||
try:
|
||||
check(queue_depth() == (0, 0), "Expected an idle lab queue before the test")
|
||||
attachment, original = client.attachment(alice, chat)
|
||||
path = "/api/v1/attachments/" + attachment["id"]
|
||||
message = client.message(alice, chat, "", attachments=[attachment["id"]])["json"]
|
||||
client.call("GET", path + "/content", 409, actor=bob)
|
||||
wait_for(lambda: queue_depth() == (1, 0), "RabbitMQ did not receive the job")
|
||||
compose("stop", "dispatcher")
|
||||
old_instances = wait_for(lambda: api_instances(client), "Expected two ready API replicas")
|
||||
compose("restart", "api1", "api2", "broker")
|
||||
new_instances = wait_for(lambda: api_instances(client), "Both API replicas did not come back")
|
||||
check(old_instances.isdisjoint(new_instances), "An API process did not restart")
|
||||
wait_for(lambda: queue_depth() == (1, 0), "Job did not survive RabbitMQ restart")
|
||||
client.call("GET", path + "/content", 409, actor=bob)
|
||||
history = client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages", actor=bob,
|
||||
schema="MessagePage")["json"]
|
||||
check(message in history["items"], "Message missing after API restart")
|
||||
compose("start", "worker")
|
||||
ready = client.wait_ready(bob, attachment)
|
||||
downloaded = client.call("GET", path + "/content", actor=bob)["bytes"]
|
||||
check(downloaded == original, "Original bytes changed")
|
||||
thumbnail_path = path + "/content?variant=thumbnail"
|
||||
image = client.call("GET", thumbnail_path, actor=bob)["bytes"]
|
||||
check(jpeg_size(image) == (256, 160), "Unexpected thumbnail dimensions")
|
||||
check(len(ready["variants"]) == 1, "Expected exactly one variant")
|
||||
check(ready["variants"][0]["sha256"] == hashlib.sha256(image).hexdigest(), "Thumbnail checksum mismatch")
|
||||
wait_for(lambda: queue_depth() == (0, 0), "Worker did not acknowledge the job")
|
||||
compose("stop", "worker")
|
||||
compose("start", "dispatcher")
|
||||
duplicate(attachment["id"])
|
||||
wait_for(lambda: queue_depth() == (1, 0), "Duplicate was not published")
|
||||
compose("start", "worker")
|
||||
wait_for(lambda: queue_depth() == (0, 0), "Duplicate was not acknowledged")
|
||||
check(client.call("GET", path, actor=bob, schema="Attachment")["json"] == ready,
|
||||
"Duplicate changed ready metadata")
|
||||
check(client.call("GET", thumbnail_path, actor=bob)["bytes"] == image, "Duplicate changed JPEG")
|
||||
result = {
|
||||
"attachment_id": attachment["id"], "message_id": message["id"], "upload_status": 202,
|
||||
"content_while_queued": 409, "queued_jobs_after_broker_restart_with_dispatcher_stopped": 1,
|
||||
"api_instance_ids_before": sorted(old_instances), "api_instance_ids_after": sorted(new_instances),
|
||||
"message_preserved_after_restart": True, "final_status": ready["status"],
|
||||
"original_bytes_match": True, "thumbnail": ready["variants"][0], "duplicate_acknowledged": True,
|
||||
"duplicate_preserved_metadata_and_bytes": True,
|
||||
"retry_limit": check_retry_limit(client, alice, bob, chat),
|
||||
}
|
||||
rendered = json.dumps(result, indent=2)
|
||||
if args.output:
|
||||
args.output.write_text(rendered + "\n", encoding="utf-8")
|
||||
print(rendered)
|
||||
finally:
|
||||
compose("start", "dispatcher", "worker")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
for variable in ("NO_PROXY", "no_proxy"):
|
||||
os.environ[variable] = ",".join(filter(None, (os.environ.get(variable), "127.0.0.1", "localhost")))
|
||||
main()
|
||||
@@ -0,0 +1,344 @@
|
||||
"""Verify the dedicated local Lab 7 deployment with synthetic users and data."""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
from http.client import HTTPSConnection
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from urllib.parse import urlsplit
|
||||
from urllib.request import HTTPSHandler, ProxyHandler, build_opener
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, check
|
||||
|
||||
|
||||
def compose(*args, source=None, env=None):
|
||||
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, input=source, env=env,
|
||||
text=True, encoding="utf-8").strip()
|
||||
|
||||
|
||||
def wait_ready(client):
|
||||
deadline = time.monotonic() + 70
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
return client.call("GET", "/health/ready", schema="Health")
|
||||
except Failure:
|
||||
time.sleep(0.5)
|
||||
raise Failure("HTTPS readiness did not recover")
|
||||
|
||||
|
||||
def verify_hostname(url, ca):
|
||||
endpoint = urlsplit(url)
|
||||
context = ssl.create_default_context(cafile=str(ca))
|
||||
with socket.create_connection((endpoint.hostname, endpoint.port or 443), timeout=5) as conn:
|
||||
try:
|
||||
with context.wrap_socket(conn, server_hostname="wrong-name.invalid"):
|
||||
raise Failure("Unexpected success with wrong hostname")
|
||||
except ssl.SSLCertVerificationError as error:
|
||||
check(error.verify_code == 62, "The negative test did not fail on hostname verification")
|
||||
return "hostname mismatch rejected"
|
||||
|
||||
|
||||
def verify_mtls():
|
||||
code = """
|
||||
import http.client
|
||||
import json
|
||||
import ssl
|
||||
|
||||
def attempt(host, mode):
|
||||
context = ssl.create_default_context(cafile='/run/tls/ca.crt')
|
||||
if mode == 'allowed':
|
||||
context.load_cert_chain('/run/tls/lb-ingress.pem')
|
||||
elif mode != 'absent':
|
||||
context.load_cert_chain(f'/run/tls/{mode}.crt', f'/run/tls/{mode}.key')
|
||||
connection = http.client.HTTPSConnection(host, 8080, context=context, timeout=5)
|
||||
try:
|
||||
connection.request('GET', '/health/live')
|
||||
response = connection.getresponse()
|
||||
return {'status': response.status, 'instance': response.getheader('X-Instance-Id')}
|
||||
except (ssl.SSLError, http.client.RemoteDisconnected, ConnectionResetError) as error:
|
||||
return {'rejected': type(error).__name__}
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
results = {}
|
||||
for host in ('api1', 'api2'):
|
||||
results[host] = dict((mode, attempt(host, mode))
|
||||
for mode in ('allowed', 'absent', 'foreign-role', 'other-role'))
|
||||
print(json.dumps(results))
|
||||
"""
|
||||
results = json.loads(compose("run", "--rm", "--no-deps", "-T", "probe", "python", "-", source=code))
|
||||
for replica in results.values():
|
||||
check(replica["allowed"]["status"] == 200 and replica["allowed"]["instance"], "LB cert rejected")
|
||||
check(all("rejected" in replica[case] for case in ("absent", "foreign-role", "other-role")),
|
||||
"API accepted a prohibited client certificate")
|
||||
return results
|
||||
|
||||
|
||||
def verify_scoped_access():
|
||||
code = """
|
||||
import json
|
||||
import os
|
||||
from urllib.error import HTTPError
|
||||
from src.bao import client
|
||||
|
||||
role = os.environ['BAO_ROLE']
|
||||
other = 'api' if role == 'worker' else 'worker'
|
||||
request = client(role)
|
||||
auth = request('auth/cert/login', {'name': role})['auth']
|
||||
token = auth['client_token']
|
||||
|
||||
def forbidden(path, payload=None):
|
||||
try:
|
||||
request(path, payload, token)
|
||||
except HTTPError as error:
|
||||
assert error.code == 403
|
||||
return error.code
|
||||
raise AssertionError('OpenBao allowed an out-of-scope operation')
|
||||
|
||||
own = request('messenger/data/' + role, token=token)['data']['data']
|
||||
out = {'allowed_keys': sorted(own), 'ttl_seconds': auth['lease_duration'],
|
||||
'other_role': forbidden('messenger/data/' + other),
|
||||
'policy_write': forbidden('sys/policies/acl/lab7-test', {'policy': ''})}
|
||||
request('auth/token/revoke-self', {}, token)
|
||||
out['after_revocation'] = forbidden('messenger/data/' + role)
|
||||
assert 0 < out['ttl_seconds'] <= 300
|
||||
|
||||
if role == 'worker':
|
||||
import psycopg
|
||||
from src.jobs import database
|
||||
with database() as db:
|
||||
out['postgres_tls'] = db.execute('SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()').fetchone()['ssl']
|
||||
try:
|
||||
db.execute('SELECT count(*) FROM users')
|
||||
except psycopg.errors.InsufficientPrivilege:
|
||||
out['users_table'] = 'denied'
|
||||
else:
|
||||
raise AssertionError('Worker can read the users table')
|
||||
from pika.exceptions import ChannelClosedByBroker
|
||||
from src.jobs import QUEUE, broker
|
||||
with broker() as connection:
|
||||
channel = connection.channel()
|
||||
channel.confirm_delivery()
|
||||
try:
|
||||
channel.basic_publish('', QUEUE, b'{}', mandatory=True)
|
||||
except ChannelClosedByBroker as error:
|
||||
assert error.reply_code == 403
|
||||
out['broker_publish'] = error.reply_code
|
||||
else:
|
||||
raise AssertionError('Worker can publish to its queue')
|
||||
|
||||
from uuid import uuid4
|
||||
from botocore.exceptions import ClientError
|
||||
from src.objects import Objects
|
||||
objects = Objects()
|
||||
prefix = 'originals/' if role == 'api' else 'system/'
|
||||
try:
|
||||
objects.client.put_object(Bucket=objects.bucket, Key=prefix + str(uuid4()), Body=b'probe')
|
||||
except ClientError as error:
|
||||
assert error.response['ResponseMetadata']['HTTPStatusCode'] == 403
|
||||
out['s3_write_other_prefix'] = 403
|
||||
else:
|
||||
raise AssertionError('S3 allowed a write outside the service prefix')
|
||||
finally:
|
||||
objects.close()
|
||||
print(json.dumps(out))
|
||||
"""
|
||||
roles = {role: json.loads(compose("exec", "-T", service, "python", "-", source=code))
|
||||
for role, service in (("api", "api1"), ("worker", "worker"))}
|
||||
check(roles["worker"]["postgres_tls"], "Worker DB connection is plaintext")
|
||||
check("CURSOR_SECRET_FILE" not in roles["worker"]["allowed_keys"], "Worker got the API cursor secret")
|
||||
return roles
|
||||
|
||||
|
||||
def verify_telemetry_restrictions():
|
||||
code = """
|
||||
import http.client
|
||||
import json
|
||||
import ssl
|
||||
context = ssl.create_default_context(cafile='/run/tls/ca.crt')
|
||||
results = {}
|
||||
for name, host, port, path, method in (
|
||||
('collector_ingest', 'otel-collector', 4318, '/v1/traces', 'POST'),
|
||||
('prometheus_query', 'telemetry-edge', 9440, '/api/v1/query', 'GET'),
|
||||
('loki_query', 'telemetry-edge', 9441, '/loki/api/v1/labels', 'GET'),
|
||||
('tempo_query', 'telemetry-edge', 9442, '/api/search', 'GET'),
|
||||
('loki_ingest', 'telemetry-edge', 9443, '/otlp/v1/logs', 'POST'),
|
||||
('tempo_ingest', 'telemetry-edge', 9444, '/v1/traces', 'POST'),
|
||||
):
|
||||
with_context = http.client.HTTPSConnection(host, port, context=context, timeout=5)
|
||||
try:
|
||||
with_context.request(method, path, headers={'Content-Type':'application/x-protobuf'})
|
||||
response = with_context.getresponse()
|
||||
assert response.status in (401, 403), (name, response.status)
|
||||
results[name] = response.status
|
||||
finally:
|
||||
with_context.close()
|
||||
print(json.dumps(results))
|
||||
"""
|
||||
return json.loads(compose("run", "--rm", "--no-deps", "-T", "probe", "python", "-", source=code))
|
||||
|
||||
|
||||
def argon_sample():
|
||||
code = """
|
||||
import json
|
||||
import statistics
|
||||
import time
|
||||
from src.security import HASHER
|
||||
samples=[]
|
||||
for _ in range(10):
|
||||
started=time.perf_counter()
|
||||
value=HASHER.hash('synthetic-password-for-benchmark')
|
||||
samples.append((time.perf_counter()-started)*1000)
|
||||
assert value.startswith('$argon2id$') and HASHER.verify(value,'synthetic-password-for-benchmark')
|
||||
print(json.dumps({'memory_kib':HASHER.memory_cost,'time_cost':HASHER.time_cost,
|
||||
'parallelism':HASHER.parallelism,'hash_p50_ms':round(statistics.median(samples),2),
|
||||
'hash_max_ms':round(max(samples),2),'samples':len(samples)}))
|
||||
"""
|
||||
return json.loads(compose("exec", "-T", "api1", "python", "-", source=code))
|
||||
|
||||
|
||||
def verify_openbao_restart(bao_url, ca_file, operator_file):
|
||||
context = ssl.create_default_context(cafile=str(ca_file))
|
||||
opener = build_opener(ProxyHandler({}), HTTPSHandler(context=context))
|
||||
|
||||
def seal_status():
|
||||
with opener.open(bao_url + "/v1/sys/seal-status", timeout=5) as response:
|
||||
data = json.load(response)
|
||||
return {"initialized": data["initialized"], "sealed": data["sealed"]}
|
||||
|
||||
compose("restart", "openbao")
|
||||
try:
|
||||
deadline = time.monotonic() + 30
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
before = seal_status()
|
||||
break
|
||||
except OSError:
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
raise Failure("OpenBao did not return after restart")
|
||||
check(before == {"initialized": True, "sealed": True}, "Unexpected state after OpenBao restart")
|
||||
finally:
|
||||
subprocess.check_call([sys.executable, "-X", "utf8", str(ROOT / "scripts/bao.py"), "unseal",
|
||||
"--url", bao_url, "--operator-file", str(operator_file)], cwd=ROOT)
|
||||
after = seal_status()
|
||||
check(after == {"initialized": True, "sealed": False}, "Unexpected state after OpenBao unseal")
|
||||
return {"after_restart": before, "after_operator_unseal": after}
|
||||
|
||||
|
||||
def verify_api(client, mtls):
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
attachment, uploaded = client.attachment(alice, chat)
|
||||
client.wait_ready(bob, attachment)
|
||||
path = "/api/v1/attachments/" + attachment["id"]
|
||||
impersonation = {"X-User-Id": alice["id"]}
|
||||
client.call("GET", path, 404, actor=eve, headers=impersonation)
|
||||
client.call("GET", path + "/content", 404, actor=eve, headers=impersonation)
|
||||
other_chat = client.call("POST", "/api/v1/chats", 201, actor=eve,
|
||||
body={"title": "Проверка ACL", "member_ids": [eve["id"]]}, schema="Chat")["json"]
|
||||
client.call("POST", "/api/v1/chats/" + other_chat["id"] + "/messages", 404, actor=eve,
|
||||
body={"text": "", "attachment_ids": [attachment["id"]]},
|
||||
headers={"Idempotency-Key": "acl-" + attachment["id"], **impersonation})
|
||||
client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=eve)
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=eve)
|
||||
client.call("POST", "/api/v1/users", 413, raw=b" " * 66000, headers={"Content-Type": "application/json"})
|
||||
|
||||
before = client.message(alice, chat, "Проверка сохранности")["json"]
|
||||
failover = {}
|
||||
for replica in ("api1", "api2"):
|
||||
try:
|
||||
compose("stop", replica)
|
||||
instance = wait_ready(client)["headers"]["X-Instance-Id"]
|
||||
deadline = time.monotonic() + 20
|
||||
while instance == mtls[replica]["allowed"]["instance"] and time.monotonic() < deadline:
|
||||
time.sleep(0.4)
|
||||
instance = wait_ready(client)["headers"]["X-Instance-Id"]
|
||||
check(instance != mtls[replica]["allowed"]["instance"], "Stopped replica still received requests")
|
||||
client.message(alice, chat, f"Доступ при остановке {replica}")
|
||||
failover[replica] = instance
|
||||
finally:
|
||||
compose("start", replica)
|
||||
wait_ready(client)
|
||||
compose("restart", "db", "s3", "broker")
|
||||
compose("restart", "api1", "api2")
|
||||
wait_ready(client)
|
||||
after = client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages", actor=bob,
|
||||
schema="MessagePage")["json"]
|
||||
check(before in after["items"], "Message missing after restart")
|
||||
check(client.call("GET", path + "/content", actor=bob)["bytes"] == uploaded, "Original changed after restart")
|
||||
return {"outsider_meta_content_attach": 404, "revoked_session": 401, "oversize_json": 413,
|
||||
"surviving_instances": failover, "message_and_original_after_restart": True}
|
||||
|
||||
|
||||
def verify_expiry(client):
|
||||
short_ttl = dict(os.environ, SESSION_TTL_SECONDS="2")
|
||||
try:
|
||||
compose("up", "-d", "--no-deps", "--force-recreate", "api1", "api2", env=short_ttl)
|
||||
wait_ready(client)
|
||||
actor = client.user("expiry")
|
||||
time.sleep(2.5)
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||
finally:
|
||||
compose("up", "-d", "--no-deps", "--force-recreate", "api1", "api2")
|
||||
wait_ready(client)
|
||||
return 401
|
||||
|
||||
|
||||
def verify_rate_limit(client, ca_file):
|
||||
time.sleep(10)
|
||||
invalid = base64.b64encode(b"nonexistent:synthetic-wrong-password").decode()
|
||||
endpoint = urlsplit(client.base)
|
||||
context = ssl.create_default_context(cafile=str(ca_file))
|
||||
connection = HTTPSConnection(endpoint.hostname, endpoint.port or 443, context=context, timeout=5)
|
||||
try:
|
||||
for attempt in range(1, 16):
|
||||
connection.request("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + invalid})
|
||||
response = connection.getresponse()
|
||||
payload = json.loads(response.read())
|
||||
check(response.status in (401, 429), "Unexpected login response")
|
||||
if response.status == 429:
|
||||
delay = int(response.headers["Retry-After"])
|
||||
request_id = response.headers["X-Request-Id"]
|
||||
check(delay > 0 and payload["error"]["request_id"] == request_id, "Invalid 429 response")
|
||||
check(payload["error"]["code"] == "rate_limited", "Unexpected rate-limit error code")
|
||||
return {"status": 429, "request_number": attempt, "retry_after_seconds": delay}
|
||||
finally:
|
||||
connection.close()
|
||||
raise Failure("Login never reached its rate limit")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="https://localhost:8443")
|
||||
parser.add_argument("--ca-file", type=Path, default=ROOT / "secrets/pki/ca.crt")
|
||||
parser.add_argument("--bao-url", default="https://localhost:18207")
|
||||
parser.add_argument("--operator-file", type=Path, default=ROOT / "secrets/operator/openbao.json")
|
||||
parser.add_argument("--output", type=Path)
|
||||
args = parser.parse_args()
|
||||
client = Client(args.base_url, str(args.ca_file))
|
||||
hostname = verify_hostname(args.base_url, args.ca_file)
|
||||
mtls = verify_mtls()
|
||||
result = {"hostname": hostname, "replica_mtls": mtls,
|
||||
"openbao_restart": verify_openbao_restart(args.bao_url, args.ca_file, args.operator_file),
|
||||
"scoped_access": verify_scoped_access(),
|
||||
"telemetry_without_credentials": verify_telemetry_restrictions(),
|
||||
"argon2id": argon_sample(), "https_api": verify_api(client, mtls),
|
||||
"expired_session": verify_expiry(client), "rate_limit": verify_rate_limit(client, args.ca_file)}
|
||||
if args.output:
|
||||
args.output.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
|
||||
print("PASS: verified TLS, mTLS identity, least privilege, sessions, rate limit and restart/failover.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
for name in ("NO_PROXY", "no_proxy"):
|
||||
os.environ[name] = ",".join(filter(None, (os.environ.get(name), "127.0.0.1", "localhost")))
|
||||
main()
|
||||
Reference in New Issue
Block a user