feat(deploy): restrict the public perimeter and resolve the client address

This commit is contained in:
shira committed 2026-10-06 21:32:03 +03:00
1 parent e52ffe7bcb
commit 57174dffba
25 files changed
+1224 -25

No files matched your search

+11
View File
@@ -63,6 +63,17 @@ SMTP_TLS_MODE=
# more than 1 only adds memory while the derivations share the CPU.
PASSWORD_HASH_CONCURRENCY=1
# The app Docker network has a pinned subnet and the frontend container a fixed
# address on it, so the backend can trust exactly that one proxy. Change the
# two together if the range collides with another network or route.
APP_SUBNET=172.29.79.0/24
APP_FRONTEND_IP=172.29.79.10
# Reverse proxies the backend trusts to report the client address in
# X-Forwarded-For. Leave it unset: the default is the frontend container's
# APP_FRONTEND_IP as a single address. A wider list lets other containers (or a
# client behind them) choose their own address; empty trusts nobody.
# TRUSTED_PROXY_CIDRS=
# Optional PostgreSQL metrics login, created when the database volume is initialized.
POSTGRES_EXPORTER_USER=metrics_reader
POSTGRES_EXPORTER_PASSWORD=replace-this-metrics-password
+2
View File
@@ -232,6 +232,8 @@ jobs:
persist-credentials: false
- name: Check Compose files
run: make -C deploy check
- name: Test the public Nginx perimeter on throwaway containers
run: make -C deploy perimeter-test
- name: Check observability files
run: make -C observability check
- name: Build the separate ML image
+9
View File
@@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"net"
"net/netip"
"os"
"strconv"
"strings"
@@ -118,6 +119,11 @@ type Config struct {
// PasswordHashConcurrency is the number of password hash derivations
// that may run at once; further logins and registrations wait.
PasswordHashConcurrency int
// TrustedProxyCIDRs are the reverse proxies in front of the API. The
// client address is taken from X-Forwarded-For only through them (see
// middleware.ClientIP). Empty trusts no proxy.
TrustedProxyCIDRs []netip.Prefix
}
type LookupEnv func(string) (string, bool)
@@ -167,6 +173,9 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) {
if err := config.loadPasswordHash(lookup); err != nil {
return Config{}, err
}
if err := config.loadTrustedProxies(lookup); err != nil {
return Config{}, err
}
var err error
config.DatabaseMigrateOnStart, err = boolOrDefault(lookup, "DATABASE_MIGRATE_ON_START", defaultDatabaseMigrateOnStart)
+48
View File
@@ -0,0 +1,48 @@
package config
import (
"fmt"
"net/netip"
"strings"
)
// loadTrustedProxies reads TRUSTED_PROXY_CIDRS, a comma-separated list of
// CIDR prefixes or single addresses of the reverse proxies in front of the
// API. Unset or empty means no proxy is trusted: the client address is the
// connecting peer and X-Forwarded-For is ignored.
func (config *Config) loadTrustedProxies(lookup LookupEnv) error {
value, _ := lookup("TRUSTED_PROXY_CIDRS")
for entry := range strings.SplitSeq(value, ",") {
entry = strings.TrimSpace(entry)
if entry == "" {
continue
}
prefix, err := parseProxyPrefix(entry)
if err != nil {
return fmt.Errorf("Config.loadTrustedProxies - TRUSTED_PROXY_CIDRS entry %q: %w", entry, err)
}
config.TrustedProxyCIDRs = append(config.TrustedProxyCIDRs, prefix)
}
return nil
}
func parseProxyPrefix(entry string) (netip.Prefix, error) {
if !strings.Contains(entry, "/") {
addr, err := netip.ParseAddr(entry)
if err != nil {
return netip.Prefix{}, fmt.Errorf("must be an IP address or a CIDR prefix")
}
addr = addr.Unmap()
return netip.PrefixFrom(addr, addr.BitLen()), nil
}
prefix, err := netip.ParsePrefix(entry)
if err != nil {
return netip.Prefix{}, fmt.Errorf("must be an IP address or a CIDR prefix")
}
if prefix.Bits() == 0 {
// A prefix that matches every address would trust every client and
// let it choose its own address.
return netip.Prefix{}, fmt.Errorf("must not match every address")
}
return prefix.Masked(), nil
}
+45
View File
@@ -0,0 +1,45 @@
package config
import (
"strings"
"testing"
)
func TestLoadFromEnvTrustedProxyCIDRs(t *testing.T) {
tests := map[string]struct {
value string
want []string
}{
"unset": {value: "", want: nil},
"list": {value: " 172.16.0.0/12, 10.79.0.1 ,fd00::/8", want: []string{"172.16.0.0/12", "10.79.0.1/32", "fd00::/8"}},
"masked": {value: "10.79.0.1/30", want: []string{"10.79.0.0/30"}},
"empty items": {value: ",,10.0.0.0/8,", want: []string{"10.0.0.0/8"}},
}
for name, test := range tests {
settings, err := LoadFromEnv(testEnvironment(map[string]string{"TRUSTED_PROXY_CIDRS": test.value}))
if err != nil {
t.Fatalf("LoadFromEnv(%s) error = %v", name, err)
}
got := make([]string, 0, len(settings.TrustedProxyCIDRs))
for _, prefix := range settings.TrustedProxyCIDRs {
got = append(got, prefix.String())
}
if strings.Join(got, ";") != strings.Join(test.want, ";") {
t.Fatalf("LoadFromEnv(%s) TrustedProxyCIDRs = %v, want %v", name, got, test.want)
}
}
}
func TestLoadFromEnvRejectsTrustedProxyCIDRs(t *testing.T) {
for name, value := range map[string]string{
"not an address": "proxy.internal",
"bad prefix": "10.0.0.0/33",
"match all v4": "0.0.0.0/0",
"match all v6": "::/0",
} {
_, err := LoadFromEnv(testEnvironment(map[string]string{"TRUSTED_PROXY_CIDRS": value}))
if err == nil || !strings.Contains(err.Error(), "Config.loadTrustedProxies - TRUSTED_PROXY_CIDRS") {
t.Fatalf("LoadFromEnv(%s) error = %v, want a TRUSTED_PROXY_CIDRS error", name, err)
}
}
}
@@ -0,0 +1,134 @@
package middleware
import (
"context"
"net"
"net/http"
"net/netip"
"strings"
)
// maxForwardedEntries bounds the X-Forwarded-For entries that are examined. A
// longer chain is not a legitimate proxy chain here (edge, app Nginx, backend);
// the entries beyond the bound, which sit furthest from this server, are
// ignored.
const maxForwardedEntries = 16
type clientAddrKey struct{}
// ResolveClientAddr returns the address of the client that made a request, for
// rate limiting and other in-memory decisions. It never logs or stores it.
//
// remoteAddr is the connecting peer (http.Request.RemoteAddr), forwardedFor
// holds every X-Forwarded-For header line, and trusted lists the proxies this
// server runs behind. The rules:
// - A peer outside trusted is the client, and the header is ignored whole:
// anyone can send it.
// - For a trusted peer, the entries are read from the right, which is the
// side that the nearest proxy wrote. Each trusted entry is another proxy
// and is skipped; the first entry that is not trusted is the client. A
// value a client put to the left of the first untrusted entry is never
// reached.
// - An entry that is not an IP address stops the walk, and the last
// address that was already proven (the nearest trusted hop) is returned.
// - When every entry is trusted, the leftmost one is returned.
//
// The result is unmapped (an IPv4-mapped IPv6 address becomes IPv4) and has
// no zone. It is invalid only when remoteAddr is not an IP address.
func ResolveClientAddr(remoteAddr string, forwardedFor []string, trusted []netip.Prefix) netip.Addr {
peer, ok := parseAddr(hostOf(remoteAddr))
if !ok {
return netip.Addr{}
}
if !isTrusted(peer, trusted) {
return peer
}
entries := forwardedEntries(forwardedFor)
hop := peer
for index := len(entries) - 1; index >= 0; index-- {
candidate, ok := parseAddr(entries[index])
if !ok {
return hop
}
if !isTrusted(candidate, trusted) {
return candidate
}
hop = candidate
}
return hop
}
// ClientIP resolves the client address with ResolveClientAddr and stores it in
// the request context for ClientAddr. With no trusted proxies configured the
// client is always the connecting peer.
func ClientIP(trusted []netip.Prefix) func(http.Handler) http.Handler {
trusted = append([]netip.Prefix(nil), trusted...)
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
addr := ResolveClientAddr(r.RemoteAddr, r.Header.Values("X-Forwarded-For"), trusted)
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), clientAddrKey{}, addr)))
})
}
}
// ClientAddr returns the client address that the ClientIP middleware stored.
// The second result is false when the middleware did not run or the peer
// address was not an IP address; a caller must then fail closed, for example
// by sharing one limiter bucket, instead of skipping its limit.
func ClientAddr(ctx context.Context) (netip.Addr, bool) {
addr, ok := ctx.Value(clientAddrKey{}).(netip.Addr)
return addr, ok && addr.IsValid()
}
// LimiterKey is the key under which a rate limiter counts a client: an IPv4
// address as is and an IPv6 address reduced to its /64 network, because one
// subscriber commonly controls a whole /64 and could otherwise pick a new
// bucket per request. The key lives only in limiter memory (or a Redis key
// with a window-length expiry); it must not be logged or stored longer.
func LimiterKey(addr netip.Addr) string {
addr = addr.Unmap()
if addr.Is6() {
prefix, err := addr.Prefix(64)
if err == nil {
return prefix.String()
}
}
return addr.String()
}
func forwardedEntries(lines []string) []string {
var entries []string
for _, line := range lines {
for part := range strings.SplitSeq(line, ",") {
entries = append(entries, strings.TrimSpace(part))
}
}
if len(entries) > maxForwardedEntries {
entries = entries[len(entries)-maxForwardedEntries:]
}
return entries
}
func hostOf(remoteAddr string) string {
if host, _, err := net.SplitHostPort(remoteAddr); err == nil {
return host
}
return remoteAddr
}
func parseAddr(value string) (netip.Addr, bool) {
addr, err := netip.ParseAddr(strings.TrimSpace(value))
if err != nil {
return netip.Addr{}, false
}
return addr.WithZone("").Unmap(), true
}
func isTrusted(addr netip.Addr, trusted []netip.Prefix) bool {
for _, prefix := range trusted {
if prefix.Contains(addr) {
return true
}
}
return false
}
@@ -0,0 +1,145 @@
package middleware
import (
"net/http"
"net/http/httptest"
"net/netip"
"testing"
)
func prefixes(t *testing.T, values ...string) []netip.Prefix {
t.Helper()
result := make([]netip.Prefix, 0, len(values))
for _, value := range values {
prefix, err := netip.ParsePrefix(value)
if err != nil {
t.Fatalf("ParsePrefix(%q) error = %v", value, err)
}
result = append(result, prefix)
}
return result
}
func TestResolveClientAddr(t *testing.T) {
// The deployed chain: client -> edge (10.79.0.1) -> app Nginx container
// (172.18.0.5) -> backend. Nginx sends one entry, the client address.
trusted := prefixes(t, "172.16.0.0/12", "10.79.0.0/30")
tests := []struct {
name string
remoteAddr string
forwarded []string
trusted []netip.Prefix
want string
}{
{"trusted chain returns the client", "172.18.0.5:41234", []string{"203.0.113.9"}, trusted, "203.0.113.9"},
{"edge entry is skipped", "172.18.0.5:1", []string{"203.0.113.9, 10.79.0.1"}, trusted, "203.0.113.9"},
{"client value left of the proven client is ignored", "172.18.0.5:1", []string{"198.51.100.7, 203.0.113.9, 10.79.0.1"}, trusted, "203.0.113.9"},
{"spoofed first entry cannot replace the real client", "172.18.0.5:1", []string{"1.2.3.4, 203.0.113.9"}, trusted, "203.0.113.9"},
{"untrusted peer ignores the header", "198.51.100.20:5555", []string{"1.2.3.4"}, trusted, "198.51.100.20"},
{"untrusted peer with a trusted looking entry", "198.51.100.20:5555", []string{"10.79.0.1"}, trusted, "198.51.100.20"},
{"no trusted proxies means the peer", "172.18.0.5:1", []string{"203.0.113.9"}, nil, "172.18.0.5"},
{"no header means the proxy itself", "172.18.0.5:1", nil, trusted, "172.18.0.5"},
{"all entries trusted returns the leftmost", "172.18.0.5:1", []string{"172.18.0.1, 10.79.0.1"}, trusted, "172.18.0.1"},
{"several header lines are one list", "172.18.0.5:1", []string{"1.2.3.4", "203.0.113.9"}, trusted, "203.0.113.9"},
{"garbage entry stops at the proven hop", "172.18.0.5:1", []string{"203.0.113.9, not-an-ip"}, trusted, "172.18.0.5"},
{"entry with a port is not an address", "172.18.0.5:1", []string{"203.0.113.9:80"}, trusted, "172.18.0.5"},
{"IPv4-mapped IPv6 is unmapped", "172.18.0.5:1", []string{"::ffff:203.0.113.9"}, trusted, "203.0.113.9"},
{"IPv6 client", "172.18.0.5:1", []string{"2001:db8::1"}, trusted, "2001:db8::1"},
{"peer without a port", "172.18.0.5", []string{"203.0.113.9"}, trusted, "203.0.113.9"},
{"IPv6 peer in brackets", "[::1]:80", []string{"203.0.113.9"}, prefixes(t, "::1/128"), "203.0.113.9"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got := ResolveClientAddr(test.remoteAddr, test.forwarded, test.trusted)
if got.String() != test.want {
t.Fatalf("ResolveClientAddr() = %s, want %s", got, test.want)
}
})
}
}
func TestResolveClientAddrInvalidPeer(t *testing.T) {
if got := ResolveClientAddr("pipe", []string{"203.0.113.9"}, prefixes(t, "0.0.0.0/0")); got.IsValid() {
t.Fatalf("ResolveClientAddr() = %s, want an invalid address", got)
}
}
func TestResolveClientAddrLongChainIsBounded(t *testing.T) {
// A client cannot push the real entry out of the examined window: the
// bound keeps the entries nearest to this server.
entries := "9.9.9.9"
for range 40 {
entries += ", 8.8.8.8"
}
entries += ", 203.0.113.9"
got := ResolveClientAddr("172.18.0.5:1", []string{entries}, prefixes(t, "172.16.0.0/12"))
if got.String() != "203.0.113.9" {
t.Fatalf("ResolveClientAddr() = %s, want 203.0.113.9", got)
}
}
func TestClientIPMiddleware(t *testing.T) {
trusted := prefixes(t, "172.16.0.0/12")
handler := ClientIP(trusted)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
addr, ok := ClientAddr(r.Context())
if !ok {
t.Error("ClientAddr() reported no address")
}
_, _ = w.Write([]byte(addr.String()))
}))
tests := []struct {
name, remote, forwarded, want string
}{
{"trusted chain", "172.18.0.5:1", "203.0.113.9", "203.0.113.9"},
{"spoof from an untrusted peer", "198.51.100.20:1", "203.0.113.9", "198.51.100.20"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
request := httptest.NewRequest(http.MethodGet, "/", nil)
request.RemoteAddr = test.remote
request.Header.Set("X-Forwarded-For", test.forwarded)
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if recorder.Body.String() != test.want {
t.Fatalf("client = %s, want %s", recorder.Body.String(), test.want)
}
})
}
}
func TestClientIPDoesNotAliasTrustedList(t *testing.T) {
trusted := prefixes(t, "172.16.0.0/12")
handler := ClientIP(trusted)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
addr, _ := ClientAddr(r.Context())
_, _ = w.Write([]byte(addr.String()))
}))
trusted[0] = netip.MustParsePrefix("198.51.100.0/24")
request := httptest.NewRequest(http.MethodGet, "/", nil)
request.RemoteAddr = "172.18.0.5:1"
request.Header.Set("X-Forwarded-For", "203.0.113.9")
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if recorder.Body.String() != "203.0.113.9" {
t.Fatalf("client = %s, want the list copied at construction", recorder.Body.String())
}
}
func TestClientAddrWithoutMiddleware(t *testing.T) {
if _, ok := ClientAddr(httptest.NewRequest(http.MethodGet, "/", nil).Context()); ok {
t.Fatal("ClientAddr() reported an address without the middleware")
}
}
func TestLimiterKey(t *testing.T) {
tests := map[string]string{
"203.0.113.9": "203.0.113.9",
"::ffff:203.0.113.9": "203.0.113.9",
"2001:db8:1:2:3:4:5:6": "2001:db8:1:2::/64",
"2001:db8:1:2:ffff:ffff::abc": "2001:db8:1:2::/64",
}
for input, want := range tests {
if got := LimiterKey(netip.MustParseAddr(input)); got != want {
t.Errorf("LimiterKey(%s) = %s, want %s", input, got, want)
}
}
}
+8 -2
View File
@@ -27,7 +27,7 @@ RELEASE_MANIFEST ?=
LINCODEX_RELEASE_TAG ?= $(shell PYTHONDONTWRITEBYTECODE=1 python3 "$(RELEASE_SCRIPT)" tag)
PLAYWRIGHT_VERSION := $(shell sed -n 's/^ *"@playwright\/test": "\([^"]*\)",\{0,1\}$$/\1/p' "$(ROOT)/frontend/package.json")
.PHONY: help config build up down logs monitoring-config monitoring-up monitoring-down monitoring-logs ml-config ml-build ml-up ml-down ml-logs check check-workflows check-release smoke test-e2e release-build release-smoke release-e2e release-manifest release-manifest-verify release-manifest-check release-up release-down release-clean
.PHONY: help config build up down logs monitoring-config monitoring-up monitoring-down monitoring-logs ml-config ml-build ml-up ml-down ml-logs check check-workflows check-release check-perimeter perimeter-test smoke test-e2e release-build release-smoke release-e2e release-manifest release-manifest-verify release-manifest-check release-up release-down release-clean
help: ## Show deployment commands
@awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "%-24s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
@@ -104,7 +104,7 @@ edge-render: ## Render the edge nginx config from deploy/edge/edge.env into depl
edge-config: ## Render the edge templates and check the nginx config with nginx -t in a container
@DOCKER="$(DOCKER)" EDGE_NGINX_IMAGE="$(EDGE_NGINX_IMAGE)" bash "$(EDGE_DIR)/scripts/check.sh" "$(EDGE_ENV)"
check: config check-workflows check-release ## Validate Compose files, CI workflow aggregates, and release tooling without starting services
check: config check-workflows check-release check-perimeter ## Validate Compose files, CI workflow aggregates, release tooling, and the public perimeter without starting services
check-workflows: ## Check that each workflow aggregate job requires every other job
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/scripts" -p 'test_workflow_aggregate.py'
@@ -112,6 +112,12 @@ check-workflows: ## Check that each workflow aggregate job requires every other
check-release: ## Test the release manifest tooling, its secret scan, and the Go and base image pins
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/deploy/scripts" -p 'test_release_manifest.py'
check-perimeter: ## Check published ports, the app Nginx paths, limits, and the trusted proxy chain from the files
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s "$(ROOT)/deploy/scripts" -p 'test_perimeter.py'
perimeter-test: ## Start throwaway Nginx containers and test denied paths, limits, headers, and forwarded headers over HTTP
LINCODEX_PERIMETER_LIVE=1 DOCKER="$(DOCKER)" PERIMETER_NGINX_IMAGE="$(EDGE_NGINX_IMAGE)" PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -v -s "$(ROOT)/deploy/scripts" -p 'test_perimeter.py'
smoke: ## Start an isolated stack and check infrastructure health routes
@bash scripts/smoke.sh
+1
View File
@@ -11,6 +11,7 @@ Configuration for running the application with Docker Compose and Nginx.
- `docker/docker-compose.release.yml` and `docker/docker-compose.ml.release.yml` are overlays that name the release images `lincodex.invalid/<service>:<tag>` and never pull them from a registry.
- `scripts/` contains the isolated stack smoke check, the browser E2E runner, and `release_manifest.py`, which builds, describes, and checks release images.
- `edge/` holds the public edge proxy: nginx and tunnel templates, certbot renewal hook, systemd drop-ins, and the scripts that render and check them. `make -C deploy edge-config` renders the nginx configuration and runs `nginx -t` in a container; see the [edge proxy runbook](../docs/en/DEPLOY.md#edge-proxy-https-and-tunnel).
- `make -C deploy check-perimeter` checks the published ports, denied paths, limits, and the trusted peer of Nginx from the files; `make -C deploy perimeter-test` checks the same over HTTP on throwaway Nginx containers; see [Public perimeter and client address](../docs/en/DEPLOY.md#public-perimeter-and-client-address).
Dockerfiles live in service directories and `.env.example` at the repository root. From the root, `make -C deploy config` checks Compose and `make -C deploy up` starts the core stack after `.env` is prepared. Start monitoring separately with `make -C deploy monitoring-up`. `make -C deploy test-e2e` runs the Playwright suite against a throwaway stack under a unique project name and removes it afterwards; see [TESTING.md](../docs/en/TESTING.md#browser-e2e-suite).
+1
View File
@@ -11,6 +11,7 @@
- `docker/docker-compose.release.yml` и `docker/docker-compose.ml.release.yml` - overlay с именами образов выпуска `lincodex.invalid/<service>:<tag>` без скачивания из registry.
- `scripts/` содержит smoke-проверку изолированного стека, запуск браузерных E2E и `release_manifest.py` для сборки, описания и сверки образов выпуска.
- `edge/` содержит публичный edge proxy: шаблоны nginx и туннеля, hook продления certbot, drop-in systemd и скрипты, которые их отрисовывают и проверяют. `make -C deploy edge-config` отрисовывает конфигурацию nginx и выполняет `nginx -t` в контейнере; см. [runbook edge proxy](../docs/ru/DEPLOY.md#edge-proxy-https-и-туннель).
- `make -C deploy check-perimeter` проверяет по файлам опубликованные порты, запрещенные пути, лимиты и доверенного пира Nginx; `make -C deploy perimeter-test` проверяет то же по HTTP на одноразовых контейнерах Nginx; см. [Публичный периметр и адрес клиента](../docs/ru/DEPLOY.md#публичный-периметр-и-адрес-клиента).
Dockerfile лежат в каталогах сервисов, `.env.example` - в корне репозитория. Из корня: `make -C deploy config` проверяет Compose, `make -C deploy up` запускает основной стек после подготовки `.env`. Мониторинг включается отдельно через `make -C deploy monitoring-up`. `make -C deploy test-e2e` запускает набор Playwright на одноразовом стеке с уникальным именем проекта и удаляет его после прогона; см. [TESTING.md](../docs/ru/TESTING.md#браузерный-e2e-набор).
+17
View File
@@ -229,6 +229,12 @@ services:
SMTP_TLS_MODE: ${SMTP_TLS_MODE:-}
# Argon2id derivations that may run at once, 64 MiB each (1 to 4).
PASSWORD_HASH_CONCURRENCY: ${PASSWORD_HASH_CONCURRENCY:-1}
# Proxies whose X-Forwarded-For is believed: only the frontend container,
# which has a fixed address on the pinned app network below. Other
# containers of that network (Prometheus, exporters, Alloy) are not
# trusted. The frontend Nginx already replaces the header with the
# client address it resolved behind the edge.
TRUSTED_PROXY_CIDRS: ${TRUSTED_PROXY_CIDRS:-${APP_FRONTEND_IP:-172.29.79.10}/32}
# Soft Go heap limit at about 78% of the 768M container limit below; the
# rest covers goroutine stacks, runtime metadata, and non-heap memory.
# Change both together.
@@ -275,6 +281,9 @@ services:
depends_on:
backend:
condition: service_started
networks:
default:
ipv4_address: ${APP_FRONTEND_IP:-172.29.79.10}
ports:
# Loopback by default. On the app host behind the edge proxy,
# APP_HTTP_BIND is the tunnel address (see docs/en/DEPLOY.md); never
@@ -309,6 +318,14 @@ volumes:
networks:
default:
name: ${APP_NETWORK:-app_default}
# Pinned so that the frontend container, the only trusted proxy of the
# backend, has a known address. Change APP_SUBNET and APP_FRONTEND_IP
# together when the range collides with a route or another Docker network;
# a network that already exists with another subnet must be recreated
# (make -C deploy down, then up).
ipam:
config:
- subnet: ${APP_SUBNET:-172.29.79.0/24}
# Only SeaweedFS, the backend, and the monitoring Prometheus join it.
storage:
name: ${APP_STORAGE_NETWORK:-${APP_PROJECT:-app}_storage}
+3 -2
View File
@@ -19,8 +19,9 @@ EDGE_ACME_WEBROOT=/var/www/certbot
# Strict-Transport-Security max-age in seconds (180 days). Raise it to
# 31536000 and consider preload only after the site has run on HTTPS for a while.
EDGE_HSTS_MAX_AGE=15552000
# Request body limit. Keep it at or above the inner nginx limit (10m) and the
# largest upload policy (resume: 5 MB plus multipart overhead).
# Request body limit. Keep it at or above every limit of the inner nginx
# (1m by default, raised per route; never above 10m) and the largest upload
# policy (resume: 5 MB plus multipart overhead).
EDGE_MAX_BODY=10m
# Tunnel: one dedicated point-to-point AmneziaWG link between the edge (server
@@ -43,7 +43,9 @@ server {
add_header Strict-Transport-Security "max-age={{EDGE_HSTS_MAX_AGE}}; includeSubDomains" always;
# Largest accepted request body. The resume upload limit is 5 MB; the
# frontend container allows 10 MB, and this value must not be lower.
# frontend container allows 1 MB by default and more only on a route that
# needs it (never above 10 MB), and this value must not be lower than any
# of those limits.
client_max_body_size {{EDGE_MAX_BODY}};
client_header_timeout 15s;
client_body_timeout 60s;
@@ -71,6 +73,9 @@ server {
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Real-IP $remote_addr;
# A client-supplied Forwarded header would be a second, unchecked source
# of the client address.
proxy_set_header Forwarded "";
proxy_redirect off;
proxy_connect_timeout 5s;
proxy_send_timeout 60s;
+125 -10
View File
@@ -1,11 +1,28 @@
# Public perimeter of the app host. Only three things are reachable here: the
# SPA (static files plus the index.html fallback), the versioned public API
# under /api/v1/, and the restricted same-origin /telemetry receiver. Backend
# /metrics (port 9090), /readyz, and every other service never pass through
# this server; the paths that look like them are answered with 404 so the SPA
# fallback does not turn them into a 200 page either.
#
# The perimeter is checked by deploy/scripts/test_perimeter.py
# (make -C deploy perimeter-test).
# Behind the TLS edge proxy the client's scheme arrives in X-Forwarded-Proto
# (deploy/edge). Keep it when it is https so the backend sees the original
# scheme; every other value falls back to the scheme of this server. The
# header is trustworthy only because the frontend port is published on
# loopback or on the tunnel address, never on a public one.
map $http_x_forwarded_proto $forwarded_proto {
default $scheme;
https https;
# The claim is believed only from the trusted edge peer, so any other peer
# cannot make the backend think the request was HTTPS.
geo $realip_remote_addr $trusted_edge {
default 0;
10.79.0.1 1;
}
map "$trusted_edge:$http_x_forwarded_proto" $forwarded_proto {
default $scheme;
"1:https" https;
}
server {
@@ -13,11 +30,46 @@ server {
server_name _;
root /usr/share/nginx/html;
index index.html;
# Redirects (for example /assets to /assets/) never use the Host header or
# the container port, so a forged Host cannot steer a redirect.
absolute_redirect off;
port_in_redirect off;
add_header X-Content-Type-Options nosniff always;
add_header Referrer-Policy strict-origin-when-cross-origin always;
add_header X-Frame-Options DENY always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
# Client address. The only trusted proxy is the edge end of the tunnel
# (AWG_EDGE_IP in deploy/edge/edge.env.example; the perimeter test keeps
# the two equal). For a request from that peer, the client is the last
# X-Forwarded-For entry that is not a trusted proxy; for any other peer
# the header is ignored and $remote_addr stays the connecting address.
# The rate limits below and the X-Forwarded-For sent to the backend use
# this value, so a client cannot choose its own bucket. If the edge peer
# reaches this server under another address (for example a Docker
# gateway address), the header is ignored and all clients share one
# bucket: that fails closed, never open.
set_real_ip_from 10.79.0.1;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
include /etc/nginx/snippets/security-headers.conf;
# Limit and rate responses use the problem format of the API contract.
# The status is set explicitly, so the error_page statuses do not change.
error_page 413 @payload_too_large;
error_page 429 @rate_limited;
location @payload_too_large {
include /etc/nginx/snippets/security-headers.conf;
default_type application/problem+json;
add_header X-Request-ID $request_id always;
return 413 '{"type":"urn:lincodex:problem:payload_too_large","title":"Request body too large","status":413,"code":"payload_too_large","detail":"Reduce the request body size and retry.","trace_id":"$request_id"}';
}
location @rate_limited {
include /etc/nginx/snippets/security-headers.conf;
add_header Retry-After 1 always;
add_header X-Request-ID $request_id always;
default_type application/problem+json;
return 429 '{"type":"urn:lincodex:problem:rate_limited","title":"Too many requests","status":429,"code":"rate_limited","detail":"Wait for the Retry-After interval and retry.","trace_id":"$request_id"}';
}
location = /healthz {
access_log off;
@@ -25,39 +77,102 @@ server {
return 200 "ok\n";
}
# Operational and administration paths of the services behind this
# server. None of them is proxied; 404 is the same answer as for an
# unknown API path, so the response does not confirm that the path exists.
location ~ ^/(metrics|readyz|debug|actuator)(/|$) {
return 404;
}
# Dotfiles are never served from the SPA directory.
location ~ /\. {
return 404;
}
# Without these, nginx would redirect /api/v1 to /api/v1/ and leak the
# difference; the public paths all have an operation name after the slash.
location = /api {
return 404;
}
location ^~ /api/ {
location = /api/v1 {
return 404;
}
# The public API. Same-origin only: no CORS header is added here or by the
# backend, so a browser refuses cross-origin reads. The backend still
# checks Origin on unsafe methods (403 csrf_check_failed).
location ^~ /api/v1/ {
limit_req zone=api_rate burst=60 nodelay;
limit_conn api_conn 40;
proxy_pass http://backend:8080;
proxy_http_version 1.1;
proxy_set_header Host $host;
# Replace, never append: the backend receives one entry, the client
# address resolved above, from a proxy it trusts (this container).
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Forwarded "";
proxy_set_header X-Forwarded-Proto $forwarded_proto;
proxy_set_header X-Request-ID $request_id;
proxy_set_header Connection "";
proxy_connect_timeout 3s;
proxy_send_timeout 30s;
# Above the longest backend dependency timeout (10 s for storage and
# mail) and below the edge read timeout (60 s), so the backend answers
# first and the edge never gives up before this server.
proxy_read_timeout 30s;
}
# Everything else under /api is not part of the public contract.
location ^~ /api/ {
return 404;
}
location = /telemetry {
if ($request_method != POST) {
return 405;
}
limit_req zone=telemetry_rate burst=10 nodelay;
client_max_body_size 1m;
set $faro_receiver faro-receiver:12347;
proxy_pass http://$faro_receiver/collect;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Forwarded "";
proxy_set_header X-Forwarded-Proto $forwarded_proto;
proxy_set_header Connection "";
proxy_connect_timeout 2s;
proxy_send_timeout 5s;
proxy_read_timeout 5s;
}
location ^~ /telemetry/ {
return 404;
}
# Hashed build files never change under their name, so they are cached
# for a year; a missing one is a 404, never the index.html fallback.
location ^~ /assets/ {
if ($request_method !~ ^(GET|HEAD)$) {
return 405;
}
include /etc/nginx/snippets/security-headers.conf;
add_header Cache-Control "public, max-age=31536000, immutable" always;
try_files $uri =404;
}
# index.html and the deep-link fallback must be revalidated on every
# load: a cached copy would name hashed assets that a release has removed.
location / {
if ($request_method !~ ^(GET|HEAD)$) {
return 405;
}
include /etc/nginx/snippets/security-headers.conf;
add_header Cache-Control "no-cache" always;
try_files $uri $uri/ /index.html;
}
}
+39 -2
View File
@@ -18,7 +18,15 @@ http {
tcp_nopush on;
keepalive_timeout 30s;
server_tokens off;
client_max_body_size 10m;
# Default request body limit: the JSON API bodies of the contract are
# small. The 5 MB resume upload has no operation in the contract yet; the
# route that gets one raises the limit in its own location in app.conf.
# The edge proxy allows 10 MB (EDGE_MAX_BODY) and must stay at or above
# the largest limit here.
client_max_body_size 1m;
client_header_timeout 10s;
client_body_timeout 30s;
send_timeout 30s;
client_body_temp_path /tmp/client_body;
proxy_temp_path /tmp/proxy;
@@ -26,7 +34,36 @@ http {
scgi_temp_path /tmp/scgi;
uwsgi_temp_path /tmp/uwsgi;
limit_req_zone $binary_remote_addr zone=telemetry_rate:10m rate=30r/m;
# Coarse per-client protection only. $remote_addr is the client address
# that app.conf resolved through the trusted edge (realip), never a value
# the client supplied. The values are far above normal browsing: the
# per-account and per-route quotas stay in the backend and are not
# replaced by these. The zones keep addresses in memory only; the access
# log does not record them.
#
# The key is the address, except that an IPv6 address counts as its /64
# network (as middleware.LimiterKey does in the backend): one subscriber
# controls a whole /64 and could otherwise take a new bucket per request.
# $remote_addr is canonical text here (inet_ntop from the edge), so the
# first four groups, or the part before "::", name the network. The two
# spellings of one /64 that differ in where "::" falls get two buckets, a
# harmless looseness for a coarse limit.
map $remote_addr $limit_key {
"~^(?<v6full>(?:[0-9a-f]{1,4}:){4})" $v6full;
"~^(?<v6short>(?:[0-9a-f]{1,4}(?::[0-9a-f]{1,4}){0,2})?::)" $v6short;
default $remote_addr;
}
limit_req_zone $limit_key zone=api_rate:10m rate=20r/s;
limit_conn_zone $limit_key zone=api_conn:10m;
limit_req_zone $limit_key zone=telemetry_rate:10m rate=30r/m;
limit_req_status 429;
limit_conn_status 429;
# A rejection line in the error log names the client address. Rejections
# are routine under a flood and the address must not be logged, so they
# are logged at notice, below the warn threshold of error_log above
# (the default, error, would write them with the address).
limit_req_log_level notice;
limit_conn_log_level notice;
resolver 127.0.0.11 valid=30s ipv6=off;
include /etc/nginx/conf.d/*.conf;
@@ -0,0 +1,18 @@
# Security headers of the app Nginx. Nginx drops every inherited add_header
# in a block that sets its own, so each block that adds a header (named
# error locations) includes this file again.
#
# CSP: the built SPA is one module script and one stylesheet from the same
# origin, fonts and logos are bundled files, and the API is same-origin, so no
# external host and no inline code is allowed. frame-ancestors is the modern
# form of X-Frame-Options and base-uri/form-action/object-src close the
# injection routes that default-src does not cover. When telemetry (Faro)
# is connected it posts to the same-origin /telemetry, which connect-src
# 'self' already allows.
add_header Content-Security-Policy "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; manifest-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'; object-src 'none'" always;
add_header X-Content-Type-Options nosniff always;
add_header Referrer-Policy strict-origin-when-cross-origin always;
add_header X-Frame-Options DENY always;
add_header Cross-Origin-Opener-Policy same-origin always;
add_header Cross-Origin-Resource-Policy same-origin always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=(), usb=(), interest-cohort=()" always;
+1
View File
@@ -80,6 +80,7 @@ done < <(env)
compose() {
env -i "${docker_env[@]}" \
APP_PROJECT="$project" APP_NETWORK="$network" APP_STORAGE_NETWORK="$storage_network" \
APP_SUBNET=172.29.82.0/24 APP_FRONTEND_IP=172.29.82.10 \
PLAYWRIGHT_VERSION="$declared" E2E_CI="${CI:-}" \
E2E_UID="$(id -u)" E2E_GID="$(id -g)" \
E2E_SPEC_DIR="$spec_dir" E2E_ARTIFACTS_DIR="$artifacts_dir" LINCODEX_RELEASE_TAG="$release_tag" \
+1
View File
@@ -31,6 +31,7 @@ started=0
# .env.example and points mail links at its own loopback port.
compose() {
APP_PROJECT="$project" APP_NETWORK="$app_network" APP_STORAGE_NETWORK="$storage_network" APP_HTTP_PORT="$port" \
APP_SUBNET=172.29.81.0/24 APP_FRONTEND_IP=172.29.81.10 \
APP_PUBLIC_URL="http://localhost:$port" LINCODEX_RELEASE_TAG="$release_tag" docker compose \
--env-file "$env_file" \
-p "$project" \
+562
View File
@@ -0,0 +1,562 @@
"""Checks of the public perimeter: published ports, the app Nginx paths, limits,
and client address handling.
Two groups of tests:
- Static tests render the Compose files and read the Nginx files. They need
only the docker CLI for `docker compose config` and run in
`make -C deploy check-perimeter` (part of `make -C deploy check`).
- Live tests start throwaway containers on a private Docker network (the
Nginx image, two stub upstreams that echo the request headers, and two
copies of the app config) and send real HTTP requests. They run only when
LINCODEX_PERIMETER_LIVE=1, which `make -C deploy perimeter-test` sets, and
skip otherwise. They start no Lincodex service and publish ports on
127.0.0.1 only.
"""
import http.client
import json
import os
import re
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
DEPLOY = ROOT / "deploy"
NGINX_DIR = DEPLOY / "nginx"
APP_CONF = NGINX_DIR / "conf.d" / "app.conf"
MAIN_CONF = NGINX_DIR / "nginx.conf"
SNIPPETS = NGINX_DIR / "snippets"
EDGE_ENV = DEPLOY / "edge" / "edge.env.example"
EDGE_HTTPS = DEPLOY / "edge" / "nginx" / "lincodex-https.conf.template"
ENV_FILE = ROOT / ".env.example"
DOCKER = os.environ.get("DOCKER", "docker")
IMAGE = os.environ.get("PERIMETER_NGINX_IMAGE", "nginx:stable-alpine")
LIVE = os.environ.get("LINCODEX_PERIMETER_LIVE") == "1"
SECURITY_HEADERS = {
"x-content-type-options": "nosniff",
"referrer-policy": "strict-origin-when-cross-origin",
"x-frame-options": "DENY",
}
def read_env(path):
values = {}
for line in path.read_text().splitlines():
line = line.strip()
if line and not line.startswith("#") and "=" in line:
key, value = line.split("=", 1)
values[key] = value
return values
def size_bytes(value):
match = re.fullmatch(r"(\d+)([kKmM]?)", value)
assert match, value
return int(match.group(1)) * {"": 1, "k": 1024, "m": 1024 * 1024}[match.group(2).lower()]
def render_compose(file_names, project, extra_env=None, profiles=()):
if isinstance(file_names, str):
file_names = [file_names]
environment = dict(os.environ, APP_PROJECT=project, APP_NETWORK=f"{project}_default")
for name in ("APP_HTTP_BIND", "APP_HTTP_PORT", "ML_BIND_ADDRESS", "APP_SUBNET", "APP_FRONTEND_IP", "TRUSTED_PROXY_CIDRS"):
environment.pop(name, None)
environment.update(extra_env or {})
command = [DOCKER, "compose", "--env-file", str(ENV_FILE), "-p", project]
for file_name in file_names:
command += ["-f", str(DEPLOY / "docker" / file_name)]
for profile in profiles:
command += ["--profile", profile]
result = subprocess.run(command + ["config", "--format", "json"], capture_output=True, text=True, env=environment, check=False)
if result.returncode != 0:
raise AssertionError(f"docker compose config failed for {file_names}: {result.stderr}")
return json.loads(result.stdout)
class ComposePortsTest(unittest.TestCase):
"""Only the app HTTP bind is a host port of the core project."""
@classmethod
def setUpClass(cls):
if shutil.which(DOCKER) is None:
raise unittest.SkipTest("docker CLI is not available")
cls.core = render_compose("docker-compose.yml", "perimeter-core")
def test_core_publishes_only_the_frontend_on_loopback(self):
published = {
name: service["ports"]
for name, service in self.core["services"].items()
if service.get("ports")
}
self.assertEqual(list(published), ["frontend"])
(port,) = published["frontend"]
self.assertEqual(port["target"], 8080)
self.assertEqual(port["host_ip"], "127.0.0.1")
self.assertEqual(port["protocol"], "tcp")
def test_frontend_bind_never_defaults_to_a_wildcard(self):
text = (DEPLOY / "docker" / "docker-compose.yml").read_text()
self.assertIn('"${APP_HTTP_BIND:-127.0.0.1}:${APP_HTTP_PORT:-8080}:8080"', text)
def test_backend_metrics_port_is_only_exposed(self):
backend = self.core["services"]["backend"]
self.assertFalse(backend.get("ports"))
self.assertIn("9090", {str(port) for port in backend.get("expose", [])})
def test_storage_network_is_internal(self):
self.assertTrue(self.core["networks"]["storage"]["internal"])
def test_other_projects_publish_only_loopback_by_default(self):
for file_name, project in (("docker-compose.ml.yml", "perimeter-ml"), ("docker-compose.monitoring.yml", "perimeter-mon")):
rendered = render_compose(file_name, project)
for name, service in rendered["services"].items():
for port in service.get("ports") or []:
with self.subTest(service=name, port=port["target"]):
self.assertEqual(port["host_ip"], "127.0.0.1")
def test_release_and_e2e_overlays_publish_no_extra_ports(self):
release = render_compose(
["docker-compose.yml", "docker-compose.release.yml"], "perimeter-release", {"LINCODEX_RELEASE_TAG": "000000000000"}
)
e2e = render_compose(
["docker-compose.yml", "docker-compose.e2e.yml"], "perimeter-e2e",
{
"PLAYWRIGHT_VERSION": "1.0.0", "E2E_UID": "1000", "E2E_GID": "1000", "E2E_SPEC_DIR": str(ROOT),
"E2E_ARTIFACTS_DIR": str(ROOT),
},
profiles=["e2e"],
)
for label, rendered, allowed in (("release", release, {"frontend"}), ("e2e", e2e, set())):
published = {name for name, service in rendered["services"].items() if service.get("ports")}
self.assertEqual(published, allowed, label)
for port in release["services"]["frontend"]["ports"]:
self.assertEqual(port["host_ip"], "127.0.0.1")
def test_backend_trusts_only_the_frontend_address(self):
import ipaddress
frontend_ip = self.core["services"]["frontend"]["networks"]["default"]["ipv4_address"]
subnet = self.core["networks"]["default"]["ipam"]["config"][0]["subnet"]
self.assertIn(ipaddress.ip_address(frontend_ip), ipaddress.ip_network(subnet))
cidrs = self.core["services"]["backend"]["environment"]["TRUSTED_PROXY_CIDRS"]
self.assertEqual(cidrs, f"{frontend_ip}/32")
env = read_env(ENV_FILE)
self.assertEqual((env["APP_FRONTEND_IP"], env["APP_SUBNET"]), (frontend_ip, subnet))
self.assertNotIn("TRUSTED_PROXY_CIDRS", env, "the example must not widen the default trust")
# No other service has the address, so no other container is trusted.
for name, service in self.core["services"].items():
if name != "frontend":
self.assertNotIn("ipv4_address", (service.get("networks") or {}).get("default") or {})
class NginxFilesTest(unittest.TestCase):
"""Text-level rules for the app and edge Nginx files."""
def setUp(self):
self.app = APP_CONF.read_text()
self.main = MAIN_CONF.read_text()
def test_proxy_targets_are_the_api_and_the_telemetry_receiver_only(self):
directives = "\n".join(line for line in self.app.splitlines() if not line.strip().startswith("#"))
targets = re.findall(r"proxy_pass\s+([^;]+);", directives)
self.assertEqual(sorted(targets), ["http://$faro_receiver/collect", "http://backend:8080"])
self.assertNotIn("9090", directives)
self.assertNotIn("9327", directives)
def test_denied_paths_are_declared(self):
self.assertIn("location ~ ^/(metrics|readyz|debug|actuator)(/|$)", self.app)
self.assertIn("location ~ /\\.", self.app)
self.assertIn("location ^~ /api/v1/", self.app)
self.assertIn("location ^~ /api/ {\n return 404;", self.app)
def test_trusted_edge_peer_matches_the_edge_configuration(self):
edge = read_env(EDGE_ENV)["AWG_EDGE_IP"]
self.assertEqual(re.findall(r"set_real_ip_from\s+([^;]+);", self.app), [edge])
self.assertEqual(re.findall(r"^\s+([\d.]+)\s+1;", self.app, re.M), [edge])
self.assertIn('"1:https"', self.app)
self.assertIn("absolute_redirect off;", self.app)
self.assertIn("port_in_redirect off;", self.app)
self.assertIn("real_ip_header X-Forwarded-For;", self.app)
self.assertIn("real_ip_recursive on;", self.app)
def test_forwarded_for_is_replaced_not_appended(self):
self.assertNotIn("proxy_add_x_forwarded_for", self.app)
self.assertEqual(self.app.count("proxy_set_header X-Forwarded-For $remote_addr;"), 2)
def test_edge_replaces_forwarded_for_and_serves_only_the_proxy_locations(self):
edge = EDGE_HTTPS.read_text()
self.assertIn("proxy_set_header X-Forwarded-For $remote_addr;", edge)
self.assertNotIn("proxy_add_x_forwarded_for", edge)
self.assertEqual(re.findall(r"^\s*location\s+(.+?)\s*\{", edge, re.M), ["^~ /api/", "/"])
def test_body_limits_are_ordered_edge_above_app(self):
edge_limit = size_bytes(read_env(EDGE_ENV)["EDGE_MAX_BODY"])
limits = [size_bytes(value) for value in re.findall(r"client_max_body_size\s+(\w+);", self.main + self.app)]
self.assertTrue(limits)
self.assertGreaterEqual(edge_limit, max(limits))
def test_timeouts_are_ordered_edge_above_app(self):
edge = EDGE_HTTPS.read_text()
edge_read = int(re.search(r"proxy_read_timeout\s+(\d+)s;", edge).group(1))
api_block = self.app.split("location ^~ /api/v1/ {")[1].split("\n }")[0]
app_read = int(re.search(r"proxy_read_timeout\s+(\d+)s;", api_block).group(1))
self.assertGreater(edge_read, app_read)
# The backend's slowest dependency timeouts are 10 s.
self.assertGreater(app_read, 10)
def test_security_headers_snippet(self):
snippet = (SNIPPETS / "security-headers.conf").read_text()
for name in ("Content-Security-Policy", "X-Content-Type-Options", "Referrer-Policy", "X-Frame-Options", "Permissions-Policy"):
self.assertIn(f"add_header {name} ", snippet)
csp = re.search(r'add_header Content-Security-Policy "([^"]+)"', snippet).group(1)
self.assertIn("frame-ancestors 'none'", csp)
self.assertIn("default-src 'none'", csp)
self.assertNotIn("unsafe-inline", csp)
self.assertNotIn("unsafe-eval", csp)
self.assertNotRegex(csp, r"https?://|\*")
def test_every_block_with_its_own_add_header_includes_the_snippet(self):
for name in ("@payload_too_large", "@rate_limited"):
block = self.app.split(f"location {name} {{")[1].split("\n }")[0]
self.assertIn("include /etc/nginx/snippets/security-headers.conf;", block)
self.assertIn("COPY deploy/nginx/snippets/", (ROOT / "frontend" / "Dockerfile").read_text())
def test_cache_headers_and_snippet_on_static_locations(self):
assets = self.app.split("location ^~ /assets/ {")[1].split("\n }")[0]
spa = self.app.split(" location / {")[1].split("\n }")[0]
for block, value in ((assets, "public, max-age=31536000, immutable"), (spa, "no-cache")):
self.assertIn(f'add_header Cache-Control "{value}" always;', block)
self.assertIn("include /etc/nginx/snippets/security-headers.conf;", block)
def test_error_log_does_not_name_clients(self):
self.assertIn("limit_req_log_level notice;", self.main)
self.assertIn("limit_conn_log_level notice;", self.main)
self.assertIn("error_log /dev/stderr warn;", self.main)
def test_request_log_format_has_no_client_address(self):
log_format = re.search(r"log_format main(.*?);", self.main, re.S).group(1)
self.assertNotIn("remote_addr", log_format)
self.assertNotIn("http_x_forwarded_for", log_format)
self.assertNotIn("realip", log_format)
STUB_CONF = r"""
events {}
http {
access_log off;
client_max_body_size 20m;
server {
listen %(port)s;
location / {
default_type text/plain;
return 200 "xff=$http_x_forwarded_for;real=$http_x_real_ip;fwd=$http_forwarded;proto=$http_x_forwarded_proto;host=$host;uri=$request_uri;id=$http_x_request_id;acao=$http_access_control_allow_origin\n";
}
}
}
"""
INDEX_HTML = '<!doctype html><html><body><div id="root"></div><script type="module" src="/assets/index.js"></script></body></html>\n'
def docker(*args, check=True):
result = subprocess.run([DOCKER, *args], capture_output=True, text=True, check=False)
if check and result.returncode != 0:
raise AssertionError(f"docker {' '.join(args[:2])} failed: {result.stderr}")
return result
class Response:
def __init__(self, status, headers, body):
self.status = status
self.headers = {key.lower(): value for key, value in headers}
self.body = body
def echo(self):
"""Parse the stub upstream's echo body into a dict."""
return dict(part.split("=", 1) for part in self.body.strip().split(";") if "=" in part)
@unittest.skipUnless(LIVE, "set LINCODEX_PERIMETER_LIVE=1 (make -C deploy perimeter-test) to run the live Nginx tests")
class LiveNginxTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.prefix = f"lincodex-perimeter-{os.getpid()}"
cls.network = cls.prefix
cls.containers = []
cls.workdir = Path(tempfile.mkdtemp(prefix="lincodex-perimeter-"))
try:
cls._start()
except BaseException:
cls.tearDownClass()
raise
@classmethod
def tearDownClass(cls):
for name in cls.containers:
docker("rm", "-f", name, check=False)
docker("network", "rm", cls.network, check=False)
shutil.rmtree(cls.workdir, ignore_errors=True)
@classmethod
def _run(cls, name, *args):
cls.containers.append(name)
return docker("run", "-d", "--name", name, "--network", cls.network, *args)
@classmethod
def _port(cls, name):
output = docker("port", name, "8080/tcp").stdout.split()[0]
return int(output.rsplit(":", 1)[1])
@classmethod
def _wait(cls, port):
import time
for _ in range(50):
try:
connection = http.client.HTTPConnection("127.0.0.1", port, timeout=2)
try:
connection.request("GET", "/healthz")
if connection.getresponse().status == 200:
return
finally:
connection.close()
except OSError:
pass
time.sleep(0.2)
raise AssertionError(f"nginx on port {port} did not start")
@classmethod
def _start(cls):
docker("network", "create", cls.network)
for alias, port in (("backend", 8080), ("faro-receiver", 12347)):
conf = cls.workdir / f"{alias}.conf"
conf.write_text(STUB_CONF % {"port": port})
cls._run(f"{cls.prefix}-{alias}", "--network-alias", alias, "-v", f"{conf}:/etc/nginx/nginx.conf:ro", IMAGE)
html = cls.workdir / "html"
(html / "assets").mkdir(parents=True)
(html / "index.html").write_text(INDEX_HTML)
(html / "assets" / "index.js").write_text("export {};\n")
# nginx -t on the committed files, unmodified. The only extra is the
# host name that the static proxy_pass needs to resolve.
docker(
"run", "--rm", "--network", cls.network, "--add-host", "backend:127.0.0.1",
"-v", f"{MAIN_CONF}:/etc/nginx/nginx.conf:ro", "-v", f"{APP_CONF}:/etc/nginx/conf.d/default.conf:ro",
"-v", f"{SNIPPETS}:/etc/nginx/snippets:ro", IMAGE, "nginx", "-t",
)
# First copy: the real trusted peer (10.79.0.1) is not this test's
# peer, so X-Forwarded-For must be ignored.
cls.untrusted_port = cls._start_app("untrusted", None, html)
# A separate copy takes the tests that exhaust a rate limit bucket, so
# they cannot make the other tests flaky.
cls.limited_port = cls._start_app("limited", None, html)
peer = cls.request(cls.untrusted_port, "GET", "/api/v1/probe").echo()["real"]
cls.peer = peer
# Second copy: the test's own peer is the trusted edge, as the edge
# tunnel address is in the deployment.
cls.trusted_port = cls._start_app("trusted", peer, html)
@classmethod
def _start_app(cls, label, trusted_peer, html):
conf = APP_CONF.read_text()
if trusted_peer is not None:
edge = read_env(EDGE_ENV)["AWG_EDGE_IP"]
assert f"set_real_ip_from {edge};" in conf
conf = conf.replace(edge, trusted_peer)
path = cls.workdir / f"app-{label}.conf"
path.write_text(conf)
name = f"{cls.prefix}-app-{label}"
cls._run(
name, "-p", "127.0.0.1::8080",
"-v", f"{MAIN_CONF}:/etc/nginx/nginx.conf:ro", "-v", f"{path}:/etc/nginx/conf.d/default.conf:ro",
"-v", f"{SNIPPETS}:/etc/nginx/snippets:ro", "-v", f"{html}:/usr/share/nginx/html:ro", IMAGE,
)
port = cls._port(name)
cls._wait(port)
return port
@staticmethod
def request(port, method, path, headers=None, body=None):
connection = http.client.HTTPConnection("127.0.0.1", port, timeout=10)
connection.request(method, path, body=body, headers=headers or {})
response = connection.getresponse()
data = response.read().decode(errors="replace")
connection.close()
return Response(response.status, response.getheaders(), data)
def get(self, path, **kwargs):
return self.request(self.untrusted_port, "GET", path, **kwargs)
# Allowed URLs
def test_spa_and_deep_link_refresh(self):
for path in ("/", "/candidate/profile", "/verify-email"):
response = self.get(path)
self.assertEqual(response.status, 200, path)
self.assertIn('<div id="root">', response.body, path)
self.assertEqual(self.get("/assets/index.js").status, 200)
self.assertEqual(self.request(self.untrusted_port, "HEAD", "/").status, 200)
self.assertEqual(self.request(self.untrusted_port, "POST", "/").status, 405)
def test_healthz(self):
response = self.get("/healthz")
self.assertEqual((response.status, response.body), (200, "ok\n"))
def test_api_v1_is_proxied(self):
response = self.get("/api/v1/healthz")
self.assertEqual(response.status, 200)
self.assertEqual(response.echo()["uri"], "/api/v1/healthz")
# Denied URLs
def test_denied_paths_are_not_proxied_and_not_the_spa(self):
denied = (
"/metrics", "/metrics/", "/metrics/x", "/readyz", "/debug/pprof/", "/actuator/health",
"/.env", "/.git/config", "/assets/.hidden", "/api", "/api/", "/api/other", "/api/v1",
"/api/v1x", "/telemetry/x",
"/api/v1/../metrics", "/%2e%2e/metrics", "/api/v1/..%2fmetrics", "//metrics", "/%6detrics",
"/api/v1/x/..%2f..%2fmetrics", "/readyz%2f", "/api/V1/x",
)
for path in denied:
with self.subTest(path=path):
response = self.get(path)
# Nginx itself rejects a path that climbs above the root (400).
self.assertIn(response.status, (400, 404))
self.assertNotIn("uri=", response.body)
self.assertNotIn('id="root"', response.body)
def test_telemetry_is_post_only_and_small(self):
self.assertEqual(self.get("/telemetry").status, 405)
response = self.request(self.untrusted_port, "POST", "/telemetry", body=b"{}")
self.assertEqual(response.status, 200)
self.assertEqual(response.echo()["uri"], "/collect")
large = self.request(self.untrusted_port, "POST", "/telemetry", body=b"x" * (2 * 1024 * 1024))
self.assertEqual(large.status, 413)
# Headers, CORS, limits
def test_security_headers_on_spa_api_and_errors(self):
for path in ("/", "/api/v1/healthz", "/metrics"):
response = self.get(path)
with self.subTest(path=path):
for name, value in SECURITY_HEADERS.items():
self.assertEqual(response.headers.get(name), value)
self.assertIn("frame-ancestors 'none'", response.headers["content-security-policy"])
self.assertIn("camera=()", response.headers["permissions-policy"])
def test_no_cors_headers_are_added(self):
headers = {"Origin": "https://evil.example", "Access-Control-Request-Method": "POST"}
for method in ("GET", "OPTIONS"):
response = self.request(self.untrusted_port, method, "/api/v1/healthz", headers=headers)
self.assertNotIn("access-control-allow-origin", response.headers)
# The Origin header itself reaches the backend, which decides on it.
self.assertEqual(self.get("/api/v1/healthz", headers=headers).echo()["acao"], "")
def test_cache_headers_keep_the_security_headers(self):
for path, value in (("/", "no-cache"), ("/candidate/profile", "no-cache"), ("/index.html", "no-cache"),
("/assets/index.js", "public, max-age=31536000, immutable")):
response = self.get(path)
with self.subTest(path=path):
self.assertEqual(response.status, 200)
self.assertEqual(response.headers.get("cache-control"), value)
for name, expected in SECURITY_HEADERS.items():
self.assertEqual(response.headers.get(name), expected)
self.assertIn("frame-ancestors 'none'", response.headers["content-security-policy"])
self.assertEqual(response.headers.get("cross-origin-opener-policy"), "same-origin")
self.assertEqual(response.headers.get("cross-origin-resource-policy"), "same-origin")
self.assertEqual(self.get("/assets/missing.js").status, 404)
def test_redirects_ignore_the_host_header(self):
response = self.get("/assets", headers={"Host": "evil.example"})
self.assertEqual(response.status, 301)
self.assertEqual(response.headers["location"], "/assets/")
def test_inadmissible_upload_is_refused_with_the_contract_problem(self):
accepted = self.request(self.untrusted_port, "POST", "/api/v1/probe", body=b"x" * (512 * 1024))
self.assertEqual(accepted.status, 200)
refused = self.request(self.untrusted_port, "POST", "/api/v1/probe", body=b"x" * (2 * 1024 * 1024))
self.assertEqual(refused.status, 413)
self.assertEqual(refused.headers["content-type"], "application/problem+json")
problem = json.loads(refused.body)
self.assertEqual((problem["code"], problem["status"]), ("payload_too_large", 413))
self.assertEqual(problem["trace_id"], refused.headers["x-request-id"])
self.assertRegex(problem["trace_id"], r"^[A-Za-z0-9._-]+$")
self.assertEqual(refused.headers.get("x-content-type-options"), "nosniff")
def test_rate_limit_answers_with_the_contract_problem(self):
statuses = [self.request(self.limited_port, "GET", "/api/v1/burst").status for _ in range(150)]
self.assertIn(429, statuses)
limited = self.request(self.limited_port, "GET", "/api/v1/burst")
self.assertEqual(limited.status, 429)
self.assertEqual(limited.headers["retry-after"], "1")
self.assertEqual(limited.headers["content-type"], "application/problem+json")
problem = json.loads(limited.body)
self.assertEqual(problem["code"], "rate_limited")
self.assertEqual(problem["trace_id"], limited.headers["x-request-id"])
self.assertEqual(limited.headers.get("x-frame-options"), "DENY")
# Client address chain
def test_untrusted_peer_cannot_choose_its_address_or_bucket(self):
spoofed = {"X-Forwarded-For": "1.2.3.4", "X-Real-IP": "1.2.3.4", "Forwarded": "for=1.2.3.4", "X-Forwarded-Proto": "https"}
echo = self.get("/api/v1/spoof", headers=spoofed).echo()
self.assertEqual(echo["xff"], self.peer)
self.assertEqual(echo["real"], self.peer)
self.assertEqual(echo["fwd"], "")
self.assertEqual(echo["proto"], "http")
# Rotating the header does not escape the limit.
statuses = [
self.request(self.limited_port, "GET", "/api/v1/rotate", headers={"X-Forwarded-For": f"198.51.100.{index % 250}"}).status
for index in range(150)
]
self.assertIn(429, statuses)
def test_trusted_edge_reports_the_client_and_spoofing_to_its_left_is_ignored(self):
edge_view = {"X-Forwarded-For": "203.0.113.9"}
echo = self.request(self.trusted_port, "GET", "/api/v1/edge", headers=edge_view).echo()
self.assertEqual((echo["xff"], echo["real"]), ("203.0.113.9", "203.0.113.9"))
chain = {"X-Forwarded-For": "1.2.3.4, 203.0.113.9", "Forwarded": "for=1.2.3.4", "X-Forwarded-Proto": "https"}
echo = self.request(self.trusted_port, "GET", "/api/v1/edge", headers=chain).echo()
self.assertEqual(echo["xff"], "203.0.113.9")
self.assertEqual(echo["fwd"], "")
self.assertEqual(echo["proto"], "https")
def test_limits_are_per_resolved_client_behind_the_trusted_edge(self):
first = {"X-Forwarded-For": "203.0.113.50"}
statuses = [self.request(self.trusted_port, "GET", "/api/v1/a", headers=first).status for _ in range(150)]
self.assertIn(429, statuses)
self.assertEqual(self.request(self.trusted_port, "GET", "/api/v1/a", headers=first).status, 429)
second = {"X-Forwarded-For": "203.0.113.51"}
self.assertEqual(self.request(self.trusted_port, "GET", "/api/v1/a", headers=second).status, 200)
def test_trusted_proto_claim_only_from_the_edge(self):
claim = {"X-Forwarded-For": "203.0.113.9", "X-Forwarded-Proto": "https"}
self.assertEqual(self.request(self.trusted_port, "GET", "/api/v1/p", headers=claim).echo()["proto"], "https")
def test_ipv6_clients_share_a_bucket_per_slash_64(self):
def status(address):
return self.request(self.trusted_port, "GET", "/api/v1/v6", headers={"X-Forwarded-For": address}).status
statuses = [status("2001:db8:1:2::1") for _ in range(150)]
self.assertIn(429, statuses)
self.assertEqual(status("2001:db8:1:2:aaaa:bbbb:cccc:dddd"), 429)
self.assertEqual(status("2001:db8:1:3::1"), 200)
def test_access_log_records_no_client_address(self):
self.get("/api/v1/logged", headers={"X-Forwarded-For": "203.0.113.77"})
logs = docker("logs", f"{self.prefix}-app-untrusted", check=False)
output = logs.stdout + logs.stderr
self.assertIn("/api/v1/logged", output)
self.assertNotIn("203.0.113.77", output)
self.assertNotIn(self.peer, output)
if __name__ == "__main__":
unittest.main()
+6
View File
@@ -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
View File
@@ -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
+6
View File
@@ -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
View File
@@ -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, а параметры обфускации повышают цену блокировки, но не являются мерой безопасности.
## Сервисы и образы
+1
View File
@@ -19,6 +19,7 @@ FROM ${NGINX_IMAGE}
COPY --from=build /workspace/frontend/dist/ /usr/share/nginx/html/
COPY deploy/nginx/nginx.conf /etc/nginx/nginx.conf
COPY deploy/nginx/conf.d/app.conf /etc/nginx/conf.d/default.conf
COPY deploy/nginx/snippets/ /etc/nginx/snippets/
EXPOSE 8080
USER 101
@@ -34,6 +34,7 @@ monitoring_started=0
core() {
APP_PROJECT="$project" APP_NETWORK="$app_network" APP_STORAGE_NETWORK="$storage_network" APP_HTTP_PORT="$port" \
APP_SUBNET=172.29.83.0/24 APP_FRONTEND_IP=172.29.83.10 \
APP_PUBLIC_URL="http://localhost:$port" EMAIL_PROVIDER=resend RESEND_API_KEY=re_placeholder_not_a_key \
EMAIL_ACCOUNT=metrics-check docker compose --env-file "$env_file" -p "$project" -f "$core_file" "$@"
}