forked from mtusi2026/mtusi2026lab7
lab7: TLS ко всем зависимостям и телеметрии; раздельные роли PostgreSQL (GRANT по коду), ACL Valkey, AMQPS, HTTPS S3, mTLS Collector/Prometheus/Loki/Tempo/Grafana
This commit is contained in:
+12
-12
@@ -180,11 +180,11 @@ ts("DB pool wait p95 by service",
|
||||
"s", "db.client.connection.wait_time: time to get a connection from the pool.")
|
||||
ts("Container CPU (cores)",
|
||||
[("sum by (job, instance) (rate(container_cpu_time_seconds_total[$__rate_interval]))", "{{job}} {{instance}}"),
|
||||
("rate(otelcol_process_cpu_seconds[$__rate_interval])", "otel-collector")],
|
||||
("rate(otelcol_process_cpu_seconds_total[$__rate_interval])", "otel-collector")],
|
||||
"short", "cgroup cpu.stat of each application container (1 = one full core); Collector: its own counter.", w=12)
|
||||
ts("Container memory",
|
||||
[("sum by (job, instance) (container_memory_usage_bytes)", "{{job}} {{instance}}"),
|
||||
("otelcol_process_memory_rss", "otel-collector RSS")],
|
||||
("otelcol_process_memory_rss_bytes", "otel-collector RSS")],
|
||||
"bytes", "cgroup memory.current of each application container; Collector RSS (memory_limiter: 400 MiB).", w=12)
|
||||
grid.end()
|
||||
|
||||
@@ -216,16 +216,16 @@ grid.end()
|
||||
# =============================================================================== telemetry pipeline
|
||||
row("Telemetry pipeline (Collector, SDK)")
|
||||
ts("Collector: spans accepted / sent / failed per second",
|
||||
[("sum(rate(otelcol_receiver_accepted_spans[$__rate_interval]))", "accepted"),
|
||||
("sum(rate(otelcol_receiver_refused_spans[$__rate_interval]))", "refused (memory_limiter)"),
|
||||
("sum(rate(otelcol_exporter_sent_spans[$__rate_interval]))", "sent to Tempo"),
|
||||
("sum(rate(otelcol_exporter_send_failed_spans[$__rate_interval]))", "send failed (dropped)")],
|
||||
"ops", "otelcol_* self-metrics, scraped from :8888. sent < accepted with tail sampling (dropped by policy).")
|
||||
[("sum(rate(otelcol_receiver_accepted_spans_total[$__rate_interval]))", "accepted"),
|
||||
("sum(rate(otelcol_receiver_refused_spans_total[$__rate_interval]))", "refused (memory_limiter)"),
|
||||
("sum(rate(otelcol_exporter_sent_spans_total[$__rate_interval]))", "sent to Tempo"),
|
||||
("sum(rate(otelcol_exporter_send_failed_spans_total[$__rate_interval]))", "send failed (dropped)")],
|
||||
"ops", "otelcol_* self-metrics, pushed over OTLP/HTTPS (lab 7). sent < accepted with tail sampling (dropped by policy).")
|
||||
ts("Collector: logs and metric points per second",
|
||||
[("sum(rate(otelcol_receiver_accepted_log_records[$__rate_interval]))", "logs accepted"),
|
||||
("sum(rate(otelcol_exporter_send_failed_log_records[$__rate_interval]))", "logs failed"),
|
||||
("sum(rate(otelcol_receiver_accepted_metric_points[$__rate_interval]))", "metric points accepted"),
|
||||
("sum(rate(otelcol_exporter_send_failed_metric_points[$__rate_interval]))", "metric points failed")],
|
||||
[("sum(rate(otelcol_receiver_accepted_log_records_total[$__rate_interval]))", "logs accepted"),
|
||||
("sum(rate(otelcol_exporter_send_failed_log_records_total[$__rate_interval]))", "logs failed"),
|
||||
("sum(rate(otelcol_receiver_accepted_metric_points_total[$__rate_interval]))", "metric points accepted"),
|
||||
("sum(rate(otelcol_exporter_send_failed_metric_points_total[$__rate_interval]))", "metric points failed")],
|
||||
"ops", "Same for the logs and metrics pipelines.")
|
||||
ts("Collector: exporter queues",
|
||||
[("max by (exporter) (otelcol_exporter_queue_size)", "{{exporter}} size"),
|
||||
@@ -237,7 +237,7 @@ ts("SDK: spans recorded vs exported (all processes)",
|
||||
"ops", "Spans finished in the process (sampled) and handed to the OTLP exporter: success / failure (Collector down).",
|
||||
w=12)
|
||||
ts("Telemetry components up",
|
||||
[("up{job=~\"otel-collector|prometheus|loki|tempo|grafana\"}", "{{job}}")],
|
||||
[("up{job=~\"prometheus|loki|tempo\"}", "{{job}}")],
|
||||
"short", "1 = the scrape succeeded.", w=12, maximum=1)
|
||||
grid.end()
|
||||
|
||||
|
||||
+29
-10
@@ -1,11 +1,22 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Create local synthetic credentials for the stand in ./secrets (ignored by Git).
|
||||
"""Create local synthetic credentials and the PKI of the stand in ./secrets (ignored by Git).
|
||||
|
||||
python scripts/init_secrets.py
|
||||
.venv/Scripts/python scripts/init_secrets.py (Linux/macOS: .venv/bin/python)
|
||||
|
||||
Idempotent: existing files are kept, so re-running never changes passwords of a
|
||||
database that already has data. Prints only file names, never values.
|
||||
Delete ./secrets together with the volumes (`docker compose down -v`) to start over.
|
||||
|
||||
Lab 7: one credential per service and role (contracts/trust-matrix.md):
|
||||
PostgreSQL postgres (superuser: initdb + operator via `docker compose exec`, never over the
|
||||
network), messenger_migrate (owner of the schema), messenger_api / _relay / _worker
|
||||
(GRANT only what the service does, migrations/0007_least_privilege.sql),
|
||||
messenger_jobctl / _auditor (operator tools). Every URL has sslmode=verify-full.
|
||||
Valkey ACL user `api` (session:* and ratelimit:* keys, a few commands), `default` user off.
|
||||
S3 admin (s3-init only) / api / worker / auditor key pairs.
|
||||
RabbitMQ relay (publish only) / worker (consume only), amqps:// (TLS 5671).
|
||||
The application services do not mount these files from lab 7 step 5 on: they read their own
|
||||
values from OpenBao (scripts/bao_operator.py copies them there), see docs/OPERATOR.md.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -19,6 +30,8 @@ from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SECRETS = ROOT / "secrets"
|
||||
CA = "/run/secrets/internal-ca.crt" # path INSIDE the containers
|
||||
DB_ROLES = ("migrate", "api", "relay", "worker", "jobctl", "auditor")
|
||||
|
||||
|
||||
def write(name: str, value: str) -> None:
|
||||
@@ -28,7 +41,7 @@ def write(name: str, value: str) -> None:
|
||||
return
|
||||
path.write_text(value + "\n", encoding="utf-8", newline="\n")
|
||||
# Readable by the container users (postgres, valkey, seaweedfs, rabbitmq, app uid 10001)
|
||||
# through the compose bind mount. Local synthetic lab credentials only.
|
||||
# through the compose bind mount; the folder ./secrets itself is 0700 for the host user.
|
||||
os.chmod(path, 0o644)
|
||||
print(f"created secrets/{name}")
|
||||
|
||||
@@ -46,17 +59,23 @@ def rabbit_hash(password: str) -> str:
|
||||
|
||||
def main() -> int:
|
||||
SECRETS.mkdir(exist_ok=True)
|
||||
os.chmod(SECRETS, 0o700)
|
||||
# PostgreSQL: superuser (no network login, pg_hba) + one login role per service.
|
||||
write("postgres_password", secrets.token_urlsafe(24)) # [A-Za-z0-9_-]: safe inside URLs
|
||||
write("valkey_password", secrets.token_urlsafe(24))
|
||||
write("database_url", f"postgresql://messenger:{read('postgres_password')}@postgres:5432/messenger")
|
||||
write("cache_url", f"redis://:{read('valkey_password')}@valkey:6379/0")
|
||||
for role in DB_ROLES:
|
||||
write(f"pg_{role}_password", secrets.token_urlsafe(24))
|
||||
write(f"database_url_{role}", f"postgresql://messenger_{role}:{read(f'pg_{role}_password')}@postgres:5432/"
|
||||
f"messenger?sslmode=verify-full&sslrootcert={CA}")
|
||||
# Valkey: ACL user `api` (infra/valkey/start.sh); TLS only (rediss).
|
||||
write("valkey_api_password", secrets.token_urlsafe(24))
|
||||
write("cache_url", f"rediss://api:{read('valkey_api_password')}@valkey:6379/0")
|
||||
# S3 key pairs (SeaweedFS identities, infra/seaweedfs/start.sh): admin = bucket bootstrap only;
|
||||
# api = Write staging + Read final; worker = Read/Write both; auditor = Read + List (no Write).
|
||||
for who in ("admin", "api", "worker", "auditor"):
|
||||
write(f"s3_{who}_access_key_id", "AK" + secrets.token_hex(9).upper())
|
||||
write(f"s3_{who}_secret_access_key", secrets.token_hex(20))
|
||||
# Lab 5: RabbitMQ users. relay may only publish to the jobs exchange, worker may only consume
|
||||
# the jobs queue; neither may declare/delete anything (configure "^$").
|
||||
# RabbitMQ users. relay may only publish to the jobs exchange, worker may only consume the jobs
|
||||
# queue; neither may declare/delete anything (configure "^$").
|
||||
write("rabbitmq_relay_password", secrets.token_urlsafe(24))
|
||||
write("rabbitmq_worker_password", secrets.token_urlsafe(24))
|
||||
users = {
|
||||
@@ -71,8 +90,8 @@ def main() -> int:
|
||||
for who in ("relay", "worker"):
|
||||
# AMQP heartbeat 10 s: a frozen client loses its connection after ~2 missed heartbeats, and
|
||||
# the broker returns its unacked messages to the queue for the other consumers.
|
||||
write(f"broker_url_{who}", f"amqp://{who}:{read(f'rabbitmq_{who}_password')}@broker:5672/?heartbeat=10")
|
||||
# Lab 6: Grafana admin (UI on 127.0.0.1:3000 and the evidence scripts, via its datasource proxy).
|
||||
write(f"broker_url_{who}", f"amqps://{who}:{read(f'rabbitmq_{who}_password')}@broker:5671/?heartbeat=10")
|
||||
# Grafana admin (UI on https://localhost:3000 and the evidence scripts, via its datasource proxy).
|
||||
write("grafana_admin_password", secrets.token_urlsafe(18))
|
||||
# Lab 7: local PKI (two CAs + service certificates) in ./secrets/pki.
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
+5
-2
@@ -16,6 +16,7 @@ from __future__ import annotations
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
@@ -24,7 +25,9 @@ import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
GRAFANA = os.environ.get("GRAFANA_URL", "http://127.0.0.1:3000").rstrip("/")
|
||||
GRAFANA = os.environ.get("GRAFANA_URL", "https://localhost:3000").rstrip("/")
|
||||
# Lab 7: Grafana is HTTPS with a public-CA certificate (SAN localhost); verified, never skipped.
|
||||
TLS = ssl.create_default_context(cafile=os.environ.get("CA_FILE") or str(ROOT / "secrets" / "pki" / "public-ca.crt"))
|
||||
|
||||
|
||||
def _auth() -> str:
|
||||
@@ -38,7 +41,7 @@ def get(uid: str, path: str, params: dict | None = None, timeout: float = 30) ->
|
||||
if params:
|
||||
url += "?" + urllib.parse.urlencode(params)
|
||||
request = urllib.request.Request(url, headers={"Authorization": _auth(), "Accept": "application/json"})
|
||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||
with urllib.request.urlopen(request, timeout=timeout, context=TLS) as response:
|
||||
return json.loads(response.read())
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Controlled request -> its trace and logs (defense scenario, steps 2-3; evidence/trace-demo.txt).
|
||||
|
||||
python scripts/trace_demo.py [--base-url http://localhost:8080] [--output evidence/trace-demo.txt]
|
||||
python scripts/trace_demo.py [--base-url https://localhost:8443] [--output evidence/trace-demo.txt]
|
||||
|
||||
1. creates a synthetic user and chat, uploads tests/fixtures/sample.png with OUR OWN W3C
|
||||
`traceparent` header (trace id chosen here) and X-Request-Id;
|
||||
@@ -36,13 +36,13 @@ def call(base: str, method: str, path: str, body=None, headers=None, raw: bytes
|
||||
data = json.dumps(body).encode()
|
||||
h["Content-Type"] = "application/json"
|
||||
request = urllib.request.Request(base + path, data=data, method=method, headers=h)
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
with urllib.request.urlopen(request, timeout=30, context=obs.TLS) as response:
|
||||
return response.status, response.headers, json.loads(response.read() or b"null")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--base-url", default="https://localhost:8443")
|
||||
parser.add_argument("--output")
|
||||
args = parser.parse_args()
|
||||
base = args.base_url.rstrip("/") + "/api/v1"
|
||||
|
||||
Reference in New Issue
Block a user