forked from mtusi2026/mtusi2026lab7
109 lines
6.7 KiB
INI
109 lines
6.7 KiB
INI
# HAProxy 2.8 LTS — единственная публичная точка входа (lab3), lab7: TLS снаружи, mTLS внутрь.
|
||
#
|
||
# клиент --TLS 1.2+ (сертификат lb-public, SAN localhost/127.0.0.1)--> :8443 frontend public
|
||
# LB --mTLS (клиентский cert lb-client, CN/SAN lb; проверка сервера: CA + SAN api)--> api:8443
|
||
#
|
||
# Проверка сервера API: `verify required ca-file` + `verifyhost api` (SAN DNS:api) — LB не
|
||
# отправит запрос «реплике», чей сертификат не выдан нашим CA на имя api.
|
||
# Проверка клиента делает API (src/tls.py): только identity `lb`, CRL. `no-ssl-reuse`:
|
||
# каждое новое соединение — полное рукопожатие, поэтому отзыв/ротация сертификата LB
|
||
# не маскируется TLS session resumption.
|
||
#
|
||
# Обнаружение реплик (как в lab3): Docker DNS, server-template до 6 слотов, проверка
|
||
# GET /health/ready по mTLS каждую 1 с; fall 2 / rise 2. Повторяются только ошибки
|
||
# установления соединения (retry-on conn-failure по умолчанию) — для POST безопасно.
|
||
#
|
||
# Лимиты (lab7): размер тела не-upload запросов — по Content-Length до реплики (64 KiB);
|
||
# загрузка (10 MiB) — в API; заголовки — tune.bufsize; медленный клиент — timeout http-request.
|
||
# Ответы, которые формирует сам LB, — в JSON-формате ошибок контракта с X-Request-Id.
|
||
|
||
global
|
||
log stdout format raw local0 info
|
||
maxconn 2000
|
||
# Внешний и внутренний TLS: не ниже 1.2, без TLS tickets (ключ тикета = общий секрет LB).
|
||
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
|
||
ssl-default-server-options ssl-min-ver TLSv1.2 no-tls-tickets
|
||
tune.bufsize 32768
|
||
|
||
resolvers docker
|
||
nameserver dns1 127.0.0.11:53
|
||
resolve_retries 3
|
||
timeout resolve 1s
|
||
timeout retry 1s
|
||
hold valid 2s
|
||
hold obsolete 2s
|
||
hold nx 2s
|
||
hold other 2s
|
||
hold refused 2s
|
||
hold timeout 2s
|
||
accepted_payload_size 8192
|
||
|
||
defaults
|
||
mode http
|
||
log global
|
||
option httplog
|
||
option dontlognull
|
||
option redispatch 1
|
||
retries 2
|
||
timeout connect 1s
|
||
timeout client 30s
|
||
timeout server 10s
|
||
timeout http-request 10s
|
||
timeout http-keep-alive 10s
|
||
timeout queue 3s
|
||
timeout check 1500ms
|
||
default-server inter 1s fastinter 500ms downinter 2s fall 2 rise 2
|
||
|
||
frontend public
|
||
bind :8443 ssl crt /run/secrets/lb_public_pem alpn http/1.1
|
||
# Сквозной идентификатор запроса (как в lab3).
|
||
unique-id-format %{+X}o\ %ci%cp-%fp-%Ts%ms-%rt-%pid
|
||
http-request set-header X-Request-Id %[unique-id] unless { req.hdr(X-Request-Id) -m found }
|
||
# X-Forwarded-For от клиента не доверяем: удаляем и ставим адрес TCP-клиента.
|
||
# API использует его для rate limit входа только потому, что к API подключается лишь LB (mTLS).
|
||
http-request del-header X-Forwarded-For
|
||
option forwardfor
|
||
# Внешний клиент не управляет trace-контекстом (подмена trace_id, ReDoS-парсеры заголовков).
|
||
http-request del-header traceparent
|
||
http-request del-header tracestate
|
||
http-request del-header baggage
|
||
# Транспорт без шифрования не принимается вовсе (порт только TLS), HSTS для браузеров.
|
||
http-response set-header Strict-Transport-Security "max-age=31536000"
|
||
# Внимание: одноимённые acl в HAProxy объединяются по ИЛИ — поэтому отдельные имена.
|
||
acl upload_path path_reg ^/api/v1/chats/[^/]+/attachments$
|
||
# Не-upload запросы: тело > 64 KiB по Content-Length отклоняется до реплики.
|
||
# Загрузки (<= 10 MiB) проверяет API: он дочитывает/сбрасывает тело и отвечает 413
|
||
# корректно (ранний ответ LB клиент, ещё пишущий 10 MiB, получил бы broken pipe).
|
||
acl body_large req.hdr_val(content-length) gt 65536
|
||
http-request return status 413 content-type application/json hdr X-Request-Id "%[req.hdr(X-Request-Id)]" lf-string "{\"error\":{\"code\":\"payload_too_large\",\"message\":\"Request body is too large\",\"request_id\":\"%[req.hdr(X-Request-Id)]\"}}" if body_large !upload_path
|
||
log-format "%ci:%cp [%tr] %ft %b/%s %TR/%Tw/%Tc/%Tr/%Ta %ST %B %tsc %ac/%fc/%bc/%sc/%rc %sq/%bq tls=%sslv rid=%[capture.req.hdr(0)] inst=%[capture.res.hdr(0)] \"%HM %HPO\""
|
||
http-request capture req.hdr(X-Request-Id) len 64
|
||
declare capture response len 32
|
||
http-response capture res.hdr(X-Instance-Id) id 0
|
||
default_backend api
|
||
|
||
backend api
|
||
balance roundrobin
|
||
acl is_upload method POST
|
||
acl is_upload_path path_reg ^/api/v1/chats/[^/]+/attachments$
|
||
http-request set-timeout server 90s if is_upload is_upload_path
|
||
option httpchk
|
||
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host api
|
||
http-check expect status 200
|
||
http-error status 503 content-type application/json hdr X-Request-Id "%[req.hdr(X-Request-Id)]" lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"No API instance is available\",\"request_id\":\"%[req.hdr(X-Request-Id)]\"}}"
|
||
http-error status 504 content-type application/json hdr X-Request-Id "%[req.hdr(X-Request-Id)]" lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"API instance timeout\",\"request_id\":\"%[req.hdr(X-Request-Id)]\"}}"
|
||
http-error status 502 content-type application/json hdr X-Request-Id "%[req.hdr(X-Request-Id)]" lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"Bad gateway\",\"request_id\":\"%[req.hdr(X-Request-Id)]\"}}"
|
||
# mTLS к каждой реплике; проверки (check) идут тем же mTLS.
|
||
server-template api 1-6 api:8443 check resolvers docker init-addr none resolve-prefer ipv4 ssl verify required ca-file /run/secrets/ca_crt crt /run/secrets/lb_client_pem verifyhost api sni str(api) no-ssl-reuse
|
||
|
||
# Состояние реплик (UP/DOWN) — только внутри контейнера (127.0.0.1), порт НЕ публикуется.
|
||
# scripts/ops.py читает его через `docker compose exec lb wget ...`.
|
||
frontend stats
|
||
bind 127.0.0.1:8404
|
||
monitor-uri /lb-health
|
||
stats enable
|
||
stats uri /stats
|
||
stats refresh 2s
|
||
stats show-legends
|
||
http-request set-log-level silent
|