feat(deploy): restrict the public perimeter and resolve the client address
This commit is contained in:
1 parent
e52ffe7bcb
commit
57174dffba
25 files changed
+1224
-25
No files matched your search
@@ -52,6 +52,12 @@ SeaweedFS runs as a separate server in the core Compose project. `backend/intern
|
||||
|
||||
The MVP does not add a separate vector database, Kubernetes, or a search microservice. Apache Kafka in KRaft mode with a transactional outbox is the selected event broker; the core Compose project runs one internal Kafka node, the `outbox_events` table has its transactional writer, and the [outbox relay](#outbox-relay) publishes committed events to Kafka. The [event consumer](#event-consumers) runtime applies events idempotently; one product consumer is registered, `notification_delivery` for mail deliveries. Redis is not used as a queue. Initial search uses PostgreSQL filters and full-text search over an allowed projection. Consider pgvector only if evaluation shows embeddings help.
|
||||
|
||||
### HTTP perimeter and client address
|
||||
|
||||
Implemented (TASK-042). The frontend Nginx is the only public HTTP entry. It serves the SPA, proxies `/api/v1/` to Go, and proxies the restricted `/telemetry`; every other path, including `/metrics`, `/readyz`, and administration paths of other services, is refused with 404. Security headers, a strict same-origin CSP, a 1 MB default body limit that answers 413 in the contract's problem format, and coarse per-client `limit_req`/`limit_conn` (429 with `Retry-After`) are set there; the limits are far above normal use and do not replace the domain quotas, which stay in the backend. The details and the checks are in [DEPLOY.md](DEPLOY.md#public-perimeter-and-client-address).
|
||||
|
||||
The client address is derived only through trusted proxies. The edge replaces `X-Forwarded-For`; the app Nginx trusts the edge tunnel address and passes the backend one resolved entry; `middleware.ClientIP` (`backend/internal/adapter/primary/http/middleware/clientip.go`) trusts `X-Forwarded-For` only from `TRUSTED_PROXY_CIDRS` (by default only the pinned frontend container address) and reads it from the right, so an entry a client puts to the left of the first untrusted hop never counts. Usecases and handlers that need the address for a limiter read it with `middleware.ClientAddr(ctx)` and key the limiter with `middleware.LimiterKey` (IPv6 reduced to /64). The address is never logged or stored beyond the limiter window; the request log and metrics have no field for it. The first consumer is the registration and resend limits (see Registration and verification resend); the router mounts `ClientIP`.
|
||||
|
||||
### Private file storage
|
||||
|
||||
`backend/internal/usecase/files/` is the shared private file layer over the `ObjectStorage` port. It holds technical rules only. A feature package (resume upload, import, PDF generation, document jobs, exports) defines a `Policy` with a namespace, a size limit in bytes, and exact media types, and owns every product rule: who may read or delete a file, page counts, content inspection, parsing, and retention. The layer is not wired into bootstrap until the first such feature uses it. Namespaces are declared in one place, `namespace.go`, and `NewPolicy` accepts no other value, so two features cannot share a namespace by accident.
|
||||
|
||||
+17
-4
@@ -19,7 +19,7 @@ The backend build context is `backend/`, so Docker applies `backend/.dockerignor
|
||||
|
||||
The current `postgres:alpine` volume mounts at `/var/lib/postgresql`; the image stores data in a subdirectory for its major version. When the tag advances to a new major version, migrate an existing database with `pg_upgrade` or backup/restore. Updating the image alone does not convert the data.
|
||||
|
||||
Open http://127.0.0.1:8080. The host port binds to loopback. Nginx handles /healthz, proxies /api/ to Go, and uses the SPA fallback for other paths. The public API health route is /api/v1/healthz through Nginx /api/. On the internal port 8080, Go also serves /healthz for the process and /readyz, which checks PostgreSQL with SELECT 1, Redis with PING, and the SeaweedFS bucket with HeadBucket; any dependency being unavailable produces 503. The internal backend port 9090 serves /metrics.
|
||||
Open http://127.0.0.1:8080. The host port binds to loopback. Nginx handles /healthz, proxies /api/v1/ to Go, and uses the SPA fallback for other paths; see [Public perimeter and client address](#public-perimeter-and-client-address). The public API health route is /api/v1/healthz through Nginx /api/v1/. On the internal port 8080, Go also serves /healthz for the process and /readyz, which checks PostgreSQL with SELECT 1, Redis with PING, and the SeaweedFS bucket with HeadBucket; any dependency being unavailable produces 503. The internal backend port 9090 serves /metrics.
|
||||
|
||||
This Nginx configuration has no production TLS. The current bind does not expose the app directly to the public network. Remote access needs a selected TLS reverse proxy, firewall rules, and environment-specific configuration.
|
||||
|
||||
@@ -74,6 +74,19 @@ The backend receives `KAFKA_BROKERS`, a comma-separated list of `host:port` boot
|
||||
|
||||
down stops containers and keeps named volumes. Do not delete database or file volumes during an ordinary stop.
|
||||
|
||||
### Public perimeter and client address
|
||||
|
||||
Only three things are reachable through the frontend container: the SPA (static files and the `index.html` fallback, so a refresh of a deep link works), the versioned API under `/api/v1/`, and the same-origin `/telemetry` receiver (POST only, 1 MB, 30 requests per minute per client; the React SDK does not send to it yet). Everything else is refused: `/metrics`, `/readyz`, `/debug/`, `/actuator/`, dotfiles, `/api`, `/api/v1`, and any other path under `/api/` answer 404 and are never proxied. Backend `/metrics` listens on port 9090, which no Nginx location reaches. The only host port of the core project is the frontend bind (`APP_HTTP_BIND`, loopback by default); PostgreSQL, Redis, Kafka, SeaweedFS, and the backend publish nothing. Grafana and ML publish on loopback only (the monitoring and ML projects).
|
||||
|
||||
- Headers (`deploy/nginx/snippets/security-headers.conf`): `Content-Security-Policy` with `default-src 'none'`, same-origin scripts, styles, fonts, images, and `connect-src`, no inline code, `frame-ancestors 'none'`, `base-uri 'none'`, `object-src 'none'`; `X-Content-Type-Options: nosniff`; `Referrer-Policy: strict-origin-when-cross-origin`; `X-Frame-Options: DENY`; `Cross-Origin-Opener-Policy` and `Cross-Origin-Resource-Policy` `same-origin`; `Permissions-Policy` denying camera, microphone, geolocation, payment, and USB. `index.html` and the deep-link fallback carry `Cache-Control: no-cache`, so a release is picked up at once; `/assets/` (hashed names) carries `public, max-age=31536000, immutable`, and a missing asset is a 404, never the fallback page. Redirects are relative (`absolute_redirect off`, `port_in_redirect off`), so a forged `Host` cannot steer them. If the SPA later needs an external host (analytics, fonts, a map), add that host to the matching CSP directive in the same change. No CORS header is sent: the API is same-origin and a browser refuses cross-origin reads; the backend still checks `Origin` on unsafe methods.
|
||||
- Body limits: `client_max_body_size` is 1 MB for `/api/v1/` (the contract's JSON bodies are small). The contract has no upload operation yet, so there is no 5 MB resume route; the change that adds it raises the limit in that route's own `location` in `deploy/nginx/conf.d/app.conf` and keeps `EDGE_MAX_BODY` at or above it. A larger body gets 413 with an `application/problem+json` body (`payload_too_large`, with `trace_id` equal to the `X-Request-ID` response header) from Nginx, in the same shape as the backend's own 413.
|
||||
- Timeouts: edge read 60 s, then app Nginx read 30 s, then the backend (storage and mail calls time out after 10 s, `Redis` after 1 s, the header read after 5 s). Each outer hop waits longer than the inner one, so the backend answers first.
|
||||
- Coarse rate limits in the app Nginx: 20 requests per second per client with a burst of 60 and 40 concurrent connections on `/api/v1/`. They exist to absorb floods and are far above normal use. They do not replace the domain quotas (per-account, per-route, per-email limits), which the backend owns and which keep counting on their own. The limiter key is the client address, with an IPv6 address folded to its /64 (as `middleware.LimiterKey` does). A limited request gets 429 with `Retry-After: 1` and the contract's `rate_limited` problem (with `trace_id`). Rejections are logged at `notice`, below the `warn` threshold of the Nginx error log, because a rejection line names the client address.
|
||||
- Client address chain: the edge replaces `X-Forwarded-For` with the connecting address; the frontend container trusts only the edge tunnel address (`set_real_ip_from`, equal to `AWG_EDGE_IP`) and takes the client from the right end of the header, so a value put in front by the client is never reached. For a peer that is not the edge it ignores the header altogether. `X-Forwarded-Proto: https` is likewise believed only from that peer. It then sends the backend a single `X-Forwarded-For` entry, the resolved client, replacing the header, and drops `Forwarded`. The core Docker network has a pinned subnet (`APP_SUBNET`, default `172.29.79.0/24`) and the frontend container a fixed address on it (`APP_FRONTEND_IP`, default `172.29.79.10`; change both together if the range collides, and recreate an existing network with `make -C deploy down` and `up`). The backend trusts `X-Forwarded-For` only from `TRUSTED_PROXY_CIDRS`, which defaults to that one address as a /32, so no other container of the network (Prometheus, exporters, Alloy) is trusted; leave the variable unset, and an empty value trusts nobody. The throwaway smoke, e2e, and metrics-check stacks use their own subnets (172.29.81 to 83) so they can run next to a development stack. The backend walks the header from the right, skipping trusted proxies; the first untrusted entry is the client. If the edge reaches the container under another address than `AWG_EDGE_IP`, the header is ignored and clients share one limiter bucket (fail closed); see the rollout checklist below.
|
||||
- The client address is used only to key limiters, in Nginx shared memory and in the backend's limiter keys (`middleware.LimiterKey`, IPv6 reduced to /64, expiring with the window). It is not logged and not stored. The app Nginx log format and the backend request log have no address field; the edge access log records `$remote_addr`, as before, and is rotated by logrotate.
|
||||
|
||||
Check it with `make -C deploy check-perimeter` (renders the Compose files and asserts the published ports; reads the Nginx files for denied paths, limit order, headers, and the trusted peer; runs inside `make -C deploy check`) and `make -C deploy perimeter-test` (starts throwaway Nginx containers on a private Docker network with stub upstreams, publishes on 127.0.0.1 only, and checks over HTTP: SPA refresh, denied paths, headers, no CORS, 413 and 429 problems, spoofed `X-Forwarded-For` from an untrusted and from a trusted peer, and that the Nginx log has no client address). It also checks the cache and cross-origin headers, relative redirects, encoded and dot-segment variants of denied paths, and per-/64 IPv6 buckets. It runs `nginx -t` on the committed files unchanged. It does not start the Compose stack, so it does not exercise the real backend or the TLS edge. Rollout checklist for the first deployment behind the edge (not done yet; the tests above cannot prove it): (1) from two external client addresses, request `/api/v1/healthz` in a loop until one gets 429 and confirm the other still gets 200, which shows that the app Nginx sees the edge as `10.79.0.1` and resolves real clients; if both are limited together, the peer address differs from `AWG_EDGE_IP` and the header is being ignored; (2) confirm `X-Forwarded-Proto: https` reaches the backend (the session cookie carries `Secure`); (3) confirm `curl http://<app-host-tunnel-ip>:8080/metrics` answers 404. Manual browser step on a running stack: open a deep link and refresh it (the SPA loads), open the developer tools and confirm the response headers and no CSP violations in the console, and send a file larger than the limit with `curl -i -X POST --data-binary @big.bin -H 'Content-Type: application/octet-stream' http://127.0.0.1:8080/api/v1/<operation>` to see 413.
|
||||
|
||||
### Outbox relay
|
||||
|
||||
The backend runs the outbox relay in its own process next to the HTTP servers. The relay publishes committed outbox events to Kafka; its design is in [ARCHITECTURE.md](ARCHITECTURE.md#outbox-relay). Compose passes none of the settings below, so the stack uses the defaults; to change one, add it to the backend `environment` in `deploy/docker/docker-compose.yml`. A directly launched backend reads them from its environment. An invalid value stops startup.
|
||||
@@ -371,8 +384,8 @@ Registration and login are not implemented yet (the operations answer 501), and
|
||||
- Port 443 allows TLS 1.2 and 1.3 with the Mozilla intermediate cipher list, HTTP/2, no session tickets, and `Strict-Transport-Security: max-age=<EDGE_HSTS_MAX_AGE>; includeSubDomains` without `preload`. The default max-age is 180 days; raise it to a year and consider preload only after the site has stayed on HTTPS. The upstream security headers (`X-Content-Type-Options`, `Referrer-Policy`, `X-Frame-Options`, `Permissions-Policy`) pass through from the frontend container.
|
||||
- OCSP stapling is off on purpose: Let's Encrypt certificates no longer carry an OCSP responder URL, so there is nothing to staple. HTTP/3 is off because it would need UDP 443, which another service on the edge host owns.
|
||||
- Compression is off for `/api/` and limited to CSS, JavaScript, SVG, and the HTML shell elsewhere (no JSON). Compressing responses that mix secrets with attacker-influenced content enables BREACH; a CSRF token delivered in an API response must never be compressed. Revisit this if a secret is ever rendered into HTML.
|
||||
- `X-Forwarded-For` and `X-Real-IP` are replaced with the connecting address, not appended to client values, because the edge is the first trusted hop. The frontend container then appends the tunnel peer, so the backend reads the client address as the first `X-Forwarded-For` entry. The container's own `X-Real-IP` and the `/telemetry` rate limit see the tunnel peer or the Docker gateway address, so all clients share that bucket until the container trusts the edge for real client addresses.
|
||||
- `client_max_body_size` is `EDGE_MAX_BODY` (10 MB, equal to the container limit). The 5 MB resume limit is a per-feature policy checked by the backend. Timeouts: 5 s to connect, 60 s to send and read (the container gives Go 30 s), 60 s for a request body.
|
||||
- `X-Forwarded-For` and `X-Real-IP` are replaced with the connecting address, not appended to client values, because the edge is the first trusted hop. The frontend container trusts the tunnel address of the edge, resolves the client from that header, uses it for its coarse rate limits, and passes the backend a single replaced `X-Forwarded-For` entry (see [Public perimeter and client address](#public-perimeter-and-client-address)).
|
||||
- `client_max_body_size` is `EDGE_MAX_BODY` (10 MB, the ceiling; the container allows 1 MB by default and raises it per route, never above this value). The 5 MB resume limit is a per-feature policy checked by the backend. Timeouts: 5 s to connect, 60 s to send and read (the container gives Go 30 s), 60 s for a request body.
|
||||
- The access log (`/var/log/nginx/lincodex.access.log`, rotated by the package logrotate rule) records the path without the query string, so values such as addresses in a query do not reach the log.
|
||||
|
||||
### Rollout on the edge host
|
||||
@@ -495,7 +508,7 @@ When the local resolver does not return the public address, add `--resolve <doma
|
||||
|
||||
### Limits
|
||||
|
||||
This is one edge host and one app host. There is no failover, no external uptime check, and no rate limiting at the edge (the backend rate limits are separate and not implemented yet). The certificate covers only the one name, the site is IPv4 only, and the ACME account has no contact address. The tunnel carries no authentication beyond the AmneziaWG keys, and the obfuscation parameters raise the cost of blocking but are not a security control.
|
||||
This is one edge host and one app host. There is no failover, no external uptime check, and no rate limiting at the edge (the frontend container applies coarse per-client limits, and the backend domain quotas are separate and not implemented yet). The certificate covers only the one name, the site is IPv4 only, and the ACME account has no contact address. The tunnel carries no authentication beyond the AmneziaWG keys, and the obfuscation parameters raise the cost of blocking but are not a security control.
|
||||
|
||||
## Services and images
|
||||
|
||||
|
||||
@@ -52,6 +52,12 @@ SeaweedFS работает отдельным сервером в основно
|
||||
|
||||
Для MVP не вводятся отдельная vector DB, Kubernetes или микросервисы поиска. Брокером событий выбран Apache Kafka в режиме KRaft с transactional outbox; core Compose проект запускает один внутренний узел Kafka, у таблицы `outbox_events` есть транзакционная запись, а [relay outbox](#relay-outbox) публикует зафиксированные события в Kafka. Runtime [обработчиков событий](#обработчики-событий) применяет события идемпотентно; зарегистрирован один продуктовый обработчик - `notification_delivery` для доставок писем. Redis не используется как очередь. Начальный поиск использует PostgreSQL фильтры/full-text по разрешенной проекции. pgvector можно рассмотреть после eval, если embeddings дают подтвержденную пользу.
|
||||
|
||||
### HTTP-периметр и адрес клиента
|
||||
|
||||
Реализовано (TASK-042). Frontend Nginx - единственная публичная HTTP-точка входа. Он отдает SPA, проксирует `/api/v1/` в Go и ограниченный `/telemetry`; любой другой путь, включая `/metrics`, `/readyz` и административные пути других сервисов, отклоняется с 404. Там же заданы заголовки безопасности, строгий CSP только для того же origin, лимит тела по умолчанию 1 МБ с ответом 413 в формате problem из контракта и грубые `limit_req`/`limit_conn` на клиента (429 с `Retry-After`); значения намного выше обычного использования и не заменяют доменные квоты, которые остаются в backend. Подробности и проверки - в [DEPLOY.md](DEPLOY.md#публичный-периметр-и-адрес-клиента).
|
||||
|
||||
Адрес клиента определяется только через доверенные прокси. Edge заменяет `X-Forwarded-For`; app Nginx доверяет адресу туннеля edge и передает backend одну найденную запись; `middleware.ClientIP` (`backend/internal/adapter/primary/http/middleware/clientip.go`) доверяет `X-Forwarded-For` только от `TRUSTED_PROXY_CIDRS` (по умолчанию только закрепленный адрес frontend контейнера) и читает его справа, поэтому запись, которую клиент поставил слева от первого недоверенного узла, не учитывается. Сценарии и обработчики, которым нужен адрес для лимитера, читают его через `middleware.ClientAddr(ctx)` и строят ключ лимитера через `middleware.LimiterKey` (IPv6 сводится к /64). Адрес не логируется и не хранится дольше окна лимитера; в журнале запросов и метриках для него нет поля. Первый потребитель - лимиты регистрации и повторной отправки (см. раздел о регистрации); роутер подключает `ClientIP`.
|
||||
|
||||
### Закрытое файловое хранилище
|
||||
|
||||
`backend/internal/usecase/files/` - общий закрытый файловый слой поверх порта `ObjectStorage`. Он содержит только технические правила. Продуктовый пакет (загрузка резюме, импорт, генерация PDF, задания по документам, выгрузки) задает `Policy` с namespace, лимитом размера в байтах и точными media types и отвечает за все продуктовые правила: кто может читать или удалять файл, число страниц, проверку содержимого, разбор и сроки хранения. Слой не подключен в bootstrap, пока его не использует первый такой сценарий. Namespace объявляются в одном месте, `namespace.go`, и `NewPolicy` не принимает других значений, поэтому два сценария не могут случайно использовать один namespace.
|
||||
|
||||
+17
-4
@@ -21,7 +21,7 @@
|
||||
|
||||
Для текущего `postgres:alpine` volume монтируется в `/var/lib/postgresql`; образ размещает данные в подкаталоге своей major-версии. При переходе тега на новую major-версию существующую базу нужно мигрировать через `pg_upgrade` или backup/restore. Обновление образа само по себе не преобразует данные.
|
||||
|
||||
Откройте http://127.0.0.1:8080. Порт привязан к loopback. Nginx отвечает на /healthz, перенаправляет /api/ в Go и использует SPA fallback для остальных путей. Публичный health-маршрут API - /api/v1/healthz через Nginx /api/. На внутреннем порту 8080 Go также обслуживает /healthz для проверки процесса и /readyz, который проверяет PostgreSQL через SELECT 1, Redis через PING и bucket SeaweedFS через HeadBucket; недоступность любого из них дает 503. Служебный /metrics слушает на внутреннем порту backend 9090.
|
||||
Откройте http://127.0.0.1:8080. Порт привязан к loopback. Nginx отвечает на /healthz, перенаправляет /api/v1/ в Go и использует SPA fallback для остальных путей; см. [Публичный периметр и адрес клиента](#публичный-периметр-и-адрес-клиента). Публичный health-маршрут API - /api/v1/healthz через Nginx /api/v1/. На внутреннем порту 8080 Go также обслуживает /healthz для проверки процесса и /readyz, который проверяет PostgreSQL через SELECT 1, Redis через PING и bucket SeaweedFS через HeadBucket; недоступность любого из них дает 503. Служебный /metrics слушает на внутреннем порту backend 9090.
|
||||
|
||||
Этот Nginx конфиг не настраивает production TLS. Текущий bind не открывает приложение напрямую во внешнюю сеть. Для удаленного доступа требуется отдельно выбранный TLS reverse proxy, firewall и конфигурация целевого окружения.
|
||||
|
||||
@@ -76,6 +76,19 @@ Backend получает `KAFKA_BROKERS` - список адресов bootstrap
|
||||
|
||||
down останавливает контейнеры, сохраняя именованные volumes. Не удаляйте volume с базой или файлами в рамках обычного останова.
|
||||
|
||||
### Публичный периметр и адрес клиента
|
||||
|
||||
Через frontend контейнер доступны только три вещи: SPA (статические файлы и fallback на `index.html`, поэтому обновление страницы по глубокой ссылке работает), версионированный API под `/api/v1/` и same-origin приемник `/telemetry` (только POST, 1 МБ, 30 запросов в минуту на клиента; React SDK в него пока не отправляет). Остальное отклоняется: `/metrics`, `/readyz`, `/debug/`, `/actuator/`, dotfiles, `/api`, `/api/v1` и любой другой путь под `/api/` отвечают 404 и не проксируются. Backend `/metrics` слушает порт 9090, до которого не доходит ни один location Nginx. Единственный порт core проекта на хосте - привязка frontend (`APP_HTTP_BIND`, по умолчанию loopback); PostgreSQL, Redis, Kafka, SeaweedFS и backend ничего не публикуют. Grafana и ML публикуются только на loopback (проекты monitoring и ML).
|
||||
|
||||
- Заголовки (`deploy/nginx/snippets/security-headers.conf`): `Content-Security-Policy` с `default-src 'none'`, скриптами, стилями, шрифтами, изображениями и `connect-src` только того же origin, без inline-кода, `frame-ancestors 'none'`, `base-uri 'none'`, `object-src 'none'`; `X-Content-Type-Options: nosniff`; `Referrer-Policy: strict-origin-when-cross-origin`; `X-Frame-Options: DENY`; `Cross-Origin-Opener-Policy` и `Cross-Origin-Resource-Policy` со значением `same-origin`; `Permissions-Policy`, запрещающий камеру, микрофон, геолокацию, платежи и USB. `index.html` и fallback глубоких ссылок получают `Cache-Control: no-cache`, поэтому релиз подхватывается сразу; `/assets/` (имена с хешем) получает `public, max-age=31536000, immutable`, а отсутствующий файл дает 404, а не страницу fallback. Редиректы относительные (`absolute_redirect off`, `port_in_redirect off`), поэтому поддельный `Host` не может ими управлять. Если SPA позже потребуется внешний хост (аналитика, шрифты, карта), добавьте его в соответствующую директиву CSP в том же изменении. CORS-заголовки не отправляются: API работает на одном origin, и браузер запрещает чтение с другого; backend по-прежнему проверяет `Origin` у небезопасных методов.
|
||||
- Лимиты тела: `client_max_body_size` равен 1 МБ для `/api/v1/` (JSON-тела контракта малы). Операции загрузки в контракте пока нет, поэтому маршрута для резюме на 5 МБ нет; изменение, которое его добавит, поднимает лимит в отдельном `location` этого маршрута в `deploy/nginx/conf.d/app.conf` и держит `EDGE_MAX_BODY` не ниже него. Более крупное тело получает от Nginx 413 с телом `application/problem+json` (`payload_too_large`, `trace_id` равен заголовку ответа `X-Request-ID`) в той же форме, что и собственный 413 backend.
|
||||
- Тайм-ауты: чтение на edge 60 с, затем чтение в app Nginx 30 с, затем backend (вызовы хранилища и почты ограничены 10 с, `Redis` - 1 с, чтение заголовков - 5 с). Каждый внешний узел ждет дольше внутреннего, поэтому первым отвечает backend.
|
||||
- Грубые лимиты частоты в app Nginx: 20 запросов в секунду на клиента с всплеском 60 и 40 одновременных соединений на `/api/v1/`. Они гасят потоки запросов и намного выше обычного использования. Они не заменяют доменные квоты (лимиты на аккаунт, маршрут, адрес почты), которыми владеет backend и которые считаются независимо. Ключ лимита - адрес клиента, а IPv6 сводится к своей /64 (как делает `middleware.LimiterKey`). Ограниченный запрос получает 429 с `Retry-After: 1` и проблемой `rate_limited` из контракта (с `trace_id`). Отказы пишутся с уровнем `notice`, ниже порога `warn` журнала ошибок Nginx, потому что строка об отказе называет адрес клиента.
|
||||
- Цепочка адреса клиента: edge заменяет `X-Forwarded-For` адресом подключения; frontend контейнер доверяет только адресу туннеля edge (`set_real_ip_from`, равен `AWG_EDGE_IP`) и берет клиента с правого края заголовка, поэтому значение, добавленное клиентом слева, никогда не достигается. Для пира, который не edge, он игнорирует заголовок целиком. `X-Forwarded-Proto: https` тоже принимается только от этого пира. Затем он отправляет backend единственную запись `X-Forwarded-For` с найденным клиентом, заменяя заголовок, и удаляет `Forwarded`. У core сети Docker закреплена подсеть (`APP_SUBNET`, по умолчанию `172.29.79.0/24`), а у frontend контейнера фиксированный адрес в ней (`APP_FRONTEND_IP`, по умолчанию `172.29.79.10`; меняйте оба вместе при коллизии диапазона, а существующую сеть пересоздайте через `make -C deploy down` и `up`). Backend доверяет `X-Forwarded-For` только от `TRUSTED_PROXY_CIDRS`, по умолчанию это один этот адрес как /32, поэтому ни один другой контейнер сети (Prometheus, exporters, Alloy) не пользуется доверием; не задавайте переменную, пустое значение не доверяет никому. Одноразовые стенды smoke, e2e и metrics-check используют свои подсети (172.29.81 - 83), чтобы работать рядом со стендом разработки. Backend читает заголовок справа, пропуская доверенные прокси; первая недоверенная запись - клиент. Если edge приходит в контейнер с другого адреса, чем `AWG_EDGE_IP`, заголовок игнорируется и клиенты делят одну корзину лимита (отказ в безопасную сторону); см. чек-лист раскатки ниже.
|
||||
- Адрес клиента используется только как ключ лимитов: в разделяемой памяти Nginx и в ключах лимитера backend (`middleware.LimiterKey`, IPv6 сводится к /64, ключ живет окно лимита). Он не логируется и не хранится. В формате журнала app Nginx и в журнале запросов backend нет поля адреса; журнал доступа edge, как и раньше, пишет `$remote_addr` и ротируется logrotate.
|
||||
|
||||
Проверка: `make -C deploy check-perimeter` (отрисовывает Compose-файлы и проверяет опубликованные порты; читает файлы Nginx на запрещенные пути, порядок лимитов, заголовки и доверенный пир; входит в `make -C deploy check`) и `make -C deploy perimeter-test` (запускает одноразовые контейнеры Nginx в приватной сети Docker с заглушками upstream, публикует только на 127.0.0.1 и проверяет по HTTP: обновление SPA, запрещенные пути, заголовки, отсутствие CORS, проблемы 413 и 429, подделанный `X-Forwarded-For` от недоверенного и от доверенного пира и отсутствие адреса клиента в журнале Nginx). Он также проверяет заголовки кеша и cross-origin, относительные редиректы, закодированные варианты и сегменты с точками в запрещенных путях и корзины IPv6 по /64. Тест выполняет `nginx -t` на неизмененных файлах репозитория. Он не поднимает Compose стенд, поэтому не проверяет настоящий backend и TLS edge. Чек-лист первой раскатки за edge (пока не выполнен; тесты выше этого не доказывают): (1) с двух внешних адресов клиентов запрашивайте `/api/v1/healthz` в цикле, пока один не получит 429, и убедитесь, что второй по-прежнему получает 200: это показывает, что app Nginx видит edge как `10.79.0.1` и находит реальных клиентов; если ограничены оба сразу, адрес пира отличается от `AWG_EDGE_IP`, и заголовок игнорируется; (2) убедитесь, что `X-Forwarded-Proto: https` доходит до backend (cookie сессии получает `Secure`); (3) убедитесь, что `curl http://<туннельный-адрес-app-хоста>:8080/metrics` отвечает 404. Ручной шаг в браузере на запущенном стенде: откройте глубокую ссылку и обновите страницу (SPA загружается), в инструментах разработчика проверьте заголовки ответа и отсутствие нарушений CSP в консоли и отправьте файл больше лимита командой `curl -i -X POST --data-binary @big.bin -H 'Content-Type: application/octet-stream' http://127.0.0.1:8080/api/v1/<operation>`, чтобы увидеть 413.
|
||||
|
||||
### Relay outbox
|
||||
|
||||
Backend запускает relay outbox в своем процессе рядом с HTTP-серверами. Relay публикует зафиксированные события outbox в Kafka; устройство описано в [ARCHITECTURE.md](ARCHITECTURE.md#relay-outbox). Compose не передает ни одну из настроек ниже, поэтому стек использует значения по умолчанию; чтобы изменить настройку, добавьте ее в `environment` сервиса backend в `deploy/docker/docker-compose.yml`. Backend, запущенный напрямую, читает их из своего окружения. Недопустимое значение останавливает старт.
|
||||
@@ -373,8 +386,8 @@ Edge-хост общий с другими сервисами. Здесь все
|
||||
- Порт 443 разрешает TLS 1.2 и 1.3 с набором шифров Mozilla intermediate, HTTP/2, без session tickets и отдает `Strict-Transport-Security: max-age=<EDGE_HSTS_MAX_AGE>; includeSubDomains` без `preload`. По умолчанию max-age - 180 дней; поднимите до года и рассматривайте preload только после того, как сайт какое-то время проработает на HTTPS. Заголовки безопасности от frontend контейнера (`X-Content-Type-Options`, `Referrer-Policy`, `X-Frame-Options`, `Permissions-Policy`) проходят насквозь.
|
||||
- OCSP stapling выключен намеренно: сертификаты Let's Encrypt больше не содержат URL OCSP-ответчика, прикреплять нечего. HTTP/3 выключен, потому что ему нужен UDP 443, который занят другим сервисом на edge-хосте.
|
||||
- Сжатие выключено для `/api/` и в остальных местах ограничено CSS, JavaScript, SVG и HTML-оболочкой (JSON не сжимается). Сжатие ответов, где секрет смешан с управляемым атакующим содержимым, открывает BREACH; CSRF-токен в ответе API нельзя сжимать никогда. Пересмотрите это, если секрет когда-либо окажется в HTML.
|
||||
- `X-Forwarded-For` и `X-Real-IP` заменяются адресом подключения, а не дополняют значения клиента, потому что edge - первый доверенный узел. Frontend контейнер затем добавляет адрес туннеля, поэтому backend читает адрес клиента как первую запись `X-Forwarded-For`. Собственный `X-Real-IP` контейнера и лимит `/telemetry` видят адрес пира туннеля или шлюза Docker, поэтому все клиенты делят одну корзину, пока контейнер не станет доверять edge для реальных адресов клиентов.
|
||||
- `client_max_body_size` равен `EDGE_MAX_BODY` (10 МБ, как лимит контейнера). Лимит резюме 5 МБ - политика конкретной функции, ее проверяет backend. Тайм-ауты: 5 с на соединение, 60 с на отправку и чтение (контейнер дает Go 30 с), 60 с на тело запроса.
|
||||
- `X-Forwarded-For` и `X-Real-IP` заменяются адресом подключения, а не дополняют значения клиента, потому что edge - первый доверенный узел. Frontend контейнер доверяет адресу туннеля edge, находит по этому заголовку клиента, использует его для своих грубых лимитов и передает backend единственную замененную запись `X-Forwarded-For` (см. [Публичный периметр и адрес клиента](#публичный-периметр-и-адрес-клиента)).
|
||||
- `client_max_body_size` равен `EDGE_MAX_BODY` (10 МБ, потолок; контейнер по умолчанию разрешает 1 МБ и поднимает лимит по маршрутам, но не выше этого значения). Лимит резюме 5 МБ - политика конкретной функции, ее проверяет backend. Тайм-ауты: 5 с на соединение, 60 с на отправку и чтение (контейнер дает Go 30 с), 60 с на тело запроса.
|
||||
- Журнал доступа (`/var/log/nginx/lincodex.access.log`, ротируется правилом logrotate из пакета) пишет путь без query string, поэтому значения вроде адресов в query в журнал не попадают.
|
||||
|
||||
### Раскатка на edge-хосте
|
||||
@@ -497,7 +510,7 @@ Reload запускает новые workers с новым сертификат
|
||||
|
||||
### Ограничения
|
||||
|
||||
Это один edge-хост и один app-хост. Нет failover, внешней проверки доступности и ограничения частоты запросов на edge (лимиты backend отдельные и еще не реализованы). Сертификат покрывает только одно имя, сайт работает только по IPv4, у аккаунта ACME нет контактного адреса. Туннель не имеет аутентификации кроме ключей AmneziaWG, а параметры обфускации повышают цену блокировки, но не являются мерой безопасности.
|
||||
Это один edge-хост и один app-хост. Нет failover, внешней проверки доступности и ограничения частоты запросов на edge (frontend контейнер применяет грубые лимиты на клиента, а доменные квоты backend отдельные и еще не реализованы). Сертификат покрывает только одно имя, сайт работает только по IPv4, у аккаунта ACME нет контактного адреса. Туннель не имеет аутентификации кроме ключей AmneziaWG, а параметры обфускации повышают цену блокировки, но не являются мерой безопасности.
|
||||
|
||||
## Сервисы и образы
|
||||
|
||||
|
||||
Reference in new issue
Block a user