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
@@ -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