7 — Т2302 — ебедев — на 5

This commit is contained in:
2026-11-22 23:26:17 +03:00
parent 20afc2c790
commit d15f2a3631
179 changed files with 21709 additions and 54 deletions
+137
View File
@@ -0,0 +1,137 @@
# HAProxy 3.0 — единственная публичная точка входа (lab7: только HTTPS).
# клиент ──TLS 1.2+ (сертификат ingress: SAN localhost/127.0.0.1)──▶ LB :8443
# LB ──mTLS (клиентский сертификат identity lb, проверка сервера: CA + SAN api + CRL)──▶ api:8443
# Реплики API принимают ТОЛЬКО mTLS с URI SAN spiffe://mtusi.lab/lb (см. src/messenger/tlsconf.py),
# поэтому обойти LB изнутри сети нельзя, а портов API на хосте нет.
#
# Обнаружение отказа реплики (lab3, без изменений): GET /health/ready по mTLS, inter 1s, fastinter 500ms,
# fall 2; retry-on conn-failure + redispatch только для не отправленных запросов.
# Ротация leaf без пересборки: новый сертификат в secrets/tls/{ingress,lb} → `kill -USR2` master-процесса
# (scripts/rotate-cert): seamless reload, новые соединения — с новым сертификатом; старый отзывается в CRL.
global
log stdout format raw local0 info
maxconn 4096
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
ssl-default-bind-ciphersuites TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256
ssl-default-bind-ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305
ssl-default-server-options ssl-min-ver TLSv1.2
tune.ssl.default-dh-param 2048
tune.bufsize 16384 # предел заголовков запроса ≈ 15 КиБ (больше → 400), см. «Ограничения»
stats socket /tmp/haproxy.sock mode 600 level admin # только внутри контейнера (оператор, rotate)
defaults
mode http
log global
option httplog
option dontlognull
timeout connect 300ms
timeout check 500ms # TLS-рукопожатие проверки + ответ /health/ready
timeout client 60s # загрузка до 10 МиБ медленным клиентом
timeout server 60s
timeout http-request 10s # весь заголовок запроса — не дольше 10 с (slowloris)
timeout http-keep-alive 10s
timeout queue "${LB_QUEUE_TIMEOUT}"
retries 2
option redispatch 1
retry-on conn-failure
unique-id-format %[uuid()]
default-server inter 1s fastinter 500ms downinter 2s fall 2 rise 2 init-addr none resolvers docker
http-error status 503 content-type application/json lf-string '{"error":{"code":"unavailable","message":"Нет доступных реплик API","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] hdr Retry-After 1
http-error status 502 content-type application/json lf-string '{"error":{"code":"unavailable","message":"Реплика API недоступна","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id]
http-error status 504 content-type application/json lf-string '{"error":{"code":"unavailable","message":"Таймаут реплики API","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id]
http-error status 400 content-type application/json lf-string '{"error":{"code":"invalid_request","message":"Некорректный запрос","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id]
http-error status 408 content-type application/json lf-string '{"error":{"code":"invalid_request","message":"Таймаут запроса","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id]
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 2s
hold obsolete 5s
accepted_payload_size 8192
# Грубый антифлуд на IP (общий для всех реплик, т.к. LB один); тонкие лимиты входа — в API (Redis).
backend st_ip
stick-table type ip size 100k expire 60s store http_req_rate(10s)
frontend api
bind :8443 ssl crt /run/tls/ingress/tls.pem alpn http/1.1
# Ограничения запроса до приложения: длина URI, число заголовков, тело (> лимита загрузки 10 МиБ).
http-request return status 414 content-type application/json lf-string '{"error":{"code":"invalid_request","message":"Слишком длинный URI","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] if { url_len gt 4096 }
http-request return status 400 content-type application/json lf-string '{"error":{"code":"invalid_request","message":"Слишком много заголовков","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] if { req.hdr_cnt gt 64 }
http-request return status 413 content-type application/json lf-string '{"error":{"code":"payload_too_large","message":"Слишком большой запрос","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] if { req.hdr_val(content-length) gt 10486784 }
http-request track-sc0 src table st_ip
http-request return status 429 content-type application/json lf-string '{"error":{"code":"rate_limited","message":"Слишком много запросов","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] hdr Retry-After 10 if { sc_http_req_rate(0) gt "${LB_IP_RATE_LIMIT}" }
# Внутренняя диагностика реплик снаружи недоступна.
http-request return status 404 content-type application/json lf-string '{"error":{"code":"not_found","message":"Объект не найден","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] if { path_beg /internal }
# IP клиента для лимитов API: заголовок ПЕРЕЗАПИСЫВАЕТСЯ (клиентское значение не проходит).
http-request set-header X-Forwarded-For %[src]
http-request set-header X-Forwarded-Proto https
http-request del-header X-User-Id
http-response set-header Strict-Transport-Security "max-age=31536000"
http-response set-header X-Content-Type-Options nosniff
# Дорогие по CPU (Argon2id) запросы — в ОТДЕЛЬНЫЙ backend со своим пределом слотов на реплику:
# поток попыток входа/регистрации не занимает слоты LB_SERVER_MAXCONN остальных запросов (research/login_dos.py).
use_backend api_login if METH_POST { path /api/v1/auth/sessions /api/v1/users }
default_backend api
frontend api_ttl
bind :8444 ssl crt /run/tls/ingress/tls.pem alpn http/1.1
http-request return status 404 content-type application/json lf-string '{"error":{"code":"not_found","message":"Объект не найден","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] if { path_beg /internal }
http-request set-header X-Forwarded-For %[src]
default_backend api_ttl
frontend api_fault
bind :8445 ssl crt /run/tls/ingress/tls.pem alpn http/1.1
http-request return status 404 content-type application/json lf-string '{"error":{"code":"not_found","message":"Объект не найден","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] if { path_beg /internal }
http-request set-header X-Forwarded-For %[src]
default_backend api_fault
frontend stats
bind 127.0.0.1:8404 # только loopback контейнера (healthcheck); на хост не публикуется
stats enable
stats uri /stats
stats refresh 2s
backend api
balance roundrobin
option httpchk
http-check send meth GET uri /health/ready
http-check expect status 200
http-reuse safe
# mTLS к реплике: проверяем её сертификат (CA, SAN = api, CRL) и предъявляем identity lb.
default-server ssl verify required ca-file /run/tls/trust/ca.crt crl-file /run/tls/trust/crl.pem verifyhost api sni str(api) crt /run/tls/lb/tls.pem alpn http/1.1 check-sni api check-alpn http/1.1
server-template api 8 api:8443 check maxconn "${LB_SERVER_MAXCONN}"
option allbackups
server-template apibk 8 api:8443 backup resolve-opts allow-dup-ip
backend api_login
balance roundrobin
option httpchk
http-check send meth GET uri /health/ready
http-check expect status 200
timeout queue 1s # дольше не ждём: клиенту 503 + Retry-After, а не растущая очередь
default-server ssl verify required ca-file /run/tls/trust/ca.crt crl-file /run/tls/trust/crl.pem verifyhost api sni str(api) crt /run/tls/lb/tls.pem alpn http/1.1 check-sni api check-alpn http/1.1
server-template login 8 api:8443 check maxconn "${LB_LOGIN_MAXCONN}"
option allbackups
server-template loginbk 8 api:8443 backup resolve-opts allow-dup-ip
backend api_ttl
balance roundrobin
option httpchk
http-check send meth GET uri /health/ready
http-check expect status 200
default-server ssl verify required ca-file /run/tls/trust/ca.crt crl-file /run/tls/trust/crl.pem verifyhost api-ttl sni str(api-ttl) crt /run/tls/lb/tls.pem alpn http/1.1 check-sni api-ttl check-alpn http/1.1
server-template ttl 2 api-ttl:8443 check
option allbackups
server-template ttlbk 2 api-ttl:8443 backup resolve-opts allow-dup-ip
backend api_fault
balance roundrobin
option httpchk
http-check send meth GET uri /health/ready
http-check expect status 200
default-server ssl verify required ca-file /run/tls/trust/ca.crt crl-file /run/tls/trust/crl.pem verifyhost api-fault sni str(api-fault) crt /run/tls/lb/tls.pem alpn http/1.1 check-sni api-fault check-alpn http/1.1
server-template fault 1 api-fault:8443 check