feat(deploy): restrict the public perimeter and resolve the client address
This commit is contained in:
1 parent
e52ffe7bcb
commit
57174dffba
25 files changed
+1224
-25
No files matched your search
+8
-2
@@ -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
|
||||
|
||||
|
||||
@@ -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).
|
||||
|
||||
|
||||
@@ -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-набор).
|
||||
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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
@@ -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
@@ -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;
|
||||
@@ -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" \
|
||||
|
||||
@@ -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" \
|
||||
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user