"""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] # The example file has no usable IDENTITY_KEY_SECRET, which Compose requires. environment = dict( os.environ, APP_PROJECT=project, APP_NETWORK=f"{project}_default", IDENTITY_KEY_SECRET="render-only-identity-key-secret" ) 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 = '
\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('