lab 7 openbao

This commit is contained in:
2026-11-23 14:39:13 +03:00
parent 20afc2c790
commit 912a874f00
118 changed files with 12464 additions and 5108 deletions
+7 -7
View File
@@ -1,7 +1,7 @@
# Инфраструктура студента
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
# Инфраструктура студента
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
@@ -0,0 +1,670 @@
{
"uid": "messenger-observability",
"title": "Messenger: observability (lab 6)",
"tags": [
"messenger",
"lab6"
],
"timezone": "browser",
"schemaVersion": 39,
"version": 1,
"refresh": "10s",
"time": {
"from": "now-30m",
"to": "now"
},
"editable": false,
"panels": [
{
"id": 1,
"type": "stat",
"title": "API availability SLI (SLO 99 % / 30 d)",
"description": "SLI = 1 - 5xx / all business requests (health excluded; 4xx are client errors). Window = dashboard time range (set 30d to read the SLO). Query: 1 - sum(increase(http_server_request_duration_seconds_count{5xx}[$__range])) / sum(increase(..._count[$__range])).",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 0,
"w": 8,
"h": 4
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "1 - (sum(increase(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_response_status_class=\"5xx\"}[$__range])) / sum(increase(http_server_request_duration_seconds_count{service_name=\"messenger-api\"}[$__range])))",
"legendFormat": "availability"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit",
"min": 0.9,
"max": 1,
"decimals": 3,
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "red",
"value": null
},
{
"color": "green",
"value": 0.99
}
]
}
},
"overrides": []
},
"options": {
"colorMode": "background",
"reduceOptions": {
"calcs": [
"lastNotNull"
]
}
}
},
{
"id": 2,
"type": "timeseries",
"title": "Alert state (pending / firing)",
"description": "ALERTS{} series written by Prometheus rule evaluation: shows pending -> firing -> gone (resolved).",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 8,
"y": 0,
"w": 16,
"h": 4
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (alertname, alertstate) (ALERTS)",
"legendFormat": "{{alertname}} {{alertstate}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {}
},
{
"id": 3,
"type": "timeseries",
"title": "API RPS by route",
"description": "Query: sum by (http_route)(rate(http_server_request_duration_seconds_count[1m])). Unit: requests/s. Route is a TEMPLATE, never a real UUID.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 4,
"w": 8,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (http_route) (rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\"}[1m]))",
"legendFormat": "{{http_route}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "reqps"
},
"overrides": []
},
"options": {}
},
{
"id": 4,
"type": "timeseries",
"title": "API 5xx error ratio",
"description": "numerator = 5xx business requests, denominator = all business requests (health excluded). Unit: ratio 0..1.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 8,
"y": 4,
"w": 8,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_response_status_class=\"5xx\"}[2m])) / sum(rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\"}[2m]))",
"legendFormat": "5xx / all"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit",
"min": 0
},
"overrides": []
},
"options": {}
},
{
"id": 5,
"type": "timeseries",
"title": "API latency p50 / p95 / p99",
"description": "histogram_quantile(q, sum by (le)(rate(http_server_request_duration_seconds_bucket[2m]))): buckets of ALL replicas are summed first. Averages of per-replica percentiles are mathematically wrong. Unit: seconds.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 16,
"y": 4,
"w": 8,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.5, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\"}[2m])))",
"legendFormat": "p50"
},
{
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\"}[2m])))",
"legendFormat": "p95"
},
{
"refId": "C",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\"}[2m])))",
"legendFormat": "p99"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {}
},
{
"id": 6,
"type": "timeseries",
"title": "Jobs by outcome",
"description": "Counter of finished attempts: success | retry | failed | lost | noop | error. Unit: attempts/s.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 12,
"w": 8,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (outcome) (rate(messenger_jobs_processed_total[1m]))",
"legendFormat": "{{outcome}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "ops"
},
"overrides": []
},
"options": {}
},
{
"id": 7,
"type": "timeseries",
"title": "Worker job duration p50 / p95 / p99",
"description": "Processing time of one attempt (claim -> outcome). Does NOT include waiting in the queue (that is queue age). Unit: seconds.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 8,
"y": 12,
"w": 8,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_job_duration_seconds_bucket{}[2m])))",
"legendFormat": "p50"
},
{
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket{}[2m])))",
"legendFormat": "p95"
},
{
"refId": "C",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_duration_seconds_bucket{}[2m])))",
"legendFormat": "p99"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {}
},
{
"id": 8,
"type": "timeseries",
"title": "Time to ready p50 / p95 / p99",
"description": "End-to-end: durable acceptance (job row) -> ready commit, incl. backlog, retries and backoff. Unit: seconds.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 16,
"y": 12,
"w": 8,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket{}[5m])))",
"legendFormat": "p50"
},
{
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket{}[5m])))",
"legendFormat": "p95"
},
{
"refId": "C",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket{}[5m])))",
"legendFormat": "p99"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {}
},
{
"id": 9,
"type": "timeseries",
"title": "Queue depth",
"description": "Jobs with status=queued whose backoff has elapsed (waiting for a worker). Computed by the dispatcher from PostgreSQL. Unit: jobs.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 20,
"w": 6,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "max by (queue_name) (messenger_queue_depth)",
"legendFormat": "{{queue_name}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {}
},
{
"id": 10,
"type": "timeseries",
"title": "Oldest waiting job age",
"description": "now - min(next_attempt_at) over due queued jobs; 0 when empty. Alert QueueLagGrowing: > 30 s for 1 m. Unit: seconds.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 6,
"y": 20,
"w": 6,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "max by (queue_name) (messenger_queue_oldest_job_age_seconds)",
"legendFormat": "{{queue_name}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {}
},
{
"id": 11,
"type": "timeseries",
"title": "Worker busy vs capacity",
"description": "busy = jobs handled right now, capacity = WORKER_CONCURRENCY. Saturation = busy / capacity. Unit: jobs.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 20,
"w": 6,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(messenger_worker_busy)",
"legendFormat": "busy"
},
{
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(messenger_worker_capacity)",
"legendFormat": "capacity"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {}
},
{
"id": 12,
"type": "timeseries",
"title": "DB pool used / waiting (API)",
"description": "psycopg_pool stats: connections checked out, requests waiting for a connection. waiting > 0 = pool saturation. Unit: connections / requests.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 18,
"y": 20,
"w": 6,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (service_instance_id) (messenger_db_pool_used)",
"legendFormat": "used {{service_instance_id}}"
},
{
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(messenger_db_pool_waiting)",
"legendFormat": "waiting (all)"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {}
},
{
"id": 13,
"type": "timeseries",
"title": "CPU by service (cores)",
"description": "rate of process CPU seconds (user+system) of the main process. Unit: CPU cores.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 28,
"w": 8,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (service_name) (rate(process_cpu_time_seconds_total[1m]))",
"legendFormat": "{{service_name}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {}
},
{
"id": 14,
"type": "timeseries",
"title": "Memory (RSS) by service",
"description": "Resident set size of the main process. Unit: bytes.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 8,
"y": 28,
"w": 8,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (service_name, service_instance_id) (process_memory_usage_bytes)",
"legendFormat": "{{service_name}} {{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "bytes"
},
"overrides": []
},
"options": {}
},
{
"id": 15,
"type": "timeseries",
"title": "Telemetry loss in the Collector",
"description": "Failed exporter sends and memory_limiter refusals (spans / metric points / log records per second). Non-zero while a backend is down: telemetry is lost, the API is not affected.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 16,
"y": 28,
"w": 8,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (__name__) (rate({__name__=~\"otelcol_(exporter_send_failed|processor_refused)_.*_total\",job=\"otel-collector\"}[1m]))",
"legendFormat": "{{__name__}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {}
},
{
"id": 16,
"type": "logs",
"title": "Warnings and errors (all services)",
"description": "Loki (OTLP). Click trace_id to open the trace in Tempo. Filter one trace: {service_name=~\"messenger-.+\"} | trace_id=\"<id>\".",
"datasource": {
"type": "loki",
"uid": "loki"
},
"gridPos": {
"x": 0,
"y": 36,
"w": 24,
"h": 10
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "loki",
"uid": "loki"
},
"expr": "{service_name=~\"messenger-.+\"} | detected_level=~\"WARN|ERROR|CRITICAL\"",
"legendFormat": ""
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"showTime": true,
"wrapLogMessage": true,
"enableLogDetails": true,
"sortOrder": "Descending"
}
}
],
"templating": {
"list": []
},
"annotations": {
"list": []
}
}
@@ -0,0 +1,9 @@
apiVersion: 1
providers:
- name: messenger
type: file
disableDeletion: true
allowUiUpdates: false
updateIntervalSeconds: 30
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,25 @@
apiVersion: 1
# Grafana -> data sources: TLS with server verification (CA + serverName) and the grafana client identity (mTLS).
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: https://prometheus:9090
isDefault: true
jsonData: {timeInterval: 15s, tlsAuth: true, tlsAuthWithCACert: true, serverName: prometheus}
secureJsonData: {tlsCACert: "$__file{/pki/ca.crt}", tlsClientCert: "$__file{/pki/tls.crt}", tlsClientKey: "$__file{/pki/tls.key}"}
- name: Loki
uid: loki
type: loki
access: proxy
url: https://loki:3100
jsonData: {tlsAuth: true, tlsAuthWithCACert: true, serverName: loki}
secureJsonData: {tlsCACert: "$__file{/pki/ca.crt}", tlsClientCert: "$__file{/pki/tls.crt}", tlsClientKey: "$__file{/pki/tls.key}"}
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: https://tempo:3200
jsonData: {tlsAuth: true, tlsAuthWithCACert: true, serverName: tempo}
secureJsonData: {tlsCACert: "$__file{/pki/ca.crt}", tlsClientCert: "$__file{/pki/tls.crt}", tlsClientKey: "$__file{/pki/tls.key}"}
+40
View File
@@ -0,0 +1,40 @@
# Lab 7 ingress: TLS (public CA, hostname localhost) from clients, mTLS to every API replica.
global
log stdout format raw local0
maxconn 1024
ssl-default-bind-options ssl-min-ver TLSv1.2
ssl-default-server-options ssl-min-ver TLSv1.2
defaults
log global
mode http
option httplog
option http-keep-alive
timeout connect 2s
timeout client 30s
timeout server 30s
timeout check 2s
timeout http-request 10s # slow-header (Slowloris) protection
resolvers docker
nameserver docker-dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 2s
hold obsolete 2s
frontend public_https
bind :8443 ssl crt /pki/lb-public/keystore.pem
http-request set-header X-Real-IP %[src] # overwritten here: the API trusts it for rate limiting (only this LB may connect)
http-response set-header Strict-Transport-Security "max-age=31536000"
default_backend api_replicas
backend api_replicas
balance roundrobin
option httpchk
http-check send meth GET uri /health/ready
http-check expect status 200
# mTLS to the replica: verify the API certificate (CA + hostname "api"), present the LB identity (CN/SAN "lb").
default-server inter 1s fall 2 rise 1 ssl verify required ca-file /pki/lb/ca.crt verifyhost api sni str(api) crt /pki/lb/keystore.pem check
server-template api 10 api:8443 resolvers docker init-addr libc,none
+6
View File
@@ -0,0 +1,6 @@
# Admin/health client config used INSIDE the kafka and kafka_init containers (identity = the mounted /pki/keystore.pem).
security.protocol=SSL
ssl.keystore.type=PEM
ssl.keystore.location=/pki/keystore.pem
ssl.truststore.type=PEM
ssl.truststore.location=/pki/ca.crt
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
# Idempotent broker topology + ACLs. Principals are certificate CNs (ssl.principal.mapping.rules).
# dispatcher = producer only, worker = consumer of the jobs topic and of its own group only. Anybody else (even with a CA-signed cert) is denied.
set -eu
K=/opt/kafka/bin; B="--bootstrap-server kafka:9092 --command-config /client.properties"
$K/kafka-topics.sh $B --create --if-not-exists --topic "$JOBS_TOPIC" --partitions 3 --replication-factor 1 --config min.insync.replicas=1 --config retention.ms=604800000
$K/kafka-acls.sh $B --add --allow-principal User:dispatcher --producer --idempotent --topic "$JOBS_TOPIC"
$K/kafka-acls.sh $B --add --allow-principal User:worker --consumer --topic "$JOBS_TOPIC" --group attachment-workers
$K/kafka-acls.sh $B --list
+29
View File
@@ -0,0 +1,29 @@
auth_enabled: false
server:
http_listen_port: 3100
grpc_listen_port: 9096
grpc_listen_address: 127.0.0.1 # in-process traffic only (single binary); not reachable from the network
http_tls_config:
cert_file: /pki/tls.crt
key_file: /pki/tls.key
client_ca_file: /pki/ca.crt
client_auth_type: RequireAndVerifyClientCert
common:
instance_addr: 127.0.0.1
path_prefix: /loki
storage:
filesystem: {chunks_directory: /loki/chunks, rules_directory: /loki/rules}
replication_factor: 1
ring: {kvstore: {store: inmemory}}
schema_config:
configs:
- from: "2024-01-01"
store: tsdb
object_store: filesystem
schema: v13
index: {prefix: index_, period: 24h}
limits_config:
allow_structured_metadata: true
ingestion_rate_mb: 8
ingestion_burst_size_mb: 16
analytics: {reporting_enabled: false}
+7 -7
View File
@@ -1,7 +1,7 @@
# OpenBao — реализовать конфигурацию и политики
Добавьте non-dev конфигурацию listener/storage/TLS, API/worker policies, bootstrap и rotation scripts. Credentials и unseal material создаются локально; здесь нет готового root token или private key.
Решение должно показать реальную сервисную аутентификацию и получение нужного secret по ограниченной policy; просто работающий контейнер OpenBao не засчитывается. На 3 статический KV secret допустим. На 4 покажите expiry/renewal/rotation и allow/deny. Путь KV v2 data/metadata и ACL должен соответствовать фактическому mount; не копируйте широкое `path "*"` для приложения.
Документируйте шаги оператора init/unseal и восстановление после restart. Скрипт не должен печатать tokens/shares или хранить их в Git. См. contracts/trust-matrix.md и REPORT.md.
# OpenBao — реализовать конфигурацию и политики
Добавьте non-dev конфигурацию listener/storage/TLS, API/worker policies, bootstrap и rotation scripts. Credentials и unseal material создаются локально; здесь нет готового root token или private key.
Решение должно показать реальную сервисную аутентификацию и получение нужного secret по ограниченной policy; просто работающий контейнер OpenBao не засчитывается. На 3 статический KV secret допустим. На 4 покажите expiry/renewal/rotation и allow/deny. Путь KV v2 data/metadata и ACL должен соответствовать фактическому mount; не копируйте широкое `path "*"` для приложения.
Документируйте шаги оператора init/unseal и восстановление после restart. Скрипт не должен печатать tokens/shares или хранить их в Git. См. contracts/trust-matrix.md и REPORT.md.
+15
View File
@@ -0,0 +1,15 @@
# Non-dev OpenBao: TLS listener, persistent file storage on a named volume, sealed after every restart.
ui = false
disable_mlock = true # container without IPC_LOCK; swap is disabled on the lab host (see REPORT)
api_addr = "https://openbao:8200"
storage "file" {
path = "/openbao/data"
}
listener "tcp" {
address = "0.0.0.0:8200"
tls_cert_file = "/run/pki/tls.crt"
tls_key_file = "/run/pki/tls.key"
tls_min_version = "tls12"
}
+4
View File
@@ -0,0 +1,4 @@
# Policy "api": read exactly one KV v2 secret. No list, no metadata, no write, no sys/*, no other service paths.
path "kv/data/api" {
capabilities = ["read"]
}
+4
View File
@@ -0,0 +1,4 @@
# Policy "dispatcher": read exactly one KV v2 secret. No list, no metadata, no write, no sys/*, no other service paths.
path "kv/data/dispatcher" {
capabilities = ["read"]
}
+4
View File
@@ -0,0 +1,4 @@
# Policy "sweeper": read exactly one KV v2 secret. No list, no metadata, no write, no sys/*, no other service paths.
path "kv/data/sweeper" {
capabilities = ["read"]
}
+4
View File
@@ -0,0 +1,4 @@
# Policy "worker": read exactly one KV v2 secret. No list, no metadata, no write, no sys/*, no other service paths.
path "kv/data/worker" {
capabilities = ["read"]
}
+7 -7
View File
@@ -1,7 +1,7 @@
# Конфигурация наблюдаемости — реализовать
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
# Конфигурация наблюдаемости — реализовать
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
+62
View File
@@ -0,0 +1,62 @@
# OpenTelemetry Collector (contrib 0.131.0), lab 7: OTLP/HTTP is mTLS-only and accepts ONLY identities issued by the "workload CA"
# (api, worker, dispatcher). A certificate signed by the root CA with another identity (grafana, lb, outsider) has no chain to that
# trust anchor and is rejected in the handshake. Exporters to the backends use TLS with server verification + the collector client cert.
extensions:
health_check:
endpoint: 0.0.0.0:13133 # liveness only, no telemetry data; inside the internal backend network, never published
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
tls:
cert_file: /pki/tls.crt
key_file: /pki/tls.key
client_ca_file: /ca/workload-ca.crt # trust anchor = workload CA only (not the root CA)
min_version: "1.2"
processors:
memory_limiter: {check_interval: 1s, limit_mib: 192, spike_limit_mib: 48}
batch: {timeout: 2s, send_batch_size: 512, send_batch_max_size: 1024}
attributes/no_secrets: # defence in depth: never forward credentials even if an SDK attached them
actions:
- {key: http.request.header.authorization, action: delete}
- {key: http.request.header.cookie, action: delete}
- {key: password, action: delete}
exporters:
prometheusremotewrite:
endpoint: https://prometheus:9090/api/v1/write
timeout: 5s
tls: {ca_file: /pki/ca.crt, cert_file: /pki/tls.crt, key_file: /pki/tls.key}
resource_to_telemetry_conversion: {enabled: true}
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 10s, max_elapsed_time: 30s}
remote_write_queue: {enabled: true, queue_size: 200, num_consumers: 2}
otlphttp/loki:
endpoint: https://loki:3100/otlp
timeout: 5s
tls: {ca_file: /pki/ca.crt, cert_file: /pki/tls.crt, key_file: /pki/tls.key}
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 10s, max_elapsed_time: 30s}
sending_queue: {enabled: true, num_consumers: 2, queue_size: 200}
otlp/tempo:
endpoint: tempo:4317
timeout: 5s
tls: {ca_file: /pki/ca.crt, cert_file: /pki/tls.crt, key_file: /pki/tls.key}
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 10s, max_elapsed_time: 30s}
sending_queue: {enabled: true, num_consumers: 2, queue_size: 200}
service:
extensions: [health_check]
pipelines:
metrics: {receivers: [otlp], processors: [memory_limiter, attributes/no_secrets, batch], exporters: [prometheusremotewrite]}
logs: {receivers: [otlp], processors: [memory_limiter, attributes/no_secrets, batch], exporters: [otlphttp/loki]}
traces: {receivers: [otlp], processors: [memory_limiter, attributes/no_secrets, batch], exporters: [otlp/tempo]}
telemetry:
logs: {level: info}
metrics:
level: normal
readers:
- pull:
exporter:
prometheus: {host: 0.0.0.0, port: 8888} # Collector self-metrics only; plain HTTP, internal network, no credentials/data
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
# PostgreSQL refuses a key that is not owned by the server user with mode 0600: copy the mounted key into a private tmpfs first.
set -eu
install -d -m 700 -o postgres -g postgres /tls
install -m 644 -o postgres -g postgres /pki/tls.crt /tls/server.crt
install -m 600 -o postgres -g postgres /pki/tls.key /tls/server.key
install -m 644 -o postgres -g postgres /pki/ca.crt /tls/ca.crt
exec docker-entrypoint.sh postgres -c ssl=on -c ssl_cert_file=/tls/server.crt -c ssl_key_file=/tls/server.key \
-c ssl_ca_file=/tls/ca.crt -c ssl_min_protocol_version=TLSv1.2 -c hba_file=/etc/postgresql/pg_hba.conf -c password_encryption=scram-sha-256
+4
View File
@@ -0,0 +1,4 @@
# Lab 7: TLS + SCRAM only. Plain-text TCP connections are rejected. The unix socket exists only inside the container (operator docker exec).
local all all trust
hostssl all all 0.0.0.0/0 scram-sha-256
host all all 0.0.0.0/0 reject
+32
View File
@@ -0,0 +1,32 @@
groups:
- name: messenger-slo
rules:
# SLI (availability): 1 - 5xx / all BUSINESS requests (health excluded; 4xx such as a wrong password are NOT errors).
# SLO: 99 % over a rolling 30 days (error budget 1 %). Alert = fast symptom: >5 % 5xx for 1 m with real traffic.
- alert: HighApiErrorRate
expr: |
(
sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_class="5xx"}[2m]))
/
sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api"}[2m]))
) > 0.05
and
sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api"}[2m])) > 0.2
for: 1m
labels:
severity: page
annotations:
summary: "API 5xx ratio above 5 % (2m window)"
description: "More than 5 % of business requests end with 5xx for 1 minute. Runbook: runbooks/high-error-rate.md"
runbook: runbooks/high-error-rate.md
# Queue lag: the oldest due job waits for a worker longer than 30 s for 1 m (worker stopped / too slow / broker problem).
# Backlog (age of waiting jobs) is NOT processing latency: processing time is messenger_job_duration_seconds.
- alert: QueueLagGrowing
expr: max(messenger_queue_oldest_job_age_seconds{queue_name="attachment-jobs"}) > 30
for: 1m
labels:
severity: page
annotations:
summary: "Oldest waiting job is older than 30 s"
description: "Jobs wait for a worker. Check messenger_worker_busy/capacity, messenger_queue_depth and the worker logs. Runbook: runbooks/queue-lag.md"
runbook: runbooks/queue-lag.md
+15
View File
@@ -0,0 +1,15 @@
global:
scrape_interval: 15s
evaluation_interval: 15s
rule_files:
- /etc/prometheus/alerts.yml
scrape_configs:
# App metrics arrive by remote write (push, mTLS). Only the Collector self-metrics (plain, internal) and Prometheus itself (TLS) are scraped.
- job_name: otel-collector
static_configs:
- targets: ["otel-collector:8888"]
- job_name: prometheus
scheme: https
tls_config: {ca_file: /pki/ca.crt, cert_file: /pki/tls.crt, key_file: /pki/tls.key, server_name: prometheus}
static_configs:
- targets: ["prometheus:9090"]
+7
View File
@@ -0,0 +1,7 @@
# Prometheus web TLS: mTLS - only clients with a certificate from our CA (collector remote-write, grafana, self-scrape).
tls_server_config:
cert_file: /pki/tls.crt
key_file: /pki/tls.key
client_ca_file: /pki/ca.crt
client_auth_type: RequireAndVerifyClientCert
min_version: TLS12
+12
View File
@@ -0,0 +1,12 @@
# Lab 7: TLS only (plain port disabled); ACL users come from users.acl (hashed passwords, `default` user off).
port 0
tls-port 6379
tls-cert-file /pki/tls.crt
tls-key-file /pki/tls.key
tls-ca-cert-file /pki/ca.crt
tls-auth-clients no
tls-protocols "TLSv1.2 TLSv1.3"
aclfile /acl/users.acl
appendonly yes
appendfsync everysec
dir /data
+39
View File
@@ -0,0 +1,39 @@
#!/bin/sh
# Idempotent bootstrap: private bucket + THREE scoped S3 users (api, worker, sweeper). Runs with the S3 root credentials, then exits.
# api : write/delete staging/*, read attachments/* (accepts uploads, serves downloads)
# worker : read/delete staging/*, write attachments/* (cannot read finished attachments, cannot write staging, cannot list)
# sweeper: list bucket, read/delete staging/* and attachments/* (no PutObject)
set -eu
: "${S3_ENDPOINT:?}" "${S3_BUCKET:?}"
RU="$(cat /run/secrets/s3_root_user)"; RP="$(cat /run/secrets/s3_root_password)"
i=0
until mc alias set local "$S3_ENDPOINT" "$RU" "$RP" >/dev/null 2>&1; do
i=$((i+1)); [ "$i" -lt 60 ] || { echo "S3 not reachable over TLS" >&2; exit 1; }; sleep 1
done
mc mb --ignore-existing "local/$S3_BUCKET"
mc anonymous set none "local/$S3_BUCKET"
printf ok | mc pipe "local/$S3_BUCKET/attachments/.ready"
B="arn:aws:s3:::$S3_BUCKET"
cat > /tmp/p-api.json <<P
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["s3:PutObject","s3:DeleteObject","s3:AbortMultipartUpload","s3:ListMultipartUploadParts"],"Resource":["$B/staging/*"]},
{"Effect":"Allow","Action":["s3:GetObject"],"Resource":["$B/attachments/*"]}]}
P
cat > /tmp/p-worker.json <<P
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["s3:GetObject","s3:DeleteObject"],"Resource":["$B/staging/*"]},
{"Effect":"Allow","Action":["s3:PutObject","s3:AbortMultipartUpload","s3:ListMultipartUploadParts"],"Resource":["$B/attachments/*"]}]}
P
cat > /tmp/p-sweeper.json <<P
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":["s3:ListBucket","s3:GetBucketLocation"],"Resource":["$B"]},
{"Effect":"Allow","Action":["s3:GetObject","s3:DeleteObject"],"Resource":["$B/attachments/*","$B/staging/*"]}]}
P
for r in api worker sweeper; do
key="svc-$r"; [ "$key" != "$RU" ] || { echo "service key must differ from root" >&2; exit 1; }
mc admin policy remove local "messenger-$r" --force >/dev/null 2>&1 || true
mc admin policy create local "messenger-$r" "/tmp/p-$r.json"
mc admin user add local "$key" "$(cat /run/secrets/s3_${r}_secret)" # idempotent: re-running = secret rotation
out=$(mc admin policy attach local "messenger-$r" --user "$key" 2>&1) || { echo "$out" | grep -qi already || { echo "$out" >&2; exit 1; }; }
done
echo "PASS: bucket $S3_BUCKET private; users svc-api, svc-worker, svc-sweeper with separate policies"
+26
View File
@@ -0,0 +1,26 @@
stream_over_http_enabled: true
server:
http_listen_port: 3200
grpc_listen_address: 127.0.0.1 # internal gRPC (querier/ingester inside the single binary) is loopback only
http_tls_config:
cert_file: /pki/tls.crt
key_file: /pki/tls.key
client_ca_file: /pki/ca.crt
client_auth_type: RequireAndVerifyClientCert
distributor:
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
tls:
cert_file: /pki/tls.crt
key_file: /pki/tls.key
client_ca_file: /pki/ca.crt # collector -> tempo is mTLS
ingester: {max_block_duration: 5m}
storage:
trace:
backend: local
wal: {path: /var/tempo/wal}
local: {path: /var/tempo/blocks}
usage_report: {reporting_enabled: false}