feat(security): add scoped identities, TLS boundaries and OpenBao bootstrap

This commit is contained in:
2026-11-20 18:08:59 +03:00
parent 20afc2c790
commit 1dd020d060
149 changed files with 16519 additions and 68 deletions
+107
View File
@@ -0,0 +1,107 @@
// Fetch the immutable module ZIP in bounded HTTP ranges. The subsequent
// go mod download validates its h1 checksum through the Go checksum database.
package main
import (
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"sync"
"time"
)
func main() {
const version = "v0.0.0-20251015172955-9e49d5e7a648"
const total int64 = 25342606
const chunk int64 = 512 * 1024
const source = "https://proxy.golang.org/github.com/minio/minio/@v/" + version + ".zip"
directory := "/go/pkg/mod/cache/download/github.com/minio/minio/@v"
if err := os.MkdirAll(directory, 0755); err != nil {
panic(err)
}
target := filepath.Join(directory, version+".zip")
if info, err := os.Stat(target); err == nil && info.Size() == total {
fmt.Println("Source ZIP cached; Go will validate checksum")
return
}
client := &http.Client{Timeout: 90 * time.Second}
jobs := make(chan int64)
errors := make(chan error, 64)
var group sync.WaitGroup
for worker := 0; worker < 8; worker++ {
group.Add(1)
go func() {
defer group.Done()
for start := range jobs {
end := min(start+chunk, total) - 1
part := fmt.Sprintf("%s.part-%d", target, start)
if info, err := os.Stat(part); err == nil && info.Size() == end-start+1 {
continue
}
var last error
for attempt := 0; attempt < 4; attempt++ {
req, _ := http.NewRequest("GET", source, nil)
req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", start, end))
response, err := client.Do(req)
if err != nil {
last = fmt.Errorf("source range request failed")
continue
}
expected := fmt.Sprintf("bytes %d-%d/%d", start, end, total)
if response.StatusCode != 206 || response.Header.Get("Content-Range") != expected {
response.Body.Close()
last = fmt.Errorf("unexpected source range response: HTTP %d", response.StatusCode)
continue
}
data, err := io.ReadAll(io.LimitReader(response.Body, end-start+2))
response.Body.Close()
if err != nil || int64(len(data)) != end-start+1 {
last = fmt.Errorf("incomplete source range")
continue
}
if err := os.WriteFile(part, data, 0644); err != nil {
last = err
continue
}
last = nil
fmt.Printf("Source part %d verified\n", start/chunk+1)
break
}
if last != nil {
errors <- last
}
}
}()
}
for start := int64(0); start < total; start += chunk {
jobs <- start
}
close(jobs)
group.Wait()
close(errors)
for err := range errors {
panic(err)
}
out, err := os.Create(target + ".partial")
if err != nil {
panic(err)
}
for start := int64(0); start < total; start += chunk {
part, err := os.Open(fmt.Sprintf("%s.part-%d", target, start))
if err != nil {
panic(err)
}
if _, err := io.Copy(out, part); err != nil {
panic(err)
}
part.Close()
}
if err := out.Close(); err != nil {
panic(err)
}
if err := os.Rename(target+".partial", target); err != nil {
panic(err)
}
}
+789
View File
@@ -0,0 +1,789 @@
{
"uid": "messenger-lab6",
"title": "Мессенджер: диагностика и SLO",
"schemaVersion": 41,
"version": 1,
"editable": false,
"timezone": "utc",
"refresh": "5s",
"time": {
"from": "now-30m",
"to": "now"
},
"tags": [
"lab6",
"slo"
],
"panels": [
{
"id": 1,
"title": "Запросы через балансировщик, в секунду",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 0,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum(rate(haproxy_backend_http_responses_total{proxy=\"messenger\"}[1m]))",
"refId": "A",
"legendFormat": "все бизнес-запросы",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "Health requests use a separate backend and are excluded. Includes ingress 503 with no API available.",
"fieldConfig": {
"defaults": {
"unit": "reqps"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 2,
"title": "Доля ответов 5xx",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 0,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum(rate(haproxy_backend_http_responses_total{proxy=\"messenger\",code=\"5xx\"}[1m])) / clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy=\"messenger\"}[1m])),0.001)",
"refId": "A",
"legendFormat": "ошибки 5xx",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "",
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 3,
"title": "API: p50 / p95 / p99, секунды",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 8,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "histogram_quantile(0.5, sum by(le) (rate(messenger_http_duration_seconds_bucket[2m])))",
"refId": "A",
"legendFormat": "p50",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "histogram_quantile(0.95, sum by(le) (rate(messenger_http_duration_seconds_bucket[2m])))",
"refId": "B",
"legendFormat": "p95",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "histogram_quantile(0.99, sum by(le) (rate(messenger_http_duration_seconds_bucket[2m])))",
"refId": "C",
"legendFormat": "p99",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "Quantiles from combined histogram buckets; complete ASGI response, no average of replica quantiles.",
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 4,
"title": "Очередь: ожидающие задания",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 8,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "max(messenger_queue_depth)",
"refId": "A",
"legendFormat": "ожидают",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "Logical PostgreSQL jobs in queued state, not count of duplicate stream notifications.",
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 5,
"title": "Возраст старейшего незавершённого задания",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 16,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "max(messenger_oldest_job_age_seconds)",
"refId": "A",
"legendFormat": "возраст",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "",
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 6,
"title": "Обработчик: занято / доступно",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 16,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum(messenger_worker_busy)",
"refId": "A",
"legendFormat": "занято",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "sum(messenger_worker_capacity)",
"refId": "B",
"legendFormat": "всего мест",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "",
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 7,
"title": "Соединения PostgreSQL",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 24,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum by(service_name) (messenger_db_pool_used)",
"refId": "A",
"legendFormat": "{{service_name}} занято",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "sum by(service_name) (messenger_db_pool_waiting)",
"refId": "B",
"legendFormat": "{{service_name}} ожидают",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "",
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 8,
"title": "Попытки обработки по результату",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 24,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum by(outcome) (rate(messenger_job_attempts_total[2m]))",
"refId": "A",
"legendFormat": "{{outcome}}",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "",
"fieldConfig": {
"defaults": {
"unit": "ops"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 9,
"title": "Длительность попытки обработки: p95",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 32,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "histogram_quantile(0.95,sum by(le)(rate(messenger_job_duration_seconds_bucket[2m])))",
"refId": "A",
"legendFormat": "p95",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "",
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 10,
"title": "От приёма до ready: p50 / p95 / p99",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 32,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "histogram_quantile(0.5,sum by(le)(rate(messenger_time_to_ready_seconds_bucket[2m])))",
"refId": "A",
"legendFormat": "p50",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "histogram_quantile(0.95,sum by(le)(rate(messenger_time_to_ready_seconds_bucket[2m])))",
"refId": "B",
"legendFormat": "p95",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "histogram_quantile(0.99,sum by(le)(rate(messenger_time_to_ready_seconds_bucket[2m])))",
"refId": "C",
"legendFormat": "p99",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "Only completed publications have a duration. Deadline SLI below also counts unfinished tasks.",
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 11,
"title": "SLO API за 30 минут: цель 99%",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 40,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "1 - sum(increase(haproxy_backend_http_responses_total{proxy=\"messenger\",code=\"5xx\"}[30m])) / clamp_min(sum(increase(haproxy_backend_http_responses_total{proxy=\"messenger\"}[30m])),1)",
"refId": "A",
"legendFormat": "доступность",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "",
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 12,
"title": "SLO ready за 30 минут: 99% не позже 10 секунд",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 40,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum(increase(messenger_slo_decisions_total{outcome=\"good\"}[30m])) / clamp_min(sum(increase(messenger_slo_decisions_total[30m])),1)",
"refId": "A",
"legendFormat": "доля вовремя",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "Durable one-time decisions per non-obsolete logical job; unfinished jobs become bad at ten seconds. Synthetic 320x200 profile.",
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 13,
"title": "CPU процессов, ядра",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 48,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum by(service_name)(rate(messenger_process_cpu_seconds_total[1m]))",
"refId": "A",
"legendFormat": "{{service_name}}",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "",
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 14,
"title": "Память процессов",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 48,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "max by(service_name)(messenger_process_memory_bytes)",
"refId": "A",
"legendFormat": "{{service_name}}",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "",
"fieldConfig": {
"defaults": {
"unit": "bytes"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 15,
"title": "Буфер экспорта Collector",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 56,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "otelcol_exporter_queue_size",
"refId": "A",
"legendFormat": "{{exporter}}",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "otelcol_exporter_queue_capacity",
"refId": "B",
"legendFormat": "{{exporter}} capacity",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "",
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 16,
"title": "Ошибки отправки трасс и логов",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 56,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum(rate(otelcol_exporter_send_failed_spans[1m]))",
"refId": "A",
"legendFormat": "spans/s",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "sum(rate(otelcol_exporter_send_failed_log_records[1m]))",
"refId": "B",
"legendFormat": "logs/s",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "",
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 17,
"title": "Состояния локальных alerts",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 64,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "ALERTS{alertstate=\"firing\"}",
"refId": "A",
"legendFormat": "{{alertname}}",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "",
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 18,
"title": "Связанные логи API и обработчика",
"type": "logs",
"datasource": {
"type": "loki",
"uid": "loki"
},
"gridPos": {
"x": 12,
"y": 64,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "{service_name=~\"messenger-api|messenger-worker\"}",
"queryType": "range",
"datasource": {
"type": "loki",
"uid": "loki"
}
}
],
"options": {
"showTime": true,
"wrapLogMessage": true,
"sortOrder": "Descending"
},
"description": "Filter structured metadata trace_id in Explore; open the same ID in the Traces datasource."
}
],
"annotations": {
"list": []
}
}
@@ -0,0 +1,10 @@
apiVersion: 1
providers:
- name: Messenger
orgId: 1
folder: Laboratory 6
type: file
disableDeletion: true
editable: false
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,37 @@
apiVersion: 1
datasources:
- name: Metrics
uid: prometheus
type: prometheus
access: proxy
url: http://127.0.0.1:13909
isDefault: true
editable: false
jsonData:
httpMethod: POST
timeInterval: 5s
- name: Logs
uid: loki
type: loki
access: proxy
url: http://127.0.0.1:13310
editable: false
jsonData:
derivedFields:
- name: TraceID
matcherType: label
matcherRegex: trace_id
url: $${__value.raw}
datasourceUid: tempo
- name: Traces
uid: tempo
type: tempo
access: proxy
url: http://127.0.0.1:13320
editable: false
jsonData:
tracesToLogsV2:
datasourceUid: loki
filterByTraceID: true
spanStartTimeShift: -1m
spanEndTimeShift: 1m
+55
View File
@@ -0,0 +1,55 @@
global
log stdout format raw local0
maxconn 512
ssl-default-bind-options ssl-min-ver TLSv1.3 no-tls-tickets
ssl-default-server-options ssl-min-ver TLSv1.3 no-tls-tickets
hard-stop-after 10s
mworker-max-reloads 2
stats socket /tmp/admin.sock mode 600 level admin
defaults
mode http
log global
log-format "http status=%ST duration_ms=%Ta"
timeout connect 1s
timeout client 15s
timeout server 8s
timeout http-request 10s
timeout http-keep-alive 5s
retries 0
option httpclose
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 1s
hold obsolete 1s
hold nx 1s
frontend public
bind :8443 ssl crt /run/identity/current/bundle.pem
use_backend health if { path_beg /health/ }
default_backend messenger
backend messenger
balance roundrobin
option httpchk
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host api
http-check expect status 200
default-server check inter 1s fastinter 250ms fall 2 rise 1 resolvers docker init-addr libc,none resolve-prefer ipv4
server-template api 1-8 api:8443 ssl verify required ca-file /trust/ca.pem crt /run/identity/current/bundle.pem sni str(api) check-sni api verifyhost api no-ssl-reuse
backend health
balance roundrobin
option httpchk
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host api
http-check expect status 200
default-server check inter 1s fall 2 rise 1 resolvers docker init-addr libc,none
server-template api 1-8 api:8443 ssl verify required ca-file /trust/ca.pem crt /run/identity/current/bundle.pem sni str(api) check-sni api verifyhost api no-ssl-reuse
frontend internal_metrics
bind 127.0.0.1:8404
http-request use-service prometheus-exporter if { path /metrics }
http-request deny
+14
View File
@@ -0,0 +1,14 @@
disable_mlock = true
ui = false
api_addr = "https://openbao:8200"
storage "file" { path = "/data/storage" }
listener "tcp" {
address = "0.0.0.0:8200"
tls_min_version = "tls13"
tls_cert_file = "/run/identity/current/cert.pem"
tls_key_file = "/run/identity/current/key.pem"
tls_client_ca_file = "/trust/ca.pem"
tls_require_and_verify_client_cert = true
tls_auto_reload = true
tls_auto_reload_interval = "5s"
}
+4
View File
@@ -0,0 +1,4 @@
path "pki/issue/api" { capabilities = ["create", "update"] }
path "auth/token/renew-self" { capabilities = ["update"] }
path "auth/token/lookup-self" { capabilities = ["read"] }
path "secret/data/api" { capabilities = ["read"] }
+3
View File
@@ -0,0 +1,3 @@
path "pki/issue/broker" { capabilities = ["create", "update"] }
path "auth/token/renew-self" { capabilities = ["update"] }
path "auth/token/lookup-self" { capabilities = ["read"] }
+3
View File
@@ -0,0 +1,3 @@
path "pki/issue/cache" { capabilities = ["create", "update"] }
path "auth/token/renew-self" { capabilities = ["update"] }
path "auth/token/lookup-self" { capabilities = ["read"] }
+3
View File
@@ -0,0 +1,3 @@
path "pki/issue/grafana" { capabilities = ["create", "update"] }
path "auth/token/renew-self" { capabilities = ["update"] }
path "auth/token/lookup-self" { capabilities = ["read"] }
+3
View File
@@ -0,0 +1,3 @@
path "pki/issue/lb" { capabilities = ["create", "update"] }
path "auth/token/renew-self" { capabilities = ["update"] }
path "auth/token/lookup-self" { capabilities = ["read"] }
+3
View File
@@ -0,0 +1,3 @@
path "pki/issue/loki" { capabilities = ["create", "update"] }
path "auth/token/renew-self" { capabilities = ["update"] }
path "auth/token/lookup-self" { capabilities = ["read"] }
+4
View File
@@ -0,0 +1,4 @@
path "pki/issue/migrate" { capabilities = ["create", "update"] }
path "auth/token/renew-self" { capabilities = ["update"] }
path "auth/token/lookup-self" { capabilities = ["read"] }
path "secret/data/migrate" { capabilities = ["read"] }
+4
View File
@@ -0,0 +1,4 @@
path "pki/issue/observer" { capabilities = ["create", "update"] }
path "auth/token/renew-self" { capabilities = ["update"] }
path "auth/token/lookup-self" { capabilities = ["read"] }
path "secret/data/observer" { capabilities = ["read"] }
+3
View File
@@ -0,0 +1,3 @@
path "pki/issue/openbao" { capabilities = ["create", "update"] }
path "auth/token/renew-self" { capabilities = ["update"] }
path "auth/token/lookup-self" { capabilities = ["read"] }
+11
View File
@@ -0,0 +1,11 @@
path "pki/*" { capabilities = ["create", "read", "update", "delete", "list", "sudo"] }
path "auth/cert/*" { capabilities = ["create", "read", "update", "delete", "list"] }
path "secret/*" { capabilities = ["create", "read", "update", "delete", "list"] }
path "sys/policies/acl/messenger-*" { capabilities = ["create", "read", "update", "delete", "list"] }
path "sys/mounts/pki/tune" { capabilities = ["read", "update", "sudo"] }
path "sys/seal" { capabilities = ["update", "sudo"] }
path "auth/token/lookup-self" { capabilities = ["read"] }
path "auth/token/renew-self" { capabilities = ["update"] }
path "auth/token/accessors" { capabilities = ["list", "sudo"] }
path "auth/token/lookup-accessor" { capabilities = ["update", "sudo"] }
path "auth/token/revoke-accessor" { capabilities = ["update", "sudo"] }
+3
View File
@@ -0,0 +1,3 @@
path "pki/issue/otel" { capabilities = ["create", "update"] }
path "auth/token/renew-self" { capabilities = ["update"] }
path "auth/token/lookup-self" { capabilities = ["read"] }
+3
View File
@@ -0,0 +1,3 @@
path "pki/issue/postgres" { capabilities = ["create", "update"] }
path "auth/token/renew-self" { capabilities = ["update"] }
path "auth/token/lookup-self" { capabilities = ["read"] }
+3
View File
@@ -0,0 +1,3 @@
path "pki/issue/prometheus" { capabilities = ["create", "update"] }
path "auth/token/renew-self" { capabilities = ["update"] }
path "auth/token/lookup-self" { capabilities = ["read"] }
+4
View File
@@ -0,0 +1,4 @@
path "pki/issue/reconciler" { capabilities = ["create", "update"] }
path "auth/token/renew-self" { capabilities = ["update"] }
path "auth/token/lookup-self" { capabilities = ["read"] }
path "secret/data/reconciler" { capabilities = ["read"] }
+4
View File
@@ -0,0 +1,4 @@
path "pki/issue/relay" { capabilities = ["create", "update"] }
path "auth/token/renew-self" { capabilities = ["update"] }
path "auth/token/lookup-self" { capabilities = ["read"] }
path "secret/data/relay" { capabilities = ["read"] }
+3
View File
@@ -0,0 +1,3 @@
path "pki/issue/s3" { capabilities = ["create", "update"] }
path "auth/token/renew-self" { capabilities = ["update"] }
path "auth/token/lookup-self" { capabilities = ["read"] }
+3
View File
@@ -0,0 +1,3 @@
path "pki/issue/tempo" { capabilities = ["create", "update"] }
path "auth/token/renew-self" { capabilities = ["update"] }
path "auth/token/lookup-self" { capabilities = ["read"] }
+4
View File
@@ -0,0 +1,4 @@
path "pki/issue/worker" { capabilities = ["create", "update"] }
path "auth/token/renew-self" { capabilities = ["update"] }
path "auth/token/lookup-self" { capabilities = ["read"] }
path "secret/data/worker" { capabilities = ["read"] }
+50
View File
@@ -0,0 +1,50 @@
# Диагностика по сохранённой телеметрии
Открой dashboard «Мессенджер: диагностика и SLO», временная зона UTC.
Сопоставляй время оповещения с метриками, трассами и связанными логами.
## API errors
Признак: ApiHighErrorRate, ApiFastBurn или ApiSlowBurn. Числитель доступности:
`sum(rate(haproxy_backend_http_responses_total{proxy="messenger",code="5xx"}[2m]))`.
Знаменатель — тот же backend со всеми code. Health использует другой backend.
Сравни API histogram, DB pool used/waiting и worker busy. В Traces найди
ошибочный server span и вложенный db.postgresql или s3.*. Длинная DB-операция
с ошибкой и занятым пулом при нормальной очереди указывает на БД. Отсутствие
API span при ingress503 может означать отсутствие готовых API. Один5xx не
доказывает причину. Через trace_id найди соответствующий Logs record.
После исправления проверь новые сообщения, спад5xx, resolved и прежние данные.
## Queue age
Признак: QueueLagGrowing, ReadyFastBurn или ReadySlowBurn. Сравни логические
queued jobs PG, oldest job age и worker busy/capacity. Upload202 при росте
ожидающей очереди и отсутствии новых worker spans указывает на обработчик.
Если попытки идут и содержат DB/S3 ошибки, причина может быть в зависимости.
Найди путь upload→producer→consumer→S3/DB. Histogram ready содержит только
завершения, поэтому отдельно проверь deadline SLI для незавершённых jobs.
После восстановления проверь тот же attachment_id, original, спад и resolved.
## Telemetry backend
Проверь backend health, Collector queue и accepted/sent/failed счётчики.
Failed attempts не равны числу уникально потерянных spans: пакет повторяется.
После слива очередей сравни изменение accepted-minus-sent и исходное состояние.
SDK queues traces/logs512records, timeout0.75s; Collector memory limiter192MiB,
batch≤256, очереди logs/traces по32пакета, один sender и finite retry≤10s.
При отказе telemetry может теряться; измеряй память и настоящие бизнес-запросы.
После восстановления найди новую трассу и лог, а не только старый screenshot.
## SLO и окна
Учебный профиль: синтетические PNG320×200, upload не чаще одного каждые3s,
закреплённые CPU/RAM. API цель99%ответов без5xx за30m на ingress. Jobs цель99%
ready≤10s от PG created_at принимающей транзакции до committed_at публикации.
Начальная граница консервативно включает завершение принимающей транзакции.
Однократные durable good/bad решения учитывают failed и незавершённые после10s.
Ручной replay не стирает прежний bad; устаревшие до решения jobs исключены.
Burn rate = доля плохих событий/0.01. Быстрое правило: burn>14.4 в30s и2m,
непрерывно45s. Длительное: burn>6 в2m и5m, непрерывно60s. Короткие окна выбраны
для воспроизводимого стенда, а не универсальной production paging policy.
Измеряются краткий всплеск/длительная деградация/firing/resolved/ложные события.
Точность времени ограничена polling2s, scrape/evaluation5s и экспортом.
+53
View File
@@ -0,0 +1,53 @@
groups:
- name: messenger-slo
interval: 5s
rules:
- alert: ApiHighErrorRate
expr: sum(rate(haproxy_backend_http_responses_total{proxy="messenger",code="5xx"}[2m])) / clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="messenger"}[2m])),0.001) > 0.05
for: 20s
labels: {severity: warning, signal: api}
annotations:
summary: More than 5 percent business responses are 5xx
runbook: infra/otel/RUNBOOK.md#api-errors
- alert: QueueLagGrowing
expr: max(messenger_oldest_job_age_seconds) > 20 and max(messenger_queue_depth) > 0
for: 10s
labels: {severity: warning, signal: ready}
annotations:
summary: Oldest unfinished attachment exceeds 20 seconds
runbook: infra/otel/RUNBOOK.md#queue-age
- alert: ApiFastBurn
expr: (sum(rate(haproxy_backend_http_responses_total{proxy="messenger",code="5xx"}[30s])) / clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="messenger"}[30s])),0.001) / 0.01 > 14.4) and (sum(rate(haproxy_backend_http_responses_total{proxy="messenger",code="5xx"}[2m])) / clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="messenger"}[2m])),0.001) / 0.01 > 14.4)
for: 45s
labels: {severity: critical, signal: api, burn: fast}
annotations:
summary: API burns the one-percent error budget in both fast windows
runbook: infra/otel/RUNBOOK.md#api-errors
- alert: ApiSlowBurn
expr: (sum(rate(haproxy_backend_http_responses_total{proxy="messenger",code="5xx"}[2m])) / clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="messenger"}[2m])),0.001) / 0.01 > 6) and (sum(rate(haproxy_backend_http_responses_total{proxy="messenger",code="5xx"}[5m])) / clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="messenger"}[5m])),0.001) / 0.01 > 6)
for: 60s
labels: {severity: critical, signal: api, burn: slow}
annotations:
summary: API burns the error budget across two longer windows
runbook: infra/otel/RUNBOOK.md#api-errors
- alert: ReadyFastBurn
expr: (sum(rate(messenger_slo_decisions_total{outcome="bad"}[30s])) / clamp_min(sum(rate(messenger_slo_decisions_total[30s])),0.001) / 0.01 > 14.4) and (sum(rate(messenger_slo_decisions_total{outcome="bad"}[2m])) / clamp_min(sum(rate(messenger_slo_decisions_total[2m])),0.001) / 0.01 > 14.4)
for: 45s
labels: {severity: critical, signal: ready, burn: fast}
annotations:
summary: Attachment deadline SLO burns the error budget
runbook: infra/otel/RUNBOOK.md#queue-age
- alert: ReadySlowBurn
expr: (sum(rate(messenger_slo_decisions_total{outcome="bad"}[2m])) / clamp_min(sum(rate(messenger_slo_decisions_total[2m])),0.001) / 0.01 > 6) and (sum(rate(messenger_slo_decisions_total{outcome="bad"}[5m])) / clamp_min(sum(rate(messenger_slo_decisions_total[5m])),0.001) / 0.01 > 6)
for: 60s
labels: {severity: critical, signal: ready, burn: slow}
annotations:
summary: Sustained misses of the attachment ten-second deadline
runbook: infra/otel/RUNBOOK.md#queue-age
- alert: CollectorUnavailable
expr: up{job="collector"} == 0
for: 15s
labels: {severity: warning, signal: telemetry}
annotations:
summary: Collector self metrics are unavailable
runbook: infra/otel/RUNBOOK.md#telemetry-backend
+88
View File
@@ -0,0 +1,88 @@
receivers:
otlp:
protocols:
http:
endpoint: 127.0.0.1:4318
processors:
memory_limiter:
check_interval: 1s
limit_mib: 192
spike_limit_mib: 32
batch:
timeout: 1s
send_batch_size: 128
send_batch_max_size: 256
exporters:
prometheus:
endpoint: 127.0.0.1:8889
metric_expiration: 15s
resource_constant_labels:
included:
- service.name
- service.instance.id
- service.version
- deployment.environment.name
otlp_http/tempo:
endpoint: http://127.0.0.1:14319
timeout: 2s
sending_queue:
queue_size: 32
num_consumers: 1
block_on_overflow: false
retry_on_failure:
initial_interval: 1s
max_interval: 2s
max_elapsed_time: 10s
otlp_http/loki:
endpoint: http://127.0.0.1:13310/otlp
timeout: 2s
sending_queue:
queue_size: 32
num_consumers: 1
block_on_overflow: false
retry_on_failure:
initial_interval: 1s
max_interval: 2s
max_elapsed_time: 10s
extensions:
health_check:
endpoint: 127.0.0.1:13133
service:
extensions:
- health_check
telemetry:
logs:
level: warn
metrics:
level: detailed
readers:
- pull:
exporter:
prometheus:
host: 127.0.0.1
port: 8888
pipelines:
traces:
receivers:
- otlp
processors:
- memory_limiter
- batch
exporters:
- otlp_http/tempo
logs:
receivers:
- otlp
processors:
- memory_limiter
- batch
exporters:
- otlp_http/loki
metrics:
receivers:
- otlp
processors:
- memory_limiter
- batch
exporters:
- prometheus
+44
View File
@@ -0,0 +1,44 @@
auth_enabled: false
server:
http_listen_port: 3100
log_level: warn
http_listen_address: 127.0.0.1
grpc_listen_address: 127.0.0.1
common:
path_prefix: /loki
replication_factor: 1
ring:
kvstore:
store: inmemory
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
schema_config:
configs:
- from: 2026-01-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
allow_structured_metadata: true
ingestion_rate_mb: 4
ingestion_burst_size_mb: 8
volume_enabled: true
otlp_config:
resource_attributes:
ignore_defaults: true
attributes_config:
- action: index_label
attributes:
- service.name
- action: structured_metadata
attributes:
- service.instance.id
- service.version
- deployment.environment.name
analytics:
reporting_enabled: false
+30
View File
@@ -0,0 +1,30 @@
global:
scrape_interval: 5s
evaluation_interval: 5s
rule_files:
- /etc/prometheus/alerts.yaml
scrape_configs:
- job_name: application_otlp
static_configs:
- targets:
- 127.0.0.1:18889
- job_name: collector
static_configs:
- targets:
- 127.0.0.1:18888
- job_name: ingress
static_configs:
- targets:
- 127.0.0.1:18404
- job_name: prometheus
static_configs:
- targets:
- localhost:9090
- job_name: tempo
static_configs:
- targets:
- 127.0.0.1:13200
- job_name: loki
static_configs:
- targets:
- 127.0.0.1:13100
+22
View File
@@ -0,0 +1,22 @@
target: all
stream_over_http_enabled: true
server:
http_listen_port: 3200
log_level: warn
http_listen_address: 127.0.0.1
grpc_listen_address: 127.0.0.1
distributor:
receivers:
otlp:
protocols:
http:
endpoint: 127.0.0.1:4318
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks
usage_report:
reporting_enabled: false
+7
View File
@@ -0,0 +1,7 @@
{
"otel": "otel/opentelemetry-collector-contrib:0.165.0@sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea",
"prometheus": "prom/prometheus:v3.16.0@sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06",
"loki": "grafana/loki:3.7.10@sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7",
"tempo": "grafana/tempo:3.1.1@sha256:64e2fbd56d9c2b3412a4b430a58ea59e91a670b1e75f920a0c702213ad145044",
"grafana": "grafana/grafana:13.3.1@sha256:0615ec4fbd4072004b7d86b46ded63013a74b7d6eb1119273dd89e8fa25c13cf"
}
+14
View File
@@ -0,0 +1,14 @@
#!/bin/sh
set -eu
root_user=$(cat /run/secrets/s3_root_user)
root_password=$(cat /run/secrets/s3_root_password)
api_key=$(cat /run/secrets/s3_access_key)
api_secret=$(cat /run/secrets/s3_secret_key)
# Credentials are passed only inside this isolated bootstrap container.
mc alias set local http://s3:9000 "$root_user" "$root_password" >/dev/null 2>&1
mc mb --ignore-existing local/messenger >/dev/null 2>&1
mc anonymous set none local/messenger >/dev/null 2>&1
mc admin user add local "$api_key" "$api_secret" >/dev/null 2>&1
mc admin policy create local messenger-api /policy.json >/dev/null 2>&1
mc admin policy attach local messenger-api --user "$api_key" >/dev/null 2>&1
printf '%s\n' 'Private bucket and scoped application policy ready'
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
set -eu
export MINIO_ROOT_USER="$(cat /run/secrets/s3_root_user)"
export MINIO_ROOT_PASSWORD="$(cat /run/secrets/s3_root_password)"
export MINIO_BROWSER=off
exec minio server /data --address 127.0.0.1:9000 --console-address 127.0.0.1:9001
+15
View File
@@ -0,0 +1,15 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetBucketLocation", "s3:ListBucket"],
"Resource": ["arn:aws:s3:::messenger"]
},
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
"Resource": ["arn:aws:s3:::messenger/objects/*"]
}
]
}
+49
View File
@@ -0,0 +1,49 @@
FROM golang:1.24.8-bookworm@sha256:4ed690d6649d63c312b99a6120025ec79ce3b542968a37da53d6236c7c61a848 AS toolchain
ENV CGO_ENABLED=0 GOMAXPROCS=2 GOFLAGS=-p=2 GOTOOLCHAIN=local
FROM toolchain AS minio-build
WORKDIR /source
COPY infra/fetch-source.go /tmp/fetch-source.go
RUN --mount=type=cache,target=/go/pkg/mod,sharing=locked \
--mount=type=cache,target=/root/.cache/go-build,sharing=locked \
go run /tmp/fetch-source.go && \
for attempt in 1 2 3 4; do \
go mod download -json github.com/minio/minio@v0.0.0-20251015172955-9e49d5e7a648 && break; \
test "$attempt" -lt 4 || exit 1; sleep 1; \
done && \
cp -a /go/pkg/mod/github.com/minio/minio@v0.0.0-20251015172955-9e49d5e7a648/. /source/
RUN --mount=type=cache,target=/go/pkg/mod,sharing=locked \
--mount=type=cache,target=/root/.cache/go-build,sharing=locked \
for attempt in 1 2 3; do \
timeout 900s go build -trimpath -ldflags='-s -w -X github.com/minio/minio/cmd.Version=2025-10-15T17:29:55Z -X github.com/minio/minio/cmd.ReleaseTag=RELEASE.2025-10-15T17-29-55Z -X github.com/minio/minio/cmd.CommitID=9e49d5e7a648f00e26f2246f4dc28e6b07f8c84a' -o /out/minio . && break; \
test "$attempt" -lt 3 || exit 1; sleep 1; \
done
FROM toolchain AS mc-build
WORKDIR /source
RUN git init . && git remote add origin https://github.com/minio/mc.git && \
git fetch --depth 1 origin 7394ce0dd2a80935aded936b09fa12cbb3cb8096 && git checkout --detach FETCH_HEAD
RUN --mount=type=cache,target=/go/pkg/mod,sharing=locked \
--mount=type=cache,target=/root/.cache/go-build,sharing=locked \
go build -trimpath -ldflags='-s -w' -o /out/mc .
FROM python:3.14.7-slim-trixie@sha256:51dafde81dbdb6ebde285137a295cf18a47ca95234fe388a343719cb97305b3d AS server
LABEL org.opencontainers.image.revision=9e49d5e7a648f00e26f2246f4dc28e6b07f8c84a org.opencontainers.image.version=RELEASE.2025-10-15T17-29-55Z
COPY --from=minio-build /out/minio /usr/local/bin/minio
COPY --from=minio-build /source/LICENSE /licenses/minio.LICENSE
COPY --chmod=755 infra/s3-entrypoint.sh /usr/local/bin/s3-entrypoint
RUN mkdir /data && chown 10001:10001 /data
USER 10001:10001
ENTRYPOINT ["/usr/local/bin/s3-entrypoint"]
EXPOSE 9000
HEALTHCHECK --interval=2s --timeout=2s --start-period=10s --retries=30 CMD ["python","-c","import urllib.request; urllib.request.urlopen('http://127.0.0.1:9000/minio/health/ready',timeout=1).read()"]
FROM python:3.14.7-slim-trixie@sha256:51dafde81dbdb6ebde285137a295cf18a47ca95234fe388a343719cb97305b3d AS bootstrap
LABEL org.opencontainers.image.revision=7394ce0dd2a80935aded936b09fa12cbb3cb8096 org.opencontainers.image.version=RELEASE.2025-08-13T08-35-41Z
COPY --from=mc-build /out/mc /usr/local/bin/mc
COPY --from=mc-build /source/LICENSE /licenses/mc.LICENSE
COPY --chmod=755 infra/s3-bootstrap.sh /usr/local/bin/s3-bootstrap
COPY infra/s3-policy.json /policy.json
USER 10001:10001
ENV MC_CONFIG_DIR=/tmp/mc
ENTRYPOINT ["/usr/local/bin/s3-bootstrap"]
+17
View File
@@ -0,0 +1,17 @@
{
"role": "api",
"dns": [
"api",
"localhost"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": false,
"servers": [],
"outbounds": [],
"bootstrap": "/bootstrap",
"kv": true
}
+16
View File
@@ -0,0 +1,16 @@
{
"role": "broker",
"dns": [
"broker"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": false,
"servers": [],
"outbounds": [],
"bootstrap": "/bootstrap",
"kv": false
}
+16
View File
@@ -0,0 +1,16 @@
{
"role": "cache",
"dns": [
"cache"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": false,
"servers": [],
"outbounds": [],
"bootstrap": "/bootstrap",
"kv": false
}
+20
View File
@@ -0,0 +1,20 @@
{
"role": "grafana",
"dns": [
"grafana",
"localhost"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": false,
"servers": [],
"outbounds": [],
"ip": [
"127.0.0.1"
],
"bootstrap": "/bootstrap",
"kv": false
}
+21
View File
@@ -0,0 +1,21 @@
{
"role": "lb",
"dns": [
"lb",
"localhost"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": false,
"servers": [],
"outbounds": [],
"ip": [
"127.0.0.1"
],
"bootstrap": "/bootstrap",
"kv": false,
"reload_pid_one": true
}
+16
View File
@@ -0,0 +1,16 @@
{
"role": "loki",
"dns": [
"loki"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": false,
"servers": [],
"outbounds": [],
"bootstrap": "/bootstrap",
"kv": false
}
+16
View File
@@ -0,0 +1,16 @@
{
"role": "migrate",
"dns": [
"migrate"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": false,
"servers": [],
"outbounds": [],
"bootstrap": "/bootstrap",
"kv": true
}
+16
View File
@@ -0,0 +1,16 @@
{
"role": "observer",
"dns": [
"observer"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": false,
"servers": [],
"outbounds": [],
"bootstrap": "/bootstrap",
"kv": true
}
+20
View File
@@ -0,0 +1,20 @@
{
"role": "openbao",
"dns": [
"openbao",
"localhost"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": false,
"servers": [],
"outbounds": [],
"ip": [
"127.0.0.1"
],
"bootstrap": "/bootstrap",
"kv": false
}
+16
View File
@@ -0,0 +1,16 @@
{
"role": "otel",
"dns": [
"otel"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": false,
"servers": [],
"outbounds": [],
"bootstrap": "/bootstrap",
"kv": false
}
+16
View File
@@ -0,0 +1,16 @@
{
"role": "postgres",
"dns": [
"postgres"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": false,
"servers": [],
"outbounds": [],
"bootstrap": "/bootstrap",
"kv": false
}
+16
View File
@@ -0,0 +1,16 @@
{
"role": "prometheus",
"dns": [
"prometheus"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": false,
"servers": [],
"outbounds": [],
"bootstrap": "/bootstrap",
"kv": false
}
+16
View File
@@ -0,0 +1,16 @@
{
"role": "reconciler",
"dns": [
"reconciler"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": false,
"servers": [],
"outbounds": [],
"bootstrap": "/bootstrap",
"kv": true
}
+16
View File
@@ -0,0 +1,16 @@
{
"role": "relay",
"dns": [
"relay"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": false,
"servers": [],
"outbounds": [],
"bootstrap": "/bootstrap",
"kv": true
}
+20
View File
@@ -0,0 +1,20 @@
{
"role": "s3",
"dns": [
"s3",
"localhost"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": false,
"servers": [],
"outbounds": [],
"ip": [
"127.0.0.1"
],
"bootstrap": "/bootstrap",
"kv": false
}
+16
View File
@@ -0,0 +1,16 @@
{
"role": "tempo",
"dns": [
"tempo"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": false,
"servers": [],
"outbounds": [],
"bootstrap": "/bootstrap",
"kv": false
}
+16
View File
@@ -0,0 +1,16 @@
{
"role": "worker",
"dns": [
"worker"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": false,
"servers": [],
"outbounds": [],
"bootstrap": "/bootstrap",
"kv": true
}
+33
View File
@@ -0,0 +1,33 @@
{
"role": "api",
"dns": [
"api",
"localhost"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": true,
"servers": [
{
"listen": "0.0.0.0:8443",
"target": "127.0.0.1:8080",
"protocol": "http",
"allow": {
"spiffe://messenger/lb": [
"* /"
]
},
"public": false
}
],
"outbounds": [
{
"listen": "127.0.0.1:14318",
"target": "https://otel:4438",
"server_identity": "spiffe://messenger/otel"
}
]
}
+25
View File
@@ -0,0 +1,25 @@
{
"role": "broker",
"dns": [
"broker"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": true,
"servers": [
{
"listen": "0.0.0.0:6380",
"target": "127.0.0.1:6379",
"protocol": "tcp",
"allow": {
"spiffe://messenger/relay": [],
"spiffe://messenger/worker": [],
"spiffe://messenger/operator": []
}
}
],
"outbounds": []
}
+24
View File
@@ -0,0 +1,24 @@
{
"role": "cache",
"dns": [
"cache"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": true,
"servers": [
{
"listen": "0.0.0.0:6380",
"target": "127.0.0.1:6379",
"protocol": "tcp",
"allow": {
"spiffe://messenger/api": [],
"spiffe://messenger/operator": []
}
}
],
"outbounds": []
}
+631
View File
@@ -0,0 +1,631 @@
// A bounded TLS boundary; cleartext targets must bind only to loopback.
package main
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
"time"
)
type Boundary struct {
Listen string `json:"listen"`
Target string `json:"target"`
Protocol string `json:"protocol"`
// Identity -> allowed HTTP method/path prefixes; an empty list denies HTTP.
Allow map[string][]string `json:"allow"`
Public bool `json:"public"`
}
type Outbound struct {
Listen string `json:"listen"`
Target string `json:"target"`
Identity string `json:"server_identity"`
}
type Config struct {
Outbounds []Outbound `json:"outbounds"`
ServeOnly bool `json:"serve_only"`
ReloadPIDOne bool `json:"reload_pid_one"`
Role string `json:"role"`
DNS []string `json:"dns"`
IP []string `json:"ip"`
Bao string `json:"bao"`
Trust string `json:"trust"`
Bootstrap string `json:"bootstrap"`
Identity string `json:"identity"`
Revoked string `json:"revoked"`
TTL string `json:"ttl"`
KV bool `json:"kv"`
Servers []Boundary `json:"servers"`
}
type Agent struct {
c Config
mu sync.Mutex
token string
tokenUntil time.Time
}
func event(name string) { log.Print("{\"event\":\"" + name + "\"}") }
func trust(c Config) (*x509.CertPool, error) {
raw, e := os.ReadFile(c.Trust)
if e != nil {
return nil, e
}
pool := x509.NewCertPool()
if !pool.AppendCertsFromPEM(raw) {
return nil, errors.New("invalid trust bundle")
}
return pool, nil
}
func material(c Config) (tls.Certificate, error) {
base := filepath.Join(c.Identity, "current")
if real, e := filepath.EvalSymlinks(base); e == nil {
base = real
} else {
base = c.Bootstrap
}
return tls.LoadX509KeyPair(filepath.Join(base, "cert.pem"), filepath.Join(base, "key.pem"))
}
func revoked(c Config, cert *x509.Certificate) bool {
raw, e := os.ReadFile(c.Revoked)
if e != nil {
return true
} // missing policy fails closed
var entries map[string]bool
if json.Unmarshal(raw, &entries) != nil {
return true
}
return entries[strings.ToLower(cert.SerialNumber.Text(16))]
}
func peer(c Config, state tls.ConnectionState, b Boundary) (string, error) {
if b.Public {
return "", nil
}
if len(state.VerifiedChains) == 0 || len(state.PeerCertificates) == 0 {
return "", errors.New("client certificate required")
}
cert := state.PeerCertificates[0]
roots, err := trust(c)
if err != nil {
return "", err
}
intermediates := x509.NewCertPool()
for _, item := range state.PeerCertificates[1:] {
intermediates.AddCert(item)
}
if _, err = cert.Verify(x509.VerifyOptions{Roots: roots, Intermediates: intermediates, KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}}); err != nil {
return "", errors.New("current trust denies client")
}
if time.Now().Before(cert.NotBefore) || !time.Now().Before(cert.NotAfter) || revoked(c, cert) {
return "", errors.New("client certificate unavailable")
}
for _, identity := range cert.URIs {
if _, ok := b.Allow[identity.String()]; ok {
return identity.String(), nil
}
}
return "", errors.New("client identity denied")
}
func serverTLS(c Config, b Boundary) *tls.Config {
return &tls.Config{MinVersion: tls.VersionTLS13, SessionTicketsDisabled: true, GetConfigForClient: func(_ *tls.ClientHelloInfo) (*tls.Config, error) {
cert, e := material(c)
if e != nil {
return nil, e
}
roots, e := trust(c)
if e != nil {
return nil, e
}
conf := &tls.Config{MinVersion: tls.VersionTLS13, Certificates: []tls.Certificate{cert}, ClientCAs: roots, SessionTicketsDisabled: true}
if !b.Public {
conf.ClientAuth = tls.RequireAndVerifyClientCert
conf.VerifyConnection = func(s tls.ConnectionState) error { _, e := peer(c, s, b); return e }
}
return conf, nil
}}
}
func atomicFile(path string, raw []byte) error {
temp := path + ".new"
if e := os.WriteFile(temp, raw, 0600); e != nil {
return e
}
return os.Rename(temp, path)
}
func (a *Agent) request(method, path string, body any, authenticated bool) (map[string]any, error) {
cert, e := material(a.c)
if e != nil {
return nil, e
}
roots, e := trust(a.c)
if e != nil {
return nil, e
}
transport := &http.Transport{TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS13, RootCAs: roots, Certificates: []tls.Certificate{cert}}, DisableKeepAlives: true, ResponseHeaderTimeout: 4 * time.Second}
defer transport.CloseIdleConnections()
client := &http.Client{Transport: transport, Timeout: 5 * time.Second}
var encoded []byte
if body != nil {
encoded, e = json.Marshal(body)
if e != nil {
return nil, e
}
}
request, e := http.NewRequest(method, a.c.Bao+"/v1/"+path, bytes.NewReader(encoded))
if e != nil {
return nil, e
}
request.Header.Set("Content-Type", "application/json")
if authenticated {
request.Header.Set("X-Vault-Token", a.token)
}
response, e := client.Do(request)
if e != nil {
return nil, errors.New("identity service unavailable")
}
defer response.Body.Close()
if response.StatusCode >= 300 {
return nil, fmt.Errorf("identity service status %d", response.StatusCode)
}
var data map[string]any
e = json.NewDecoder(io.LimitReader(response.Body, 1024*1024)).Decode(&data)
return data, e
}
func (a *Agent) refresh() error {
a.mu.Lock()
defer a.mu.Unlock()
now := time.Now()
if a.token != "" && time.Until(a.tokenUntil) < 95*time.Second {
result, err := a.request("POST", "auth/token/renew-self", map[string]string{"increment": "120s"}, true)
if err == nil {
auth, ok := result["auth"].(map[string]any)
if !ok {
return errors.New("invalid renewal response")
}
ttl, ok := auth["lease_duration"].(float64)
if !ok || ttl < 1 {
return errors.New("invalid renewed lease")
}
a.tokenUntil = now.Add(time.Duration(ttl * float64(time.Second)))
event("identity.token_renewed")
} else {
a.token = ""
}
}
if a.token == "" {
// The exact CN+URI constraints select the correct role. Omitting name
// permits old/new CA roles to coexist safely during trust rollover.
result, err := a.request("POST", "auth/cert/login", map[string]string{}, false)
if err != nil {
return err
}
auth, ok := result["auth"].(map[string]any)
if !ok {
return errors.New("invalid auth response")
}
a.token, ok = auth["client_token"].(string)
if !ok {
return errors.New("missing service token")
}
ttl, ok := auth["lease_duration"].(float64)
if !ok || ttl < 1 {
return errors.New("invalid service lease")
}
a.tokenUntil = now.Add(time.Duration(ttl * float64(time.Second)))
event("identity.authenticated")
}
cert, e := material(a.c)
_, currentErr := os.Stat(filepath.Join(a.c.Identity, "current"))
_, initializedErr := os.Stat(filepath.Join(a.c.Identity, "agent.json"))
renew := initializedErr != nil || currentErr != nil || e != nil || cert.Leaf == nil || time.Until(cert.Leaf.NotAfter) < 80*time.Second
if renew {
request := map[string]any{"common_name": a.c.Role, "alt_names": strings.Join(a.c.DNS, ","), "uri_sans": "spiffe://messenger/" + a.c.Role, "ttl": a.c.TTL}
if len(a.c.IP) > 0 {
request["ip_sans"] = strings.Join(a.c.IP, ",")
}
result, e := a.request("POST", "pki/issue/"+a.c.Role, request, true)
if e != nil {
return e
}
data, ok := result["data"].(map[string]any)
if !ok {
return errors.New("invalid PKI response")
}
crt, ok := data["certificate"].(string)
if !ok {
return errors.New("missing certificate")
}
key, ok := data["private_key"].(string)
if !ok {
return errors.New("missing private key")
}
if chain, ok := data["ca_chain"].([]any); ok {
for _, item := range chain {
crt += "\n" + item.(string)
}
}
parsed, e := tls.X509KeyPair([]byte(crt), []byte(key))
if e != nil {
return e
}
dir, e := os.MkdirTemp(a.c.Identity, "generation-")
if e != nil {
return e
}
if e = os.WriteFile(filepath.Join(dir, "cert.pem"), []byte(crt), 0600); e != nil {
return e
}
if e = os.WriteFile(filepath.Join(dir, "key.pem"), []byte(key), 0600); e != nil {
return e
}
if e = os.WriteFile(filepath.Join(dir, "bundle.pem"), []byte(crt+"\n"+key), 0600); e != nil {
return e
}
link := filepath.Join(a.c.Identity, "next")
os.Remove(link)
if e = os.Symlink(filepath.Base(dir), link); e != nil {
return e
}
if e = os.Rename(link, filepath.Join(a.c.Identity, "current")); e != nil {
return e
}
// Retain only the current and immediately previous generations, bounding tmpfs.
entries, _ := os.ReadDir(a.c.Identity)
for _, entry := range entries {
if entry.IsDir() && strings.HasPrefix(entry.Name(), "generation-") && entry.Name() != filepath.Base(dir) {
info, _ := entry.Info()
if info != nil && now.Sub(info.ModTime()) > 3*time.Minute {
os.RemoveAll(filepath.Join(a.c.Identity, entry.Name()))
}
}
}
if parsed.Leaf == nil {
return errors.New("unparsed certificate")
}
event("identity.certificate_issued")
if a.c.ReloadPIDOne {
if e = syscall.Kill(1, syscall.SIGUSR2); e != nil {
return errors.New("certificate reload failed")
}
}
}
if a.c.KV {
result, e := a.request("GET", "secret/data/"+a.c.Role, nil, true)
if e != nil {
return e
}
outer, ok := result["data"].(map[string]any)
if !ok {
return errors.New("invalid secret response")
}
values, ok := outer["data"].(map[string]any)
if !ok {
return errors.New("invalid secret values")
}
expiry := now.Add(60 * time.Second)
if a.tokenUntil.Before(expiry) {
expiry = a.tokenUntil
}
data, e := json.Marshal(map[string]any{"fetched_at": now.Unix(), "valid_until": expiry.Unix(), "values": values})
if e != nil {
return e
}
if e = atomicFile(filepath.Join(a.c.Identity, "secrets.json"), data); e != nil {
return e
}
}
return atomicFile(filepath.Join(a.c.Identity, "agent.json"), []byte(`{"refreshed_at":`+strconv.FormatInt(now.Unix(), 10)+`}`))
}
type boundedListener struct {
net.Listener
slots chan struct{}
}
type boundedConn struct {
net.Conn
once sync.Once
release func()
}
func (c *boundedConn) Close() error { e := c.Conn.Close(); c.once.Do(c.release); return e }
func (l *boundedListener) Accept() (net.Conn, error) {
for {
c, e := l.Listener.Accept()
if e != nil {
return nil, e
}
select {
case l.slots <- struct{}{}:
return &boundedConn{Conn: c, release: func() { <-l.slots }}, nil
default:
c.Close()
}
}
}
func runHTTP(c Config, b Boundary) error {
target, e := url.Parse("http://" + b.Target)
if e != nil {
return e
}
proxy := httputil.NewSingleHostReverseProxy(target)
proxy.Transport = &http.Transport{MaxIdleConns: 32, MaxIdleConnsPerHost: 16, ResponseHeaderTimeout: 8 * time.Second, IdleConnTimeout: 30 * time.Second}
proxy.ErrorLog = log.New(io.Discard, "", 0)
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, e error) {
w.Header().Set("Connection", "close")
http.Error(w, "Protected service unavailable", 503)
}
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Force a fresh handshake after each response: no indefinitely cached
// certificate identity across rollover, expiry or serial revocation.
w.Header().Set("Connection", "close")
identity, e := peer(c, *r.TLS, b)
if e != nil {
w.Header().Set("Connection", "close")
http.Error(w, "Client identity denied", 403)
return
}
allowed := b.Public
for _, rule := range b.Allow[identity] {
parts := strings.SplitN(rule, " ", 2)
if len(parts) == 2 && (parts[0] == "*" || parts[0] == r.Method) && strings.HasPrefix(r.URL.Path, parts[1]) {
allowed = true
}
}
if !allowed {
http.Error(w, "Operation denied", 403)
return
}
r.Header.Del("X-Forwarded-Client-Cert")
r.Header.Del("X-TLS-Identity")
proxy.ServeHTTP(w, r)
})
listener, e := net.Listen("tcp", b.Listen)
if e != nil {
return e
}
listener = &boundedListener{Listener: listener, slots: make(chan struct{}, 128)}
server := &http.Server{Handler: handler, TLSConfig: serverTLS(c, b), ReadHeaderTimeout: 5 * time.Second, IdleTimeout: 30 * time.Second, MaxHeaderBytes: 32768, ErrorLog: log.New(io.Discard, "", 0)}
return server.Serve(tls.NewListener(listener, server.TLSConfig))
}
// Native clients use a private loopback endpoint when their certificate
// reload behavior cannot meet the short credential lifetime. Every network
// connection is verified mTLS; configuration cannot publish this HTTP hop.
func runOutbound(c Config, b Outbound) error {
target, e := url.Parse(b.Target)
if e != nil || target.Scheme != "https" || target.Hostname() == "" {
return errors.New("outbound TLS target required")
}
host, _, e := net.SplitHostPort(b.Listen)
if e != nil || host != "127.0.0.1" {
return errors.New("outbound listener must be loopback")
}
proxy := httputil.NewSingleHostReverseProxy(target)
proxy.Transport = &http.Transport{
DisableKeepAlives: true, MaxConnsPerHost: 32, ResponseHeaderTimeout: 8 * time.Second,
DialTLSContext: func(ctx context.Context, network, address string) (net.Conn, error) {
cert, e := material(c)
if e != nil {
return nil, e
}
roots, e := trust(c)
if e != nil {
return nil, e
}
config := &tls.Config{MinVersion: tls.VersionTLS13, RootCAs: roots, Certificates: []tls.Certificate{cert}, ServerName: target.Hostname(), VerifyConnection: func(state tls.ConnectionState) error {
if len(state.VerifiedChains) == 0 || len(state.PeerCertificates) == 0 {
return errors.New("unverified protected server")
}
leaf := state.PeerCertificates[0]
if revoked(c, leaf) {
return errors.New("protected server revoked")
}
if b.Identity != "" {
found := false
for _, identity := range leaf.URIs {
if identity.String() == b.Identity {
found = true
}
}
if !found {
return errors.New("protected server identity denied")
}
}
return nil
}}
dialer := tls.Dialer{NetDialer: &net.Dialer{Timeout: 2 * time.Second}, Config: config}
return dialer.DialContext(ctx, network, address)
},
}
proxy.ErrorLog = log.New(io.Discard, "", 0)
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, e error) {
w.Header().Set("Connection", "close")
http.Error(w, "Protected destination unavailable", 503)
}
listener, e := net.Listen("tcp", b.Listen)
if e != nil {
return e
}
listener = &boundedListener{Listener: listener, slots: make(chan struct{}, 64)}
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Connection", "close")
proxy.ServeHTTP(w, r)
})
server := &http.Server{Handler: handler, ReadHeaderTimeout: 5 * time.Second, IdleTimeout: 10 * time.Second, MaxHeaderBytes: 32768, ErrorLog: log.New(io.Discard, "", 0)}
return server.Serve(listener)
}
func runTCP(c Config, b Boundary) error {
listener, e := net.Listen("tcp", b.Listen)
if e != nil {
return e
}
slots := make(chan struct{}, 128)
for {
raw, e := listener.Accept()
if e != nil {
return e
}
select {
case slots <- struct{}{}:
default:
raw.Close()
continue
}
go func() {
defer func() { <-slots }()
defer raw.Close()
raw.SetDeadline(time.Now().Add(5 * time.Second))
if b.Protocol == "postgres" {
request := make([]byte, 8)
if _, e := io.ReadFull(raw, request); e != nil {
return
}
if binary.BigEndian.Uint32(request[:4]) != 8 || binary.BigEndian.Uint32(request[4:]) != 80877103 {
return
}
if _, e := raw.Write([]byte{'S'}); e != nil {
return
}
}
client := tls.Server(raw, serverTLS(c, b))
if e := client.Handshake(); e != nil {
return
}
target, e := net.DialTimeout("tcp", b.Target, 2*time.Second)
if e != nil {
return
}
defer target.Close()
// Bound a previously authenticated connection even after expiry/revocation.
deadline := time.Now().Add(45 * time.Second)
state := client.ConnectionState()
if len(state.PeerCertificates) > 0 && state.PeerCertificates[0].NotAfter.Before(deadline) {
deadline = state.PeerCertificates[0].NotAfter
}
client.SetDeadline(deadline)
target.SetDeadline(deadline)
done := make(chan struct{}, 1)
go func() { io.Copy(target, client); done <- struct{}{} }()
io.Copy(client, target)
client.Close()
target.Close()
<-done
}()
}
}
func main() {
if len(os.Args) != 2 {
event("gateway.invalid_configuration")
os.Exit(2)
}
raw, e := os.ReadFile(os.Args[1])
if e != nil {
event("gateway.invalid_configuration")
os.Exit(2)
}
var c Config
if json.Unmarshal(raw, &c) != nil || c.Role == "" {
event("gateway.invalid_configuration")
os.Exit(2)
}
if c.TTL == "" {
c.TTL = "120s"
}
if e = os.MkdirAll(c.Identity, 0700); e != nil {
event("gateway.identity_directory_unavailable")
os.Exit(2)
}
for _, b := range c.Servers {
host, _, err := net.SplitHostPort(b.Target)
if err != nil || (host != "127.0.0.1" && host != "[::1]" && host != "::1") {
event("gateway.nonlocal_target_denied")
os.Exit(2)
}
}
agent := &Agent{c: c}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
// Bootstrap failures never start a cleartext fallback listener.
if !c.ServeOnly {
for {
if e = agent.refresh(); e == nil {
break
}
event("identity.refresh_failed")
select {
case <-ctx.Done():
return
case <-time.After(3 * time.Second):
}
}
go func() {
ticker := time.NewTicker(15 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
if agent.refresh() != nil {
event("identity.refresh_failed")
}
}
}
}()
} else {
for {
cert, err := material(c)
if err == nil && cert.Leaf != nil && time.Now().Before(cert.Leaf.NotAfter) {
break
}
select {
case <-ctx.Done():
return
case <-time.After(time.Second):
}
}
}
for _, boundary := range c.Servers {
go func(b Boundary) {
var e error
if b.Protocol == "http" {
e = runHTTP(c, b)
} else {
e = runTCP(c, b)
}
if e != nil {
event("gateway.listener_failed")
stop()
}
}(boundary)
}
for _, outbound := range c.Outbounds {
go func(b Outbound) {
if e := runOutbound(c, b); e != nil {
event("gateway.outbound_failed")
stop()
}
}(outbound)
}
event("gateway.ready")
<-ctx.Done()
}
+122
View File
@@ -0,0 +1,122 @@
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/json"
"encoding/pem"
"math/big"
"net/url"
"os"
"path/filepath"
"testing"
"time"
)
type authority struct {
cert *x509.Certificate
key *ecdsa.PrivateKey
pem []byte
}
func root(t *testing.T) authority {
t.Helper()
key, e := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if e != nil {
t.Fatal(e)
}
template := &x509.Certificate{SerialNumber: big.NewInt(time.Now().UnixNano()), Subject: pkix.Name{CommonName: "Synthetic test CA"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign}
der, e := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
if e != nil {
t.Fatal(e)
}
cert, e := x509.ParseCertificate(der)
if e != nil {
t.Fatal(e)
}
return authority{cert, key, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})}
}
func client(t *testing.T, ca authority, role string, expired bool) *x509.Certificate {
t.Helper()
key, e := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if e != nil {
t.Fatal(e)
}
identity, _ := url.Parse("spiffe://messenger/" + role)
expiry := time.Now().Add(time.Minute)
if expired {
expiry = time.Now().Add(-time.Minute)
}
template := &x509.Certificate{SerialNumber: big.NewInt(time.Now().UnixNano()), Subject: pkix.Name{CommonName: role}, NotBefore: time.Now().Add(-time.Hour), NotAfter: expiry, URIs: []*url.URL{identity}, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, KeyUsage: x509.KeyUsageDigitalSignature}
der, e := x509.CreateCertificate(rand.Reader, template, ca.cert, &key.PublicKey, ca.key)
if e != nil {
t.Fatal(e)
}
cert, e := x509.ParseCertificate(der)
if e != nil {
t.Fatal(e)
}
return cert
}
func TestClientAuthorizationUsesCurrentChainIdentityExpiryAndRevocation(t *testing.T) {
ca := root(t)
foreign := root(t)
directory := t.TempDir()
conf := Config{Trust: filepath.Join(directory, "ca.pem"), Revoked: filepath.Join(directory, "revoked.json")}
if e := os.WriteFile(conf.Trust, ca.pem, 0600); e != nil {
t.Fatal(e)
}
if e := os.WriteFile(conf.Revoked, []byte(`{}`), 0600); e != nil {
t.Fatal(e)
}
boundary := Boundary{Allow: map[string][]string{"spiffe://messenger/lb": {"* /"}}}
good := client(t, ca, "lb", false)
state := func(leaf *x509.Certificate, issuer authority) tls.ConnectionState {
return tls.ConnectionState{PeerCertificates: []*x509.Certificate{leaf, issuer.cert}, VerifiedChains: [][]*x509.Certificate{{leaf, issuer.cert}}}
}
cases := []struct {
name string
state tls.ConnectionState
allowed bool
}{
{"authorized", state(good, ca), true},
{"no_certificate", tls.ConnectionState{}, false},
{"trusted_but_wrong_role", state(client(t, ca, "worker", false), ca), false},
{"foreign_authority", state(client(t, foreign, "lb", false), foreign), false},
{"expired", state(client(t, ca, "lb", true), ca), false},
}
for _, test := range cases {
t.Run(test.name, func(t *testing.T) {
_, e := peer(conf, test.state, boundary)
if (e == nil) != test.allowed {
t.Fatalf("authorization mismatch: allowed=%v error=%v", test.allowed, e)
}
})
}
raw, _ := json.Marshal(map[string]bool{good.SerialNumber.Text(16): true})
if e := os.WriteFile(conf.Revoked, raw, 0600); e != nil {
t.Fatal(e)
}
if _, e := peer(conf, state(good, ca), boundary); e == nil {
t.Fatal("revoked client accepted on previously authenticated connection")
}
if e := os.WriteFile(conf.Revoked, []byte(`{}`), 0600); e != nil {
t.Fatal(e)
}
if e := os.WriteFile(conf.Trust, foreign.pem, 0600); e != nil {
t.Fatal(e)
}
if _, e := peer(conf, state(good, ca), boundary); e == nil {
t.Fatal("retired authority accepted from cached verified chain")
}
if e := os.Remove(conf.Revoked); e != nil {
t.Fatal(e)
}
if _, e := peer(conf, state(good, ca), boundary); e == nil {
t.Fatal("missing revocation policy did not fail closed")
}
}
+42
View File
@@ -0,0 +1,42 @@
{
"role": "grafana",
"dns": [
"grafana",
"localhost"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": true,
"servers": [
{
"listen": "0.0.0.0:3443",
"target": "127.0.0.1:3000",
"protocol": "http",
"allow": {},
"public": true
}
],
"outbounds": [
{
"listen": "127.0.0.1:13909",
"target": "https://prometheus:9900",
"server_identity": "spiffe://messenger/prometheus"
},
{
"listen": "127.0.0.1:13310",
"target": "https://loki:3310",
"server_identity": "spiffe://messenger/loki"
},
{
"listen": "127.0.0.1:13320",
"target": "https://tempo:3320",
"server_identity": "spiffe://messenger/tempo"
}
],
"ip": [
"127.0.0.1"
]
}
+33
View File
@@ -0,0 +1,33 @@
{
"role": "lb",
"dns": [
"lb",
"localhost"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": true,
"servers": [
{
"listen": "0.0.0.0:18404",
"target": "127.0.0.1:8404",
"protocol": "http",
"allow": {
"spiffe://messenger/prometheus": [
"GET /metrics"
],
"spiffe://messenger/operator": [
"GET /metrics"
]
},
"public": false
}
],
"outbounds": [],
"ip": [
"127.0.0.1"
]
}
+36
View File
@@ -0,0 +1,36 @@
{
"role": "loki",
"dns": [
"loki"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": true,
"servers": [
{
"listen": "0.0.0.0:3310",
"target": "127.0.0.1:3100",
"protocol": "http",
"allow": {
"spiffe://messenger/grafana": [
"GET /",
"POST /api/"
],
"spiffe://messenger/prometheus": [
"GET /metrics"
],
"spiffe://messenger/operator": [
"GET /"
],
"spiffe://messenger/otel": [
"POST /otlp/"
]
},
"public": false
}
],
"outbounds": []
}
+14
View File
@@ -0,0 +1,14 @@
{
"role": "migrate",
"dns": [
"migrate"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": true,
"servers": [],
"outbounds": []
}
+20
View File
@@ -0,0 +1,20 @@
{
"role": "observer",
"dns": [
"observer"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": true,
"servers": [],
"outbounds": [
{
"listen": "127.0.0.1:14318",
"target": "https://otel:4438",
"server_identity": "spiffe://messenger/otel"
}
]
}
+88
View File
@@ -0,0 +1,88 @@
{
"role": "otel",
"dns": [
"otel"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": true,
"servers": [
{
"listen": "0.0.0.0:4438",
"target": "127.0.0.1:4318",
"protocol": "http",
"allow": {
"spiffe://messenger/api": [
"POST /v1/"
],
"spiffe://messenger/worker": [
"POST /v1/"
],
"spiffe://messenger/relay": [
"POST /v1/"
],
"spiffe://messenger/observer": [
"POST /v1/"
],
"spiffe://messenger/operator": [
"POST /v1/"
]
},
"public": false
},
{
"listen": "0.0.0.0:18889",
"target": "127.0.0.1:8889",
"protocol": "http",
"allow": {
"spiffe://messenger/prometheus": [
"GET /metrics"
],
"spiffe://messenger/operator": [
"GET /metrics"
]
},
"public": false
},
{
"listen": "0.0.0.0:18888",
"target": "127.0.0.1:8888",
"protocol": "http",
"allow": {
"spiffe://messenger/prometheus": [
"GET /metrics"
],
"spiffe://messenger/operator": [
"GET /metrics"
]
},
"public": false
},
{
"listen": "0.0.0.0:13333",
"target": "127.0.0.1:13133",
"protocol": "http",
"allow": {
"spiffe://messenger/operator": [
"GET /"
]
},
"public": false
}
],
"outbounds": [
{
"listen": "127.0.0.1:13310",
"target": "https://loki:3310",
"server_identity": "spiffe://messenger/loki"
},
{
"listen": "127.0.0.1:14319",
"target": "https://tempo:4438",
"server_identity": "spiffe://messenger/tempo"
}
]
}
+29
View File
@@ -0,0 +1,29 @@
{
"role": "postgres",
"dns": [
"postgres"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": true,
"servers": [
{
"listen": "0.0.0.0:5443",
"target": "127.0.0.1:5432",
"protocol": "postgres",
"allow": {
"spiffe://messenger/api": [],
"spiffe://messenger/worker": [],
"spiffe://messenger/relay": [],
"spiffe://messenger/observer": [],
"spiffe://messenger/reconciler": [],
"spiffe://messenger/migrate": [],
"spiffe://messenger/operator": []
}
}
],
"outbounds": []
}
+56
View File
@@ -0,0 +1,56 @@
{
"role": "prometheus",
"dns": [
"prometheus"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": true,
"servers": [
{
"listen": "0.0.0.0:9900",
"target": "127.0.0.1:9090",
"protocol": "http",
"allow": {
"spiffe://messenger/grafana": [
"GET /api/",
"POST /api/v1/query"
],
"spiffe://messenger/operator": [
"GET /"
]
},
"public": false
}
],
"outbounds": [
{
"listen": "127.0.0.1:18889",
"target": "https://otel:18889",
"server_identity": "spiffe://messenger/otel"
},
{
"listen": "127.0.0.1:18888",
"target": "https://otel:18888",
"server_identity": "spiffe://messenger/otel"
},
{
"listen": "127.0.0.1:18404",
"target": "https://lb:18404",
"server_identity": "spiffe://messenger/lb"
},
{
"listen": "127.0.0.1:13200",
"target": "https://tempo:3320",
"server_identity": "spiffe://messenger/tempo"
},
{
"listen": "127.0.0.1:13100",
"target": "https://loki:3310",
"server_identity": "spiffe://messenger/loki"
}
]
}
+14
View File
@@ -0,0 +1,14 @@
{
"role": "reconciler",
"dns": [
"reconciler"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": true,
"servers": [],
"outbounds": []
}
+20
View File
@@ -0,0 +1,20 @@
{
"role": "relay",
"dns": [
"relay"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": true,
"servers": [],
"outbounds": [
{
"listen": "127.0.0.1:14318",
"target": "https://otel:4438",
"server_identity": "spiffe://messenger/otel"
}
]
}
+39
View File
@@ -0,0 +1,39 @@
{
"role": "s3",
"dns": [
"s3",
"localhost"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": true,
"servers": [
{
"listen": "0.0.0.0:9443",
"target": "127.0.0.1:9000",
"protocol": "http",
"allow": {
"spiffe://messenger/api": [
"* /"
],
"spiffe://messenger/worker": [
"* /"
],
"spiffe://messenger/reconciler": [
"* /"
],
"spiffe://messenger/operator": [
"* /"
]
},
"public": false
}
],
"outbounds": [],
"ip": [
"127.0.0.1"
]
}
+47
View File
@@ -0,0 +1,47 @@
{
"role": "tempo",
"dns": [
"tempo"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": true,
"servers": [
{
"listen": "0.0.0.0:3320",
"target": "127.0.0.1:3200",
"protocol": "http",
"allow": {
"spiffe://messenger/grafana": [
"GET /",
"POST /api/"
],
"spiffe://messenger/prometheus": [
"GET /metrics"
],
"spiffe://messenger/operator": [
"GET /"
]
},
"public": false
},
{
"listen": "0.0.0.0:4438",
"target": "127.0.0.1:4318",
"protocol": "http",
"allow": {
"spiffe://messenger/otel": [
"POST /v1/traces"
],
"spiffe://messenger/operator": [
"POST /v1/traces"
]
},
"public": false
}
],
"outbounds": []
}
+20
View File
@@ -0,0 +1,20 @@
{
"role": "worker",
"dns": [
"worker"
],
"bao": "https://openbao:8200",
"trust": "/trust/ca.pem",
"revoked": "/trust/revoked.json",
"identity": "/run/identity",
"ttl": "120s",
"serve_only": true,
"servers": [],
"outbounds": [
{
"listen": "127.0.0.1:14318",
"target": "https://otel:4438",
"server_identity": "spiffe://messenger/otel"
}
]
}