From c70972b32c4c1d0eebccd69d44a402d058bd676b Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 12:15:14 -0800 Subject: [PATCH 01/45] feat: add guardrail settings with auth-aware defaults Caps, quota limits, reaper timings, SSRF and allowlist switches, and the LLM benchmark flag, all configurable from the environment. The allowlist and LLM flag default on/off according to AUTH_ENABLED. Co-Authored-By: Claude Sonnet 5.5 --- backend/app/core/config.py | 69 ++++++++++++++++++++++++ backend/tests/test_guardrail_settings.py | 42 +++++++++++++++ 2 files changed, 111 insertions(+) create mode 100644 backend/tests/test_guardrail_settings.py diff --git a/backend/app/core/config.py b/backend/app/core/config.py index e6c2d87..fe20b28 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -43,6 +43,75 @@ class Settings(BaseSettings): # right of X-Forwarded-For (entries to the left are client-controlled). trusted_proxy_hops: int = 0 + # --- Guardrails (hosted demo) -------------------------------------------- + # Hard caps, enforced server-side in the request schemas. They apply even + # when auth is off; raise them in .env for local load testing. + max_num_requests: int = 500 + max_concurrency: int = 20 + max_request_timeout_s: float = 10.0 + # Wall-clock limit for one whole run (asyncio.wait_for around the engine). + run_wall_clock_limit_s: float = 60.0 + # Quotas, computed from the runs table so they survive restarts. Enforced + # only when auth is enabled (see quotas_enforced): locally there is no code + # to attribute usage to and the limits would only get in the way. + max_concurrent_runs: int = 2 + max_active_runs_per_code: int = 1 + # Daily budgets are sums of num_requests per UTC day. + daily_budget_per_code: int = 2_000 + daily_budget_global: int = 10_000 + # Stale-run reaper: a run still pending/running after the wall-clock limit + # plus this grace period is marked failed (its worker died or was restarted). + reaper_grace_seconds: float = 120.0 + reaper_interval_seconds: float = 60.0 + + # SSRF: refuse targets that are, or resolve to, non-public addresses. + # Fail closed: keep this true on any hosted deployment. Set it to false only + # for local development against localhost services. + block_private_targets: bool = True + dns_resolve_timeout_s: float = 5.0 + # Target allowlist: exact hostnames only (no wildcards, no suffix matching), + # comma-separated. A plain string, not list[str], so ALLOWED_TARGET_HOSTS can + # be written as a comma-separated value instead of JSON. SSRF checks still + # apply to allowlisted hosts. Enforcement defaults to ON when auth is on; + # TARGET_ALLOWLIST_ENABLED overrides it either way. + allowed_target_hosts: str = "httpbin.org" + target_allowlist_enabled: bool | None = None + # LLM benchmark route. Defaults to OFF when auth is on (it forwards a + # caller-supplied API key to a caller-supplied endpoint); LLM_BENCHMARK_ENABLED + # overrides it either way. + llm_benchmark_enabled: bool | None = None + + # /health database probe timeout. + health_db_timeout_s: float = 3.0 + + # Each flag below is resolved at call time (not import time) so tests and + # operators see the current auth_enabled value. + @property + def allowlist_enforced(self) -> bool: + if self.target_allowlist_enabled is not None: + return self.target_allowlist_enabled + return self.auth_enabled + + @property + def quotas_enforced(self) -> bool: + return self.auth_enabled + + @property + def llm_benchmark_active(self) -> bool: + if self.llm_benchmark_enabled is not None: + return self.llm_benchmark_enabled + return not self.auth_enabled + + @property + def allowed_target_host_list(self) -> list[str]: + """Normalised allowlist entries: lowercase, no trailing dot, no blanks.""" + hosts: list[str] = [] + for raw in self.allowed_target_hosts.split(","): + entry = raw.strip().lower().rstrip(".") + if entry: + hosts.append(entry) + return hosts + # Single instance imported everywhere settings = Settings() diff --git a/backend/tests/test_guardrail_settings.py b/backend/tests/test_guardrail_settings.py new file mode 100644 index 0000000..10886c0 --- /dev/null +++ b/backend/tests/test_guardrail_settings.py @@ -0,0 +1,42 @@ +from app.core.config import Settings + + +def make(**kwargs) -> Settings: + # _env_file=None keeps a developer's local .env out of these tests. + return Settings(_env_file=None, **kwargs) + + +def test_defaults_match_the_agreed_caps(): + s = make() + assert s.max_num_requests == 500 + assert s.max_concurrency == 20 + assert s.max_request_timeout_s == 10.0 + assert s.run_wall_clock_limit_s == 60.0 + assert s.max_concurrent_runs == 2 + assert s.max_active_runs_per_code == 1 + assert s.block_private_targets is True + + +def test_allowlist_follows_auth_unless_overridden(): + assert make(auth_enabled=True).allowlist_enforced is True + assert make(auth_enabled=False).allowlist_enforced is False + assert make(auth_enabled=True, target_allowlist_enabled=False).allowlist_enforced is False + assert make(auth_enabled=False, target_allowlist_enabled=True).allowlist_enforced is True + + +def test_llm_benchmark_is_off_when_auth_is_on_unless_overridden(): + assert make(auth_enabled=True).llm_benchmark_active is False + assert make(auth_enabled=False).llm_benchmark_active is True + assert make(auth_enabled=True, llm_benchmark_enabled=True).llm_benchmark_active is True + assert make(auth_enabled=False, llm_benchmark_enabled=False).llm_benchmark_active is False + + +def test_quotas_follow_auth(): + assert make(auth_enabled=True).quotas_enforced is True + assert make(auth_enabled=False).quotas_enforced is False + + +def test_allowed_hosts_are_normalised_from_a_comma_separated_string(): + s = make(allowed_target_hosts=" HTTPBIN.org, demo.example.com. ,,") + assert s.allowed_target_host_list == ["httpbin.org", "demo.example.com"] + assert make(allowed_target_hosts="").allowed_target_host_list == [] From a028a6153ac7874339b643b9bcde86e541bfab14 Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 12:17:40 -0800 Subject: [PATCH 02/45] feat: add SSRF guard for benchmark targets Reject non-http(s) schemes, credentials, malformed URLs, and any target that is or resolves to a loopback, private, link-local (incl. 169.254.169.254), CGNAT, multicast, unspecified or reserved address, plus the IPv6 equivalents (::1, fc00::/7, fe80::/10, IPv4-mapped, NAT64 and 6to4 with embedded private IPv4). Legacy decimal, octal and hex IPv4 spellings are decoded before the check, and one bad DNS record rejects the whole answer. Tests use a fake DNS fixture so they never touch the network. Co-Authored-By: Claude Sonnet 5.5 --- backend/app/services/ssrf.py | 248 +++++++++++++++++++++++++++++++++++ backend/tests/conftest.py | 36 +++++ backend/tests/test_ssrf.py | 205 +++++++++++++++++++++++++++++ 3 files changed, 489 insertions(+) create mode 100644 backend/app/services/ssrf.py create mode 100644 backend/tests/test_ssrf.py diff --git a/backend/app/services/ssrf.py b/backend/app/services/ssrf.py new file mode 100644 index 0000000..bd8891f --- /dev/null +++ b/backend/app/services/ssrf.py @@ -0,0 +1,248 @@ +""" +SSRF guard for benchmark targets. + +The backend sends HTTP requests to a URL chosen by the caller, so it must not +be usable to reach the host's own services, the private network, or the cloud +metadata endpoint (169.254.169.254). + +Defence in depth, in order: + 1. parse_target() rejects odd schemes, credentials and malformed URLs. It uses + httpx's own URL parser, the same one the benchmark client uses, so the host + we check is the host that gets connected to (no parser differential). + 2. resolve_target() resolves the name and rejects the target if ANY returned + address is non-public. Literal IPs in legacy forms (decimal 2130706433, + octal 0177.0.0.1, hex 0x7f.1, short 127.1) are decoded before the check. + 3. The addresses it returns are pinned for the actual connections (see + app/services/pinned.py), so a second DNS answer cannot redirect traffic + after the check (DNS rebinding). + +Error messages are meant for the caller: they name the category (loopback, +private network, ...) but never the resolved address, so the endpoint cannot +be used to map internal DNS. +""" +import asyncio +import ipaddress +import socket +from dataclasses import dataclass + +import httpx + +from app.core.config import settings + +_MAX_URL_LENGTH = 2048 + + +class TargetRejected(Exception): + """The target URL is not allowed. str(exc) is safe to show to the caller.""" + + +# (network, label). Anything inside one of these is never a valid public target. +_V4_DENY_SPEC = [ + ("0.0.0.0/8", "unspecified or this-network address"), + ("10.0.0.0/8", "private network"), + ("100.64.0.0/10", "carrier-grade NAT"), + ("127.0.0.0/8", "loopback"), + ("169.254.0.0/16", "link-local or cloud metadata"), + ("172.16.0.0/12", "private network"), + ("192.0.0.0/24", "reserved"), + ("192.0.2.0/24", "documentation range"), + ("192.88.99.0/24", "reserved"), + ("192.168.0.0/16", "private network"), + ("198.18.0.0/15", "benchmarking range"), + ("198.51.100.0/24", "documentation range"), + ("203.0.113.0/24", "documentation range"), + ("224.0.0.0/4", "multicast"), + ("240.0.0.0/4", "reserved"), +] +_V6_DENY_SPEC = [ + # ::/96 covers the unspecified address (::), loopback (::1) and the + # deprecated IPv4-compatible form (::a.b.c.d). + ("::/96", "unspecified, loopback or IPv4-compatible address"), + ("::ffff:0:0/96", "IPv4-mapped IPv6 address"), + ("64:ff9b:1::/48", "reserved"), + ("100::/64", "reserved"), + ("2001::/23", "reserved (includes Teredo)"), + ("2001:db8::/32", "documentation range"), + ("3fff::/20", "documentation range"), + ("fc00::/7", "private network"), + ("fe80::/10", "link-local"), + ("fec0::/10", "reserved"), + ("ff00::/8", "multicast"), +] +_NAT64 = ipaddress.ip_network("64:ff9b::/96") + + +def _compile(spec: list[tuple[str, str]]) -> list[tuple[ipaddress._BaseNetwork, str]]: + compiled = [] + for cidr, label in spec: + compiled.append((ipaddress.ip_network(cidr), label)) + return compiled + + +_V4_DENY = _compile(_V4_DENY_SPEC) +_V6_DENY = _compile(_V6_DENY_SPEC) + + +def blocked_reason(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> str | None: + """Return a human label if the address must not be contacted, else None.""" + if isinstance(ip, ipaddress.IPv4Address): + for network, label in _V4_DENY: + if ip in network: + return label + return None + + for network, label in _V6_DENY: + if ip in network: + return label + + # Addresses that embed an IPv4 address: judge the embedded address, so + # 64:ff9b::7f00:1 (NAT64) and 2002:7f00:1:: (6to4) cannot smuggle 127.0.0.1. + embedded: ipaddress.IPv4Address | None = None + if ip in _NAT64: + embedded = ipaddress.IPv4Address(int(ip) & 0xFFFFFFFF) + elif ip.sixtofour is not None: + embedded = ip.sixtofour + if embedded is not None: + reason = blocked_reason(embedded) + if reason is not None: + return reason + return None + + +def _parse_ip_literal(host: str) -> ipaddress.IPv4Address | ipaddress.IPv6Address | None: + """ + Decode a host that is an IP literal, including the legacy IPv4 spellings + that libc resolvers accept but ipaddress does not (decimal, octal, hex and + short forms). Returns None for ordinary hostnames. + """ + try: + return ipaddress.ip_address(host) + except ValueError: + pass + # inet_aton is the same parser getaddrinfo falls back to, so whatever it + # accepts is what the connection layer would also treat as an address. + try: + packed = socket.inet_aton(host) + except OSError: + return None + return ipaddress.IPv4Address(packed) + + +@dataclass(frozen=True) +class ParsedTarget: + url: str + scheme: str + host: str # lowercase, IDNA (punycode) form, no brackets + port: int + + +@dataclass(frozen=True) +class ResolvedTarget: + url: str + scheme: str + host: str + port: int + # Validated addresses to pin the connections to, in connection order. + addresses: list[str] + + +def parse_target(url: str) -> ParsedTarget: + if not isinstance(url, str) or not url: + raise TargetRejected("Target URL is empty") + if len(url) > _MAX_URL_LENGTH: + raise TargetRejected("Target URL is too long") + # Whitespace, control characters and backslashes are where URL parsers + # disagree with each other; none has a place in a benchmark target. + for ch in url: + if ord(ch) <= 0x20 or ord(ch) == 0x7F or ch == "\\": + raise TargetRejected("Target URL contains invalid characters") + + try: + parsed = httpx.URL(url) + except (httpx.InvalidURL, ValueError): + raise TargetRejected("Target URL is not valid") + + scheme = parsed.scheme.lower() + if scheme not in ("http", "https"): + raise TargetRejected("Only http and https targets are allowed") + if parsed.userinfo: + raise TargetRejected("Target URL must not contain credentials") + + try: + host = parsed.raw_host.decode("ascii").lower() + except UnicodeDecodeError: + raise TargetRejected("Target URL is not valid") + if not host or "%" in host: + # "%" would be an IPv6 zone id or an escape inside the host. + raise TargetRejected("Target URL is not valid") + host = host.rstrip(".") + if not host: + raise TargetRejected("Target URL is not valid") + + port = parsed.port + if port is None: + port = 443 if scheme == "https" else 80 + if port < 1 or port > 65535: + raise TargetRejected("Target URL has an invalid port") + return ParsedTarget(url=url, scheme=scheme, host=host, port=port) + + +async def _resolve_host(host: str, port: int) -> list[str]: + """DNS lookup; returns address strings. Separate function so tests can stub it.""" + loop = asyncio.get_running_loop() + infos = await loop.getaddrinfo(host, port, type=socket.SOCK_STREAM) + addresses: list[str] = [] + for info in infos: + address = info[4][0] + # IPv6 results can carry a scope id ("fe80::1%en0"); drop it. + address = address.split("%", 1)[0] + if address not in addresses: + addresses.append(address) + return addresses + + +async def resolve_target(parsed: ParsedTarget) -> ResolvedTarget: + """Resolve the host and reject non-public destinations.""" + literal = _parse_ip_literal(parsed.host) + if literal is not None: + addresses = [str(literal)] + else: + try: + addresses = await asyncio.wait_for( + _resolve_host(parsed.host, parsed.port), + timeout=settings.dns_resolve_timeout_s, + ) + except asyncio.TimeoutError: + raise TargetRejected("Target host lookup timed out") + except OSError: + raise TargetRejected("Target host could not be resolved") + if not addresses: + raise TargetRejected("Target host could not be resolved") + + validated: list[str] = [] + for address in addresses: + try: + ip = ipaddress.ip_address(address) + except ValueError: + raise TargetRejected("Target host resolved to an invalid address") + if settings.block_private_targets: + reason = blocked_reason(ip) + if reason is not None: + # Any one bad record rejects the whole target: a name that + # also points at an internal address is not a safe target. + raise TargetRejected(f"Target address is not allowed ({reason})") + validated.append(str(ip)) + + return ResolvedTarget( + url=parsed.url, + scheme=parsed.scheme, + host=parsed.host, + port=parsed.port, + addresses=validated, + ) + + +async def validate_target(url: str) -> ResolvedTarget: + """Parse, resolve and check one target URL. Raises TargetRejected.""" + parsed = parse_target(url) + return await resolve_target(parsed) diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 5d1dd95..3d3b0a0 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -1,4 +1,5 @@ import os +import socket import tempfile # Test configuration must be in the environment BEFORE app modules import, @@ -48,6 +49,41 @@ async def _no_index(**kwargs): login_limiter._global.clear() +# Public-looking addresses for tests that need a target to resolve. +DEFAULT_DNS = { + "httpbin.org": ["93.184.216.34"], + "example.com": ["93.184.216.34"], +} + + +class FakeDNS: + """hostname -> addresses table; `calls` records every lookup made.""" + + def __init__(self) -> None: + self.table: dict[str, list[str]] = dict(DEFAULT_DNS) + self.calls: list[str] = [] + + def __setitem__(self, host: str, addresses: list[str]) -> None: + self.table[host] = addresses + + async def resolve(self, host: str, port: int) -> list[str]: + self.calls.append(host) + if host not in self.table: + raise socket.gaierror("name not known") + return list(self.table[host]) + + +@pytest.fixture(autouse=True) +def dns(monkeypatch): + """ + Replace real DNS so tests never touch the network and can make any name + resolve to any address. Unknown names fail to resolve, like NXDOMAIN. + """ + fake = FakeDNS() + monkeypatch.setattr("app.services.ssrf._resolve_host", fake.resolve) + return fake + + @pytest_asyncio.fixture(autouse=True) async def _fresh_schema(): # Each test runs on its own event loop; pooled asyncpg connections are bound diff --git a/backend/tests/test_ssrf.py b/backend/tests/test_ssrf.py new file mode 100644 index 0000000..962a22f --- /dev/null +++ b/backend/tests/test_ssrf.py @@ -0,0 +1,205 @@ +import asyncio +import ipaddress +import socket + +import pytest + +from app.core.config import settings +from app.services import ssrf +from app.services.ssrf import TargetRejected, blocked_reason, parse_target, validate_target + +# Captured at import time, before the autouse `dns` fixture stubs the module attribute. +REAL_RESOLVE_HOST = ssrf._resolve_host + +# --- address classification --------------------------------------------------- + +BLOCKED_ADDRESSES = [ + "127.0.0.1", "127.255.255.254", "10.0.0.1", "10.255.255.255", "172.16.0.1", + "172.31.255.255", "192.168.0.1", "192.168.255.255", "169.254.169.254", + "169.254.170.2", "100.64.0.1", "100.127.255.255", "0.0.0.0", "0.1.2.3", + "224.0.0.1", "239.255.255.250", "240.0.0.1", "255.255.255.255", + "192.0.0.8", "198.18.0.1", "192.0.2.1", "198.51.100.7", "203.0.113.9", + "::", "::1", "::2", "::ffff:127.0.0.1", "::ffff:10.0.0.1", "::ffff:8.8.8.8", + "fc00::1", "fd12:3456:789a::1", "fe80::1", "febf::1", "fec0::1", "ff02::1", + "ff05::2", "2001:db8::1", "2001::1", "100::1", + "64:ff9b::7f00:1", "64:ff9b::a00:1", "64:ff9b::a9fe:a9fe", + "2002:7f00:1::", "2002:a00:1::", "2002:a9fe:a9fe::", +] + +ALLOWED_ADDRESSES = [ + "8.8.8.8", "1.1.1.1", "93.184.216.34", "172.15.255.255", "172.32.0.1", + "100.63.255.255", "100.128.0.1", "169.253.0.1", "126.255.255.255", + "2606:4700:4700::1111", "2a00:1450:4001:81b::200e", "64:ff9b::808:808", +] + + +def test_blocked_addresses_are_all_blocked(): + for text in BLOCKED_ADDRESSES: + assert blocked_reason(ipaddress.ip_address(text)) is not None, text + + +def test_public_addresses_are_allowed(): + for text in ALLOWED_ADDRESSES: + assert blocked_reason(ipaddress.ip_address(text)) is None, text + + +def test_metadata_address_has_a_readable_label(): + assert "metadata" in blocked_reason(ipaddress.ip_address("169.254.169.254")) + assert blocked_reason(ipaddress.ip_address("127.0.0.1")) == "loopback" + + +# --- URL parsing: schemes and malformed input --------------------------------- + +BAD_SCHEMES = [ + "ftp://example.com/", "file:///etc/passwd", "gopher://example.com/", + "ws://example.com/", "wss://example.com/", "data:text/plain,hi", + "javascript:alert(1)", "dict://example.com:11211/", "ldap://example.com/", + "//example.com/", "example.com", "", +] + + +def test_non_http_schemes_are_rejected(): + for url in BAD_SCHEMES: + with pytest.raises(TargetRejected): + parse_target(url) + + +MALFORMED = [ + "http://exa mple.com/", "http://example.com/\r\nX-Evil: 1", "http://example.com/\x00", + "http://127.0.0.1\\@example.com/", "http://user:pass@example.com/", + "http://user@example.com/", "http://example.com:0/", "http://example.com:99999/", + "http://[fe80::1%25eth0]/", "http://" + "a" * 3000 + ".com/", "http:///path", +] + + +def test_malformed_urls_and_credentials_are_rejected(): + for url in MALFORMED: + with pytest.raises(TargetRejected): + parse_target(url) + + +def test_valid_urls_are_normalised(): + parsed = parse_target("HTTPS://Example.COM./p?q=1") + assert (parsed.scheme, parsed.host, parsed.port) == ("https", "example.com", 443) + assert parse_target("http://example.com:8080/").port == 8080 + # Fragment tricks do not change the host that is checked and connected to. + assert parse_target("http://example.com#@127.0.0.1/").host == "example.com" + + +# --- literal IPs in every encoding -------------------------------------------- + +LITERAL_BLOCKED_URLS = [ + "http://127.0.0.1/", "http://127.0.0.1:8000/", "https://127.0.0.1/", + "http://2130706433/", # decimal + "http://017700000001/", # octal, single number + "http://0x7f000001/", # hex, single number + "http://0x7f.0.0.1/", # hex octet + "http://127.1/", # short form + "http://127.0.1/", + "http://0/", "http://0.0.0.0/", + "http://localhost/", # resolved through the (fake) DNS below + "http://[::1]/", "http://[0:0:0:0:0:0:0:1]/", "http://[::]/", + "http://[::ffff:127.0.0.1]/", "http://[::ffff:7f00:1]/", "http://[::ffff:a00:1]/", + "http://[fc00::1]/", "http://[fd00::1]/", "http://[fe80::1]/", + "http://[64:ff9b::7f00:1]/", "http://[2002:7f00:1::]/", + "http://10.0.0.1/", "http://10.1.2.3:9200/", "http://172.16.5.4/", + "http://172.31.0.1/", "http://192.168.1.1/", + "http://169.254.169.254/latest/meta-data/", "http://169.254.169.254./", + "http://2852039166/", # 169.254.169.254 as a decimal number + "http://0xa9fea9fe/", + "http://100.64.0.1/", "http://100.100.100.200/", + "http://224.0.0.1/", "http://239.255.255.250/", "http://255.255.255.255/", + "http://[ff02::1]/", +] + + +async def test_private_and_special_targets_are_rejected_in_every_encoding(dns): + dns["localhost"] = ["127.0.0.1", "::1"] + for url in LITERAL_BLOCKED_URLS: + with pytest.raises(TargetRejected): + await validate_target(url) + + +async def test_literal_ip_rejections_never_depend_on_dns(dns): + # Literal addresses are judged without a lookup, so there is nothing to spoof. + for url in ["http://2130706433/", "http://[::1]/", "http://169.254.169.254/"]: + with pytest.raises(TargetRejected): + await validate_target(url) + assert dns.calls == [] + + +async def test_rejection_message_names_the_category_but_not_the_address(dns): + with pytest.raises(TargetRejected) as exc: + await validate_target("http://169.254.169.254/") + assert "metadata" in str(exc.value) + assert "169.254" not in str(exc.value) + + +async def test_public_literals_and_hostnames_are_accepted(dns): + target = await validate_target("https://8.8.8.8/dns") + assert target.addresses == ["8.8.8.8"] + target = await validate_target("http://example.com:8080/x") + assert (target.host, target.port, target.addresses) == ("example.com", 8080, ["93.184.216.34"]) + target = await validate_target("http://[2606:4700:4700::1111]/") + assert target.addresses == ["2606:4700:4700::1111"] + + +# --- hostnames that resolve to bad addresses ----------------------------------- + +async def test_hostname_resolving_to_private_ip_is_rejected(dns): + for address in ["10.0.0.5", "192.168.1.10", "172.20.0.2", "127.0.0.1", "169.254.169.254", + "100.64.0.9", "::1", "fd00::5", "fe80::1", "::ffff:10.0.0.5"]: + dns["internal.example.test"] = [address] + with pytest.raises(TargetRejected): + await validate_target("http://internal.example.test/") + + +async def test_one_bad_record_rejects_a_mixed_answer(dns): + dns["mixed.example.test"] = ["93.184.216.34", "10.0.0.5"] + with pytest.raises(TargetRejected): + await validate_target("http://mixed.example.test/") + dns["mixed.example.test"] = ["10.0.0.5", "93.184.216.34"] + with pytest.raises(TargetRejected): + await validate_target("http://mixed.example.test/") + + +async def test_unresolvable_and_empty_answers_are_rejected(dns): + with pytest.raises(TargetRejected): + await validate_target("http://nxdomain.example.test/") + dns["empty.example.test"] = [] + with pytest.raises(TargetRejected): + await validate_target("http://empty.example.test/") + + +async def test_slow_dns_times_out(monkeypatch): + async def _hang(host, port): + await asyncio.sleep(30) + return ["93.184.216.34"] + + monkeypatch.setattr("app.services.ssrf._resolve_host", _hang) + monkeypatch.setattr(settings, "dns_resolve_timeout_s", 0.05) + with pytest.raises(TargetRejected) as exc: + await validate_target("http://slow.example.test/") + assert "timed out" in str(exc.value) + + +async def test_every_returned_address_is_pinned_in_order(dns): + dns["multi.example.test"] = ["93.184.216.34", "2606:4700:4700::1111"] + target = await validate_target("https://multi.example.test/") + assert target.addresses == ["93.184.216.34", "2606:4700:4700::1111"] + + +async def test_private_targets_can_be_allowed_for_local_development(dns, monkeypatch): + monkeypatch.setattr(settings, "block_private_targets", False) + dns["localhost"] = ["127.0.0.1"] + target = await validate_target("http://localhost:8000/") + assert target.addresses == ["127.0.0.1"] + # The scheme rules still apply. + with pytest.raises(TargetRejected): + await validate_target("file:///etc/passwd") + + +def test_real_resolver_handles_a_literal_without_the_network(): + # Smoke test of the unstubbed code path using an address that needs no DNS. + addresses = asyncio.run(REAL_RESOLVE_HOST("127.0.0.1", 80)) + assert addresses == ["127.0.0.1"] From 0b521ef86b6a037f36b81e1219e69b49db626262 Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 12:18:18 -0800 Subject: [PATCH 03/45] feat: add pinned-IP httpx transport for benchmark clients Connections go only to addresses validated by the SSRF check, so a second DNS answer cannot rebind the name to an internal host. The Host header, TLS SNI and certificate verification still use the original hostname. Redirects stay off and environment proxies are ignored. The transport refuses to start if httpx internals change, instead of silently going unpinned. Co-Authored-By: Claude Sonnet 5.5 --- backend/app/services/pinned.py | 121 ++++++++++++++++ backend/tests/test_pinned_transport.py | 183 +++++++++++++++++++++++++ 2 files changed, 304 insertions(+) create mode 100644 backend/app/services/pinned.py create mode 100644 backend/tests/test_pinned_transport.py diff --git a/backend/app/services/pinned.py b/backend/app/services/pinned.py new file mode 100644 index 0000000..27230c8 --- /dev/null +++ b/backend/app/services/pinned.py @@ -0,0 +1,121 @@ +""" +HTTP transport that connects only to pre-validated IP addresses. + +The SSRF check resolves a hostname once and decides whether it is safe. If the +HTTP client then resolved the name again, an attacker-controlled DNS server +could answer differently the second time (DNS rebinding) and point the +connection at an internal address. This transport removes the second lookup: +the TCP connection goes to the pinned address, while everything above TCP still +uses the original hostname, so + + - the Host header is the hostname the caller gave, + - TLS SNI and certificate verification use that hostname (httpcore passes the + request's host to start_tls as server_hostname), + - connection pooling stays keyed by the hostname. + +Only hostnames present in `pins` can be connected to at all; anything else +(including a redirect target, though redirects are off) fails to connect. +""" +import httpcore +import httpx + +from app.core.config import settings + + +class PinnedBackend(httpcore.AsyncNetworkBackend): + def __init__( + self, + pins: dict[str, list[str]], + inner: httpcore.AsyncNetworkBackend | None = None, + ) -> None: + self._pins: dict[str, list[str]] = {} + for host, addresses in pins.items(): + self._pins[host.lower()] = list(addresses) + self._inner = inner if inner is not None else httpcore.AnyIOBackend() + + async def connect_tcp( + self, + host: str, + port: int, + timeout: float | None = None, + local_address: str | None = None, + socket_options=None, + ): + addresses = self._pins.get(host.lower()) + if not addresses: + raise httpcore.ConnectError("Host is not a pinned benchmark target") + last_error: Exception | None = None + # Try each validated address in order, like a normal multi-record connect. + for address in addresses: + try: + return await self._inner.connect_tcp( + address, + port, + timeout=timeout, + local_address=local_address, + socket_options=socket_options, + ) + except (httpcore.ConnectError, httpcore.ConnectTimeout) as exc: + last_error = exc + assert last_error is not None + raise last_error + + async def connect_unix_socket(self, path: str, timeout: float | None = None, socket_options=None): + raise httpcore.ConnectError("Unix sockets are not allowed") + + async def sleep(self, seconds: float) -> None: + await self._inner.sleep(seconds) + + +class PinnedTransport(httpx.AsyncHTTPTransport): + """AsyncHTTPTransport whose connection pool uses PinnedBackend.""" + + def __init__( + self, + pins: dict[str, list[str]], + limits: httpx.Limits | None = None, + backend: httpcore.AsyncNetworkBackend | None = None, + ) -> None: + limits = limits if limits is not None else httpx.Limits() + super().__init__(verify=True, limits=limits, retries=0, http2=False) + # httpx has no public hook for the network backend, so swap the pool it + # built. Fail closed if a future httpx moves it: an unpinned transport + # would silently bring back the DNS-rebinding hole. + if not isinstance(getattr(self, "_pool", None), httpcore.AsyncConnectionPool): + raise RuntimeError("Unsupported httpx version: cannot pin connections") + self._pool = httpcore.AsyncConnectionPool( + ssl_context=httpx.create_ssl_context(verify=True), + max_connections=limits.max_connections, + max_keepalive_connections=limits.max_keepalive_connections, + keepalive_expiry=limits.keepalive_expiry, + http1=True, + http2=False, + retries=0, + network_backend=PinnedBackend(pins, inner=backend), + ) + + +def build_pinned_client( + pins: dict[str, list[str]], + *, + headers: dict | None = None, + timeout: float, + max_connections: int, + backend: httpcore.AsyncNetworkBackend | None = None, +) -> httpx.AsyncClient: + """ + The one way the backend creates a client for a user-supplied target: + pinned addresses, no redirects, no environment proxies. + """ + transport = PinnedTransport( + pins, + limits=httpx.Limits(max_connections=max_connections, max_keepalive_connections=max_connections), + backend=backend, + ) + return httpx.AsyncClient( + transport=transport, + headers=headers or {}, + timeout=timeout, + follow_redirects=False, # a 3xx must not lead to an unchecked host + trust_env=False, # no HTTP(S)_PROXY from the environment + ) diff --git a/backend/tests/test_pinned_transport.py b/backend/tests/test_pinned_transport.py new file mode 100644 index 0000000..44ad6b1 --- /dev/null +++ b/backend/tests/test_pinned_transport.py @@ -0,0 +1,183 @@ +import asyncio +import socket + +import httpcore +import httpx +import pytest + +from app.services.pinned import PinnedBackend, PinnedTransport, build_pinned_client + + +async def _serve(handler): + server = await asyncio.start_server(handler, "127.0.0.1", 0) + port = server.sockets[0].getsockname()[1] + return server, port + + +async def _echo_host(reader, writer): + head = await reader.readuntil(b"\r\n\r\n") + host_line = b"" + for line in head.split(b"\r\n"): + if line.lower().startswith(b"host:"): + host_line = line + body = host_line + writer.write( + b"HTTP/1.1 200 OK\r\nContent-Length: " + str(len(body)).encode() + b"\r\nConnection: close\r\n\r\n" + body + ) + await writer.drain() + writer.close() + + +async def test_connects_to_the_pinned_address_and_keeps_the_original_host_header(monkeypatch): + server, port = await _serve(_echo_host) + + def _no_dns(*args, **kwargs): + raise AssertionError("the pinned transport must not resolve names") + + monkeypatch.setattr(socket, "getaddrinfo", _no_dns) + async with server: + # "pinned.example.test" does not exist in DNS; only the pin makes this work. + async with build_pinned_client( + {"pinned.example.test": ["127.0.0.1"]}, timeout=5, max_connections=2 + ) as client: + resp = await client.get(f"http://pinned.example.test:{port}/x") + assert resp.status_code == 200 + assert resp.text.strip().lower() == f"host: pinned.example.test:{port}" + + +async def test_unpinned_hosts_cannot_be_connected_to(): + server, port = await _serve(_echo_host) + async with server: + async with build_pinned_client( + {"pinned.example.test": ["127.0.0.1"]}, timeout=5, max_connections=2 + ) as client: + # Same listening port, different name: no pin, so no connection. + with pytest.raises(httpx.ConnectError): + await client.get(f"http://other.example.test:{port}/") + # An IP literal that is not pinned is refused too. + with pytest.raises(httpx.ConnectError): + await client.get(f"http://127.0.0.1:{port}/") + + +async def test_rebinding_cannot_redirect_a_pinned_name(monkeypatch): + """Even if DNS now says 'internal', the pinned (validated) address is used.""" + server, port = await _serve(_echo_host) + resolved: list[str] = [] + + def _evil_dns(host, *args, **kwargs): + resolved.append(host) + return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("10.0.0.5", 80))] + + monkeypatch.setattr(socket, "getaddrinfo", _evil_dns) + async with server: + async with build_pinned_client( + {"rebind.example.test": ["127.0.0.1"]}, timeout=5, max_connections=2 + ) as client: + resp = await client.get(f"http://rebind.example.test:{port}/") + assert resp.status_code == 200 + assert resolved == [] + + +async def test_redirects_are_not_followed(): + async def _redirect(reader, writer): + await reader.readuntil(b"\r\n\r\n") + writer.write( + b"HTTP/1.1 302 Found\r\nLocation: http://169.254.169.254/\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + ) + await writer.drain() + writer.close() + + server, port = await _serve(_redirect) + async with server: + async with build_pinned_client( + {"redir.example.test": ["127.0.0.1"]}, timeout=5, max_connections=2 + ) as client: + resp = await client.get(f"http://redir.example.test:{port}/") + assert resp.status_code == 302 + assert resp.headers["location"] == "http://169.254.169.254/" + + +async def test_environment_proxies_are_ignored(monkeypatch): + monkeypatch.setenv("HTTP_PROXY", "http://127.0.0.1:9") + monkeypatch.setenv("HTTPS_PROXY", "http://127.0.0.1:9") + server, port = await _serve(_echo_host) + async with server: + async with build_pinned_client( + {"proxy.example.test": ["127.0.0.1"]}, timeout=5, max_connections=2 + ) as client: + resp = await client.get(f"http://proxy.example.test:{port}/") + assert resp.status_code == 200 + + +class _RecordingStream(httpcore.AsyncNetworkStream): + def __init__(self, log): + self._log = log + + async def read(self, max_bytes, timeout=None): + return b"" + + async def write(self, buffer, timeout=None): + return None + + async def aclose(self): + return None + + async def start_tls(self, ssl_context, server_hostname=None, timeout=None): + self._log["server_hostname"] = server_hostname + raise httpcore.ConnectError("stop after recording the TLS server name") + + def get_extra_info(self, info): + return None + + +class _RecordingBackend(httpcore.AsyncNetworkBackend): + def __init__(self): + self.log = {} + + async def connect_tcp(self, host, port, timeout=None, local_address=None, socket_options=None): + self.log["connected_to"] = host + return _RecordingStream(self.log) + + async def connect_unix_socket(self, path, timeout=None, socket_options=None): + raise AssertionError("unix sockets must never be used") + + async def sleep(self, seconds): + return None + + +async def test_tls_uses_the_hostname_for_sni_while_connecting_to_the_pinned_ip(): + backend = _RecordingBackend() + async with build_pinned_client( + {"secure.example.test": ["93.184.216.34"]}, timeout=5, max_connections=2, backend=backend + ) as client: + with pytest.raises(httpx.ConnectError): + await client.get("https://secure.example.test/") + assert backend.log["connected_to"] == "93.184.216.34" + assert backend.log["server_hostname"] == "secure.example.test" + + +async def test_second_address_is_tried_when_the_first_fails(): + class _Flaky(_RecordingBackend): + async def connect_tcp(self, host, port, timeout=None, local_address=None, socket_options=None): + self.log.setdefault("tried", []).append(host) + if host == "93.184.216.34": + raise httpcore.ConnectError("refused") + return _RecordingStream(self.log) + + backend = _Flaky() + pinned = PinnedBackend({"multi.example.test": ["93.184.216.34", "8.8.8.8"]}, inner=backend) + stream = await pinned.connect_tcp("multi.example.test", 80) + assert stream is not None + assert backend.log["tried"] == ["93.184.216.34", "8.8.8.8"] + + +def test_transport_refuses_to_start_if_httpx_internals_change(monkeypatch): + original = httpx.AsyncHTTPTransport.__init__ + + def _no_pool(self, *args, **kwargs): + original(self, *args, **kwargs) + del self._pool + + monkeypatch.setattr(httpx.AsyncHTTPTransport, "__init__", _no_pool) + with pytest.raises(RuntimeError): + PinnedTransport({"x.example.test": ["8.8.8.8"]}) From ed9a96b10c9b6dd139fc76a3fd870acbd1d1e0c7 Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 12:19:05 -0800 Subject: [PATCH 04/45] feat: add exact-match target allowlist ALLOWED_TARGET_HOSTS is checked before any DNS lookup and compares whole hostnames after lowercasing, trailing-dot removal and punycode, so httpbin.org.evil.com, sub.httpbin.org and URL credential tricks do not match. Wildcards, ports and paths are not valid entries. SSRF checks still run for allowlisted hosts. Enforcement defaults to on when auth is enabled. Co-Authored-By: Claude Sonnet 5.5 --- backend/app/services/ssrf.py | 39 ++++++++++- backend/tests/test_allowlist.py | 112 ++++++++++++++++++++++++++++++++ backend/tests/test_ssrf.py | 7 ++ 3 files changed, 157 insertions(+), 1 deletion(-) create mode 100644 backend/tests/test_allowlist.py diff --git a/backend/app/services/ssrf.py b/backend/app/services/ssrf.py index bd8891f..b285190 100644 --- a/backend/app/services/ssrf.py +++ b/backend/app/services/ssrf.py @@ -22,6 +22,7 @@ """ import asyncio import ipaddress +import logging import socket from dataclasses import dataclass @@ -29,6 +30,8 @@ from app.core.config import settings +logger = logging.getLogger(__name__) + _MAX_URL_LENGTH = 2048 @@ -242,7 +245,41 @@ async def resolve_target(parsed: ParsedTarget) -> ResolvedTarget: ) +def allowed_hosts() -> list[str]: + """ + The configured allowlist as exact ASCII (punycode) hostnames. Entries that + are not plain hostnames (wildcards, ports, paths) are dropped with a + warning rather than half-matched: matching is exact, never by suffix. + """ + hosts: list[str] = [] + for entry in settings.allowed_target_host_list: + bad = False + for ch in entry: + if ch in "*/@:?#\\ []%": + bad = True + if bad: + logger.warning("Ignoring invalid ALLOWED_TARGET_HOSTS entry %r", entry) + continue + try: + hosts.append(entry.encode("idna").decode("ascii")) + except UnicodeError: + logger.warning("Ignoring invalid ALLOWED_TARGET_HOSTS entry %r", entry) + return hosts + + +def check_allowlist(host: str) -> None: + """Exact-match the (already normalised) target host against the allowlist.""" + if not settings.allowlist_enforced: + return + # `in` on a list is an exact string comparison: "httpbin.org.evil.com", + # "evilhttpbin.org" and "sub.httpbin.org" are all different strings. + if host not in allowed_hosts(): + raise TargetRejected("Target host is not on the allowlist for this demo") + + async def validate_target(url: str) -> ResolvedTarget: - """Parse, resolve and check one target URL. Raises TargetRejected.""" + """Parse, check the allowlist, resolve and check one target URL. Raises TargetRejected.""" parsed = parse_target(url) + # The allowlist runs before any DNS lookup, so arbitrary names are never resolved. + check_allowlist(parsed.host) return await resolve_target(parsed) diff --git a/backend/tests/test_allowlist.py b/backend/tests/test_allowlist.py new file mode 100644 index 0000000..9f21ba1 --- /dev/null +++ b/backend/tests/test_allowlist.py @@ -0,0 +1,112 @@ +import pytest + +from app.core.config import settings +from app.services.ssrf import TargetRejected, allowed_hosts, check_allowlist, validate_target + + +@pytest.fixture(autouse=True) +def _enforce(monkeypatch): + monkeypatch.setattr(settings, "auth_enabled", True) + monkeypatch.setattr(settings, "target_allowlist_enabled", None) + monkeypatch.setattr(settings, "allowed_target_hosts", "httpbin.org,demo.example.com") + + +async def test_exact_hosts_pass(dns): + dns["demo.example.com"] = ["93.184.216.34"] + for url in ["https://httpbin.org/get", "http://demo.example.com:8080/x", "HTTPS://HTTPBIN.ORG/get", + "https://httpbin.org./get"]: + target = await validate_target(url) + assert target.addresses + + +async def test_suffix_prefix_and_subdomain_tricks_fail(dns): + for host in ["httpbin.org.evil.com", "evilhttpbin.org", "httpbin.org-evil.com", "sub.httpbin.org", + "xhttpbin.org", "httpbin.org.", "org", "demo.example.com.evil.com"]: + dns[host] = ["93.184.216.34"] + for url in ["https://httpbin.org.evil.com/", "https://evilhttpbin.org/", "https://httpbin.org-evil.com/", + "https://sub.httpbin.org/", "https://xhttpbin.org/", "https://org/", + "https://demo.example.com.evil.com/"]: + with pytest.raises(TargetRejected) as exc: + await validate_target(url) + assert "allowlist" in str(exc.value) + + +async def test_url_tricks_cannot_smuggle_an_allowlisted_name(dns): + dns["evil.com"] = ["93.184.216.34"] + for url in [ + "https://httpbin.org@evil.com/", # credentials, real host evil.com + "https://evil.com/?httpbin.org", + "https://evil.com/#httpbin.org", + "https://evil.com/httpbin.org", + "https://httpbin.org:443@evil.com/", + "https://evil.com\\@httpbin.org/", + ]: + with pytest.raises(TargetRejected): + await validate_target(url) + + +async def test_lookalike_unicode_hosts_do_not_match(dns): + # U+0131 (dotless i) in place of "i": a different name once punycoded. + with pytest.raises(TargetRejected): + await validate_target("https://httpbın.org/") + + +async def test_allowlisted_hosts_still_get_ssrf_checks(dns, monkeypatch): + monkeypatch.setattr(settings, "allowed_target_hosts", "internal.example.test,127.0.0.1") + dns["internal.example.test"] = ["10.0.0.5"] + with pytest.raises(TargetRejected) as exc: + await validate_target("http://internal.example.test/") + assert "allowlist" not in str(exc.value) + with pytest.raises(TargetRejected) as exc: + await validate_target("http://127.0.0.1/") + assert "allowlist" not in str(exc.value) + + +async def test_rebinding_after_allowlisting_is_still_caught(dns, monkeypatch): + # The name is allowlisted; DNS later starts returning a metadata address. + monkeypatch.setattr(settings, "allowed_target_hosts", "rebind.example.test") + dns["rebind.example.test"] = ["93.184.216.34"] + assert (await validate_target("http://rebind.example.test/")).addresses == ["93.184.216.34"] + dns["rebind.example.test"] = ["169.254.169.254"] + with pytest.raises(TargetRejected): + await validate_target("http://rebind.example.test/") + + +async def test_no_dns_lookup_for_hosts_off_the_list(dns): + with pytest.raises(TargetRejected): + await validate_target("https://not-listed.example.org/") + assert dns.calls == [] + + +def test_wildcards_ports_and_paths_are_not_valid_entries(monkeypatch): + monkeypatch.setattr( + settings, "allowed_target_hosts", "*.example.com,example.org:8080,example.net/path,ok.example.io" + ) + assert allowed_hosts() == ["ok.example.io"] + with pytest.raises(TargetRejected): + check_allowlist("foo.example.com") + + +def test_empty_allowlist_rejects_everything_when_enforced(monkeypatch): + monkeypatch.setattr(settings, "allowed_target_hosts", "") + with pytest.raises(TargetRejected): + check_allowlist("httpbin.org") + + +def test_unicode_entries_are_compared_in_punycode(monkeypatch): + monkeypatch.setattr(settings, "allowed_target_hosts", "bücher.example") + assert allowed_hosts() == ["xn--bcher-kva.example"] + check_allowlist("xn--bcher-kva.example") + + +def test_allowlist_is_off_by_default_without_auth(monkeypatch): + monkeypatch.setattr(settings, "auth_enabled", False) + check_allowlist("anything.example.org") + monkeypatch.setattr(settings, "target_allowlist_enabled", True) + with pytest.raises(TargetRejected): + check_allowlist("anything.example.org") + + +def test_allowlist_can_be_switched_off_explicitly(monkeypatch): + monkeypatch.setattr(settings, "target_allowlist_enabled", False) + check_allowlist("anything.example.org") diff --git a/backend/tests/test_ssrf.py b/backend/tests/test_ssrf.py index 962a22f..b033e3c 100644 --- a/backend/tests/test_ssrf.py +++ b/backend/tests/test_ssrf.py @@ -11,6 +11,13 @@ # Captured at import time, before the autouse `dns` fixture stubs the module attribute. REAL_RESOLVE_HOST = ssrf._resolve_host +@pytest.fixture(autouse=True) +def _allowlist_off(monkeypatch): + # These tests are about the address checks; the allowlist has its own file. + # With it on, many cases would be rejected for the wrong reason. + monkeypatch.setattr(settings, "target_allowlist_enabled", False) + + # --- address classification --------------------------------------------------- BLOCKED_ADDRESSES = [ From c0986cc423c828ea6625edbce9490267981381b6 Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 12:20:00 -0800 Subject: [PATCH 05/45] feat: enforce SSRF and allowlist on POST /benchmark and pin connections The target is validated before the run row is created (422 with a readable reason, no address in the message) and validated again right before connecting. The addresses from that second check are passed to the engine, which connects only to them, so a DNS answer that changes between accept and connect fails the run without sending anything. Co-Authored-By: Claude Sonnet 5.5 --- backend/app/api/runs.py | 21 +++++ backend/app/services/pinned.py | 9 +- backend/app/services/runner.py | 14 ++- backend/tests/test_pinned_transport.py | 17 ++++ backend/tests/test_target_guard_api.py | 125 +++++++++++++++++++++++++ 5 files changed, 182 insertions(+), 4 deletions(-) create mode 100644 backend/tests/test_target_guard_api.py diff --git a/backend/app/api/runs.py b/backend/app/api/runs.py index 777bf30..9b92a0c 100644 --- a/backend/app/api/runs.py +++ b/backend/app/api/runs.py @@ -25,6 +25,7 @@ from app.services.aggregator import compute_metrics from app.services.indexer import index_run from app.services.runner import run_benchmark, run_llm_benchmark +from app.services.ssrf import TargetRejected, validate_target from app.services.scope import ( effective_baseline, index_owner_value, @@ -68,11 +69,18 @@ async def _execute_and_persist(run_id: uuid.UUID, req: BenchmarkRequest) -> None run.status = RunStatus.running await session.commit() + # Resolve again right before connecting: DNS may have changed since + # the request was accepted. The addresses validated here are the + # ones the connections are pinned to. + target = await validate_target(str(req.target_url)) + result = await run_benchmark( target_url=str(req.target_url), method=req.method, num_requests=req.num_requests, concurrency=req.concurrency, + pins={target.host: target.addresses}, + timeout_s=settings.max_request_timeout_s, headers=req.headers, body=req.body, ) @@ -157,6 +165,13 @@ async def _execute_and_persist(run_id: uuid.UUID, req: BenchmarkRequest) -> None logger.warning("Indexing failed for run %s: %s", run.id, exc) logger.info("Indexing block completed for run %s", run_id) + except TargetRejected as rejected: + # The target passed the check at request time but not now (for + # example DNS started returning an internal address). Nothing was sent. + logger.warning("Run %s refused before connecting: %s", run_id, rejected) + run.status = RunStatus.failed + await session.commit() + except Exception as bg_exc: logger.exception("Background task failed for run %s: %s", run_id, bg_exc) run.status = RunStatus.failed @@ -174,6 +189,12 @@ async def create_benchmark( db: DB, principal: CurrentPrincipal, ) -> RunCreatedResponse: + # Reject unsafe targets before a row exists: 422 with a readable reason. + try: + await validate_target(str(req.target_url)) + except TargetRejected as rejected: + raise HTTPException(status_code=422, detail=str(rejected)) + run = Run( target_url=str(req.target_url), method=req.method.upper(), diff --git a/backend/app/services/pinned.py b/backend/app/services/pinned.py index 27230c8..2ab235c 100644 --- a/backend/app/services/pinned.py +++ b/backend/app/services/pinned.py @@ -22,6 +22,11 @@ from app.core.config import settings +def _key(host: str) -> str: + # "example.com." and "example.com" are the same host. + return host.lower().rstrip(".") + + class PinnedBackend(httpcore.AsyncNetworkBackend): def __init__( self, @@ -30,7 +35,7 @@ def __init__( ) -> None: self._pins: dict[str, list[str]] = {} for host, addresses in pins.items(): - self._pins[host.lower()] = list(addresses) + self._pins[_key(host)] = list(addresses) self._inner = inner if inner is not None else httpcore.AnyIOBackend() async def connect_tcp( @@ -41,7 +46,7 @@ async def connect_tcp( local_address: str | None = None, socket_options=None, ): - addresses = self._pins.get(host.lower()) + addresses = self._pins.get(_key(host)) if not addresses: raise httpcore.ConnectError("Host is not a pinned benchmark target") last_error: Exception | None = None diff --git a/backend/app/services/runner.py b/backend/app/services/runner.py index 36883de..1eb32ef 100644 --- a/backend/app/services/runner.py +++ b/backend/app/services/runner.py @@ -3,18 +3,26 @@ import httpx +from app.services.pinned import build_pinned_client + async def run_benchmark( target_url: str, method: str, num_requests: int, concurrency: int, + pins: dict[str, list[str]], + timeout_s: float, headers: dict | None = None, body: dict | None = None, ) -> dict: """ Fire num_requests against target_url with bounded concurrency. + `pins` maps the target hostname to the IP addresses that the SSRF check + validated; connections go only there (see app/services/pinned.py), so DNS is + never consulted again and a rebinding answer cannot change the destination. + Returns: latencies: per-request latency in milliseconds (one entry per request, including errored ones so callers can correlate with error_count) @@ -29,8 +37,10 @@ async def run_benchmark( # A single client is reused across all tasks — connection pooling is # handled internally by httpx and is much cheaper than creating a client - # per request. - async with httpx.AsyncClient(headers=headers or {}, timeout=30.0) as client: + # per request. The client never follows redirects and ignores proxy env vars. + async with build_pinned_client( + pins, headers=headers, timeout=timeout_s, max_connections=concurrency + ) as client: async def _single_request() -> None: nonlocal error_count diff --git a/backend/tests/test_pinned_transport.py b/backend/tests/test_pinned_transport.py index 44ad6b1..fe8e618 100644 --- a/backend/tests/test_pinned_transport.py +++ b/backend/tests/test_pinned_transport.py @@ -181,3 +181,20 @@ def _no_pool(self, *args, **kwargs): monkeypatch.setattr(httpx.AsyncHTTPTransport, "__init__", _no_pool) with pytest.raises(RuntimeError): PinnedTransport({"x.example.test": ["8.8.8.8"]}) + + +async def test_run_benchmark_engine_works_through_the_pinned_client(): + from app.services.runner import run_benchmark + + server, port = await _serve(_echo_host) + async with server: + result = await run_benchmark( + target_url=f"http://engine.example.test:{port}/", + method="GET", + num_requests=6, + concurrency=3, + pins={"engine.example.test": ["127.0.0.1"]}, + timeout_s=5.0, + ) + assert len(result["latencies"]) == 6 + assert result["error_count"] == 0 diff --git a/backend/tests/test_target_guard_api.py b/backend/tests/test_target_guard_api.py new file mode 100644 index 0000000..4c06624 --- /dev/null +++ b/backend/tests/test_target_guard_api.py @@ -0,0 +1,125 @@ +import pytest +from sqlalchemy import func, select + +from app.core.config import settings +from app.core.db import AsyncSessionLocal +from app.models.run import Run, RunStatus +from tests.conftest import login, make_code + +BODY = {"method": "GET", "num_requests": 5, "concurrency": 2} + + +@pytest.fixture(autouse=True) +def _allowlist_off(monkeypatch): + monkeypatch.setattr(settings, "target_allowlist_enabled", False) + + +async def headers_for(client, label="alpha-recruiter"): + code_id, code = await make_code(label) + return code_id, await login(client, code) + + +async def run_count() -> int: + async with AsyncSessionLocal() as session: + return (await session.execute(select(func.count()).select_from(Run))).scalar_one() + + +async def test_unsafe_targets_get_422_and_create_no_run(client, dns, monkeypatch): + dns["localhost"] = ["127.0.0.1"] + dns["internal.example.test"] = ["10.0.0.5"] + dns["v6.example.test"] = ["::1"] + _, h = await headers_for(client) + started = [] + + async def _spy(run_id, req): + started.append(run_id) + + monkeypatch.setattr("app.api.runs._execute_and_persist", _spy) + urls = [ + "http://127.0.0.1/", "http://localhost:8000/", "http://[::1]/", "http://[::ffff:127.0.0.1]/", + "http://2130706433/", "http://017700000001/", "http://0x7f000001/", "http://127.1/", + "http://10.0.0.1/", "http://172.16.0.9/", "http://192.168.1.1/", "http://169.254.169.254/latest/", + "http://100.64.0.1/", "http://224.0.0.1/", "http://0.0.0.0/", "http://[fc00::1]/", "http://[fe80::1]/", + "http://internal.example.test/", "http://v6.example.test/", "http://nxdomain.example.test/", + "ftp://example.com/", "file:///etc/passwd", "gopher://example.com/", + ] + for url in urls: + resp = await client.post("/benchmark", headers=h, json={"target_url": url, **BODY}) + assert resp.status_code == 422, url + assert resp.json()["detail"] + assert started == [] + assert await run_count() == 0 + + +async def test_error_detail_does_not_leak_addresses(client, dns): + dns["internal.example.test"] = ["10.9.8.7"] + _, h = await headers_for(client) + resp = await client.post("/benchmark", headers=h, json={"target_url": "http://internal.example.test/", **BODY}) + assert resp.status_code == 422 + assert "10.9.8.7" not in resp.text + + +async def test_public_target_is_accepted(client, monkeypatch): + _, h = await headers_for(client) + + async def _noop(run_id, req): + return None + + monkeypatch.setattr("app.api.runs._execute_and_persist", _noop) + resp = await client.post("/benchmark", headers=h, json={"target_url": "https://httpbin.org/get", **BODY}) + assert resp.status_code == 202 + assert await run_count() == 1 + + +async def test_background_run_connects_only_to_the_validated_addresses(client, dns, monkeypatch): + dns["httpbin.org"] = ["93.184.216.34"] + _, h = await headers_for(client) + seen = {} + + async def _fake_run(**kwargs): + seen.update(kwargs) + return {"latencies": [10.0] * kwargs["num_requests"], "error_count": 0, "total_time": 0.5} + + monkeypatch.setattr("app.api.runs.run_benchmark", _fake_run) + resp = await client.post("/benchmark", headers=h, json={"target_url": "https://httpbin.org/get", **BODY}) + assert resp.status_code == 202 + assert seen["pins"] == {"httpbin.org": ["93.184.216.34"]} + assert seen["timeout_s"] == settings.max_request_timeout_s + async with AsyncSessionLocal() as session: + run = (await session.execute(select(Run))).scalars().one() + assert run.status == RunStatus.done + + +async def test_dns_rebinding_between_accept_and_connect_fails_the_run(client, monkeypatch): + """First lookup is public (request accepted); the second, at connect time, is internal.""" + answers = [["93.184.216.34"], ["169.254.169.254"]] + + async def _rebinding(host, port): + return answers.pop(0) if len(answers) > 1 else answers[0] + + monkeypatch.setattr("app.services.ssrf._resolve_host", _rebinding) + connected = [] + + async def _must_not_connect(**kwargs): + connected.append(kwargs) + return {"latencies": [], "error_count": 0, "total_time": 0.0} + + monkeypatch.setattr("app.api.runs.run_benchmark", _must_not_connect) + _, h = await headers_for(client) + resp = await client.post("/benchmark", headers=h, json={"target_url": "https://httpbin.org/get", **BODY}) + assert resp.status_code == 202 + assert connected == [] + async with AsyncSessionLocal() as session: + run = (await session.execute(select(Run))).scalars().one() + assert run.status == RunStatus.failed + + +async def test_allowlist_applies_through_the_api(client, dns, monkeypatch): + monkeypatch.setattr(settings, "target_allowlist_enabled", None) # follow auth (on) + monkeypatch.setattr(settings, "allowed_target_hosts", "httpbin.org") + dns["httpbin.org.evil.com"] = ["93.184.216.34"] + _, h = await headers_for(client) + resp = await client.post("/benchmark", headers=h, json={"target_url": "https://httpbin.org.evil.com/", **BODY}) + assert resp.status_code == 422 + assert "allowlist" in resp.json()["detail"] + assert await run_count() == 0 From 8c54c8b969aec8226072825ff254828ab0bf3f34 Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 12:20:53 -0800 Subject: [PATCH 06/45] feat: cap requests, concurrency and timeout; limit runs to 60 s num_requests <= 500, concurrency <= 20 and a new per-request timeout_s <= 10 are enforced in the request schemas from settings (also for the LLM request), so every client is bound by them. The engine runs under asyncio.wait_for with a 60 s wall-clock limit; a run that hits it is cancelled and marked failed. Co-Authored-By: Claude Sonnet 5.5 --- backend/app/api/runs.py | 40 ++++++++++--- backend/app/schemas/run.py | 44 ++++++++++++--- backend/tests/test_caps.py | 96 ++++++++++++++++++++++++++++++++ backend/tests/test_wall_clock.py | 54 ++++++++++++++++++ 4 files changed, 218 insertions(+), 16 deletions(-) create mode 100644 backend/tests/test_caps.py create mode 100644 backend/tests/test_wall_clock.py diff --git a/backend/app/api/runs.py b/backend/app/api/runs.py index 9b92a0c..ba50d27 100644 --- a/backend/app/api/runs.py +++ b/backend/app/api/runs.py @@ -1,3 +1,4 @@ +import asyncio import logging import uuid from typing import Annotated @@ -74,15 +75,20 @@ async def _execute_and_persist(run_id: uuid.UUID, req: BenchmarkRequest) -> None # ones the connections are pinned to. target = await validate_target(str(req.target_url)) - result = await run_benchmark( - target_url=str(req.target_url), - method=req.method, - num_requests=req.num_requests, - concurrency=req.concurrency, - pins={target.host: target.addresses}, - timeout_s=settings.max_request_timeout_s, - headers=req.headers, - body=req.body, + # Hard wall-clock limit for the whole run: wait_for cancels the + # engine (and its client) if the run is still going when it expires. + result = await asyncio.wait_for( + run_benchmark( + target_url=str(req.target_url), + method=req.method, + num_requests=req.num_requests, + concurrency=req.concurrency, + pins={target.host: target.addresses}, + timeout_s=_request_timeout(req), + headers=req.headers, + body=req.body, + ), + timeout=settings.run_wall_clock_limit_s, ) latencies = result["latencies"] @@ -165,6 +171,15 @@ async def _execute_and_persist(run_id: uuid.UUID, req: BenchmarkRequest) -> None logger.warning("Indexing failed for run %s: %s", run.id, exc) logger.info("Indexing block completed for run %s", run_id) + except asyncio.TimeoutError: + logger.warning( + "Run %s exceeded the %gs wall-clock limit and was cancelled", + run_id, + settings.run_wall_clock_limit_s, + ) + run.status = RunStatus.failed + await session.commit() + except TargetRejected as rejected: # The target passed the check at request time but not now (for # example DNS started returning an internal address). Nothing was sent. @@ -432,6 +447,13 @@ async def diagnose_run( # Helpers # --------------------------------------------------------------------------- +def _request_timeout(req) -> float: + """Per-request timeout: the caller's value (already capped) or the server maximum.""" + if req.timeout_s is not None: + return req.timeout_s + return settings.max_request_timeout_s + + def _pct_delta(current: float, baseline: float) -> float: """Return percentage change of current vs baseline (positive = regression). Returns 0.0 when baseline is zero to avoid division-by-zero.""" diff --git a/backend/app/schemas/run.py b/backend/app/schemas/run.py index b81a03c..7ae3ff6 100644 --- a/backend/app/schemas/run.py +++ b/backend/app/schemas/run.py @@ -2,8 +2,9 @@ from datetime import datetime from typing import Literal -from pydantic import BaseModel, Field, HttpUrl +from pydantic import BaseModel, Field, HttpUrl, field_validator +from app.core.config import settings from app.models.run import RunStatus @@ -11,11 +12,39 @@ # Request schemas # --------------------------------------------------------------------------- -class BenchmarkRequest(BaseModel): +# The caps below are read from settings when a request is validated (not frozen +# at import time), so they are enforced server-side for every client and an +# operator can change them with an environment variable. +class _Capped(BaseModel): + @field_validator("num_requests", check_fields=False) + @classmethod + def _cap_num_requests(cls, value: int) -> int: + if value > settings.max_num_requests: + raise ValueError(f"num_requests must be at most {settings.max_num_requests}") + return value + + @field_validator("concurrency", check_fields=False) + @classmethod + def _cap_concurrency(cls, value: int) -> int: + if value > settings.max_concurrency: + raise ValueError(f"concurrency must be at most {settings.max_concurrency}") + return value + + @field_validator("timeout_s", check_fields=False) + @classmethod + def _cap_timeout(cls, value: float | None) -> float | None: + if value is not None and value > settings.max_request_timeout_s: + raise ValueError(f"timeout_s must be at most {settings.max_request_timeout_s:g}") + return value + + +class BenchmarkRequest(_Capped): target_url: HttpUrl method: str = Field(default="GET", max_length=10, pattern=r"^[A-Z]+$") - num_requests: int = Field(ge=1, le=10_000) - concurrency: int = Field(ge=1, le=500) + num_requests: int = Field(ge=1) + concurrency: int = Field(ge=1) + # Per-request timeout in seconds. Omit to use the server maximum. + timeout_s: float | None = Field(default=None, gt=0) headers: dict[str, str] | None = None body: dict | None = None # SLA thresholds — all optional. Omit a field to skip that threshold. @@ -27,14 +56,15 @@ class BenchmarkRequest(BaseModel): sla_error_rate_pct: float | None = Field(default=None, ge=0, le=100) -class LLMBenchmarkRequest(BaseModel): +class LLMBenchmarkRequest(_Capped): endpoint_url: HttpUrl # api_key is kept out of logs; callers must pass it per-request. api_key: str model: str prompt: str - num_requests: int = Field(default=10, ge=1, le=1_000) - concurrency: int = Field(default=3, ge=1, le=50) + num_requests: int = Field(default=10, ge=1) + concurrency: int = Field(default=3, ge=1) + timeout_s: float | None = Field(default=None, gt=0) class DiagnoseRequest(BaseModel): diff --git a/backend/tests/test_caps.py b/backend/tests/test_caps.py new file mode 100644 index 0000000..1cfce29 --- /dev/null +++ b/backend/tests/test_caps.py @@ -0,0 +1,96 @@ +import pytest +from sqlalchemy import func, select + +from app.core.config import settings +from app.core.db import AsyncSessionLocal +from app.models.run import Run +from app.schemas.run import BenchmarkRequest, LLMBenchmarkRequest +from tests.conftest import login, make_code + +OK = {"target_url": "https://httpbin.org/get", "method": "GET", "num_requests": 10, "concurrency": 2} + + +@pytest.fixture(autouse=True) +def _noop_background(monkeypatch): + async def _noop(run_id, req): + return None + + monkeypatch.setattr("app.api.runs._execute_and_persist", _noop) + + +async def auth(client): + _, code = await make_code("caps-recruiter") + return await login(client, code) + + +async def run_count() -> int: + async with AsyncSessionLocal() as session: + return (await session.execute(select(func.count()).select_from(Run))).scalar_one() + + +async def post(client, h, **overrides): + return await client.post("/benchmark", headers=h, json={**OK, **overrides}) + + +async def test_values_at_the_caps_are_accepted(client): + h = await auth(client) + resp = await post(client, h, num_requests=500, concurrency=20, timeout_s=10) + assert resp.status_code == 202 + + +async def test_num_requests_over_the_cap_is_rejected(client): + h = await auth(client) + for value in [501, 1000, 10_000, 10**9]: + resp = await post(client, h, num_requests=value) + assert resp.status_code == 422, value + assert "at most 500" in resp.text + assert await run_count() == 0 + + +async def test_concurrency_over_the_cap_is_rejected(client): + h = await auth(client) + for value in [21, 50, 500]: + resp = await post(client, h, concurrency=value) + assert resp.status_code == 422, value + assert "at most 20" in resp.text + + +async def test_timeout_over_the_cap_is_rejected(client): + h = await auth(client) + for value in [10.01, 11, 30, 3600]: + resp = await post(client, h, timeout_s=value) + assert resp.status_code == 422, value + assert "at most 10" in resp.text + + +async def test_non_positive_values_are_rejected(client): + h = await auth(client) + for field, value in [("num_requests", 0), ("num_requests", -5), ("concurrency", 0), + ("concurrency", -1), ("timeout_s", 0), ("timeout_s", -2)]: + resp = await post(client, h, **{field: value}) + assert resp.status_code == 422, (field, value) + + +async def test_caps_are_settings_not_constants(client, monkeypatch): + h = await auth(client) + monkeypatch.setattr(settings, "max_num_requests", 50) + monkeypatch.setattr(settings, "max_concurrency", 4) + monkeypatch.setattr(settings, "max_request_timeout_s", 2.0) + assert (await post(client, h, num_requests=51)).status_code == 422 + assert (await post(client, h, concurrency=5)).status_code == 422 + assert (await post(client, h, timeout_s=2.5)).status_code == 422 + assert (await post(client, h, num_requests=50, concurrency=4, timeout_s=2)).status_code == 202 + + +def test_llm_request_uses_the_same_caps(): + base = {"endpoint_url": "https://api.example.com/v1/chat", "api_key": "k", "model": "m", "prompt": "p"} + LLMBenchmarkRequest(**base, num_requests=500, concurrency=20) + for field, value in [("num_requests", 501), ("concurrency", 21), ("timeout_s", 11)]: + with pytest.raises(ValueError): + LLMBenchmarkRequest(**base, **{field: value}) + + +def test_schema_enforces_caps_without_the_api(): + # The caps live in the schema, so any code path that builds a request obeys them. + with pytest.raises(ValueError): + BenchmarkRequest(target_url="https://httpbin.org/get", num_requests=501, concurrency=1) diff --git a/backend/tests/test_wall_clock.py b/backend/tests/test_wall_clock.py new file mode 100644 index 0000000..605ace0 --- /dev/null +++ b/backend/tests/test_wall_clock.py @@ -0,0 +1,54 @@ +import asyncio + +from sqlalchemy import select + +from app.core.config import settings +from app.core.db import AsyncSessionLocal +from app.models.run import Run, RunStatus +from tests.conftest import login, make_code + +OK = {"target_url": "https://httpbin.org/get", "method": "GET", "num_requests": 10, "concurrency": 2} + + +async def test_run_is_cancelled_and_failed_at_the_wall_clock_limit(client, monkeypatch): + monkeypatch.setattr(settings, "run_wall_clock_limit_s", 0.2) + state = {"started": False, "cancelled": False} + + async def _slow_engine(**kwargs): + state["started"] = True + try: + await asyncio.sleep(30) + except asyncio.CancelledError: + state["cancelled"] = True + raise + + monkeypatch.setattr("app.api.runs.run_benchmark", _slow_engine) + _, code = await make_code("slow-recruiter") + h = await login(client, code) + + loop = asyncio.get_running_loop() + began = loop.time() + resp = await client.post("/benchmark", headers=h, json=OK) + elapsed = loop.time() - began + + assert resp.status_code == 202 + assert elapsed < 5 # the 30 s sleep was cut short by the 0.2 s limit + assert state["started"] and state["cancelled"] + async with AsyncSessionLocal() as session: + run = (await session.execute(select(Run))).scalars().one() + assert run.status == RunStatus.failed + + +async def test_a_run_inside_the_limit_still_completes(client, monkeypatch): + monkeypatch.setattr(settings, "run_wall_clock_limit_s", 5.0) + + async def _quick_engine(**kwargs): + return {"latencies": [12.0] * kwargs["num_requests"], "error_count": 0, "total_time": 0.1} + + monkeypatch.setattr("app.api.runs.run_benchmark", _quick_engine) + _, code = await make_code("quick-recruiter") + h = await login(client, code) + assert (await client.post("/benchmark", headers=h, json=OK)).status_code == 202 + async with AsyncSessionLocal() as session: + run = (await session.execute(select(Run))).scalars().one() + assert run.status == RunStatus.done From a8ed36c3184dc0c4f27a216a381fd7d1b7de2a61 Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 12:22:13 -0800 Subject: [PATCH 07/45] feat: add active-run limits and daily request budgets At most 2 runs may be pending or running at once, and 1 per access code. Each code and the app as a whole also have a daily budget (sum of num_requests since 00:00 UTC; 2,000 per code and 10,000 overall by default). Everything is computed from the runs table, so it survives restarts. Exceeding a limit returns 429 with a readable message and a Retry-After header. The check and the insert run under one lock. Quotas apply only when auth is enabled. Co-Authored-By: Claude Sonnet 5.5 --- backend/app/api/runs.py | 41 +++++--- backend/app/services/quotas.py | 114 +++++++++++++++++++++ backend/tests/conftest.py | 9 +- backend/tests/test_quotas.py | 180 +++++++++++++++++++++++++++++++++ 4 files changed, 327 insertions(+), 17 deletions(-) create mode 100644 backend/app/services/quotas.py create mode 100644 backend/tests/test_quotas.py diff --git a/backend/app/api/runs.py b/backend/app/api/runs.py index ba50d27..088a044 100644 --- a/backend/app/api/runs.py +++ b/backend/app/api/runs.py @@ -25,6 +25,7 @@ ) from app.services.aggregator import compute_metrics from app.services.indexer import index_run +from app.services.quotas import QuotaExceeded, admission_lock, check_quotas from app.services.runner import run_benchmark, run_llm_benchmark from app.services.ssrf import TargetRejected, validate_target from app.services.scope import ( @@ -210,20 +211,32 @@ async def create_benchmark( except TargetRejected as rejected: raise HTTPException(status_code=422, detail=str(rejected)) - run = Run( - target_url=str(req.target_url), - method=req.method.upper(), - num_requests=req.num_requests, - concurrency=req.concurrency, - # Tag the run with the creating code so usage can be attributed. - access_code_id=principal.code_id, - ) - db.add(run) - # Flush to get the DB-assigned id without committing the transaction; - # commit happens here so the row is visible to the background task's - # separate session before that task starts. - await db.commit() - await db.refresh(run) + # Check the limits and insert the run under one lock, so two simultaneous + # requests cannot both pass the same check. + async with admission_lock(): + try: + await check_quotas(db, principal.code_id, req.num_requests) + except QuotaExceeded as exceeded: + raise HTTPException( + status_code=429, + detail=str(exceeded), + headers={"Retry-After": str(exceeded.retry_after_s)}, + ) + + run = Run( + target_url=str(req.target_url), + method=req.method.upper(), + num_requests=req.num_requests, + concurrency=req.concurrency, + # Tag the run with the creating code so usage can be attributed. + access_code_id=principal.code_id, + ) + db.add(run) + # Flush to get the DB-assigned id without committing the transaction; + # commit happens here so the row is visible to the background task's + # separate session before that task starts. + await db.commit() + await db.refresh(run) # BackgroundTasks runs after the response is sent but inside the same # process — no broker needed for week-1 simplicity (see CLAUDE.md). diff --git a/backend/app/services/quotas.py b/backend/app/services/quotas.py new file mode 100644 index 0000000..21ba428 --- /dev/null +++ b/backend/app/services/quotas.py @@ -0,0 +1,114 @@ +""" +Usage limits for the hosted demo, computed from the runs table. + +Nothing here is kept in memory, so the limits survive restarts and are shared +by every worker that reads the same database: + - at most MAX_CONCURRENT_RUNS runs pending/running across the whole app + - at most MAX_ACTIVE_RUNS_PER_CODE pending/running runs per access code + - a daily budget (sum of num_requests since 00:00 UTC) per code and globally + +The check and the insert of the new run happen under one lock (admission_lock) +so two simultaneous requests in this process cannot both pass the same check. +Across several replicas the lock is per-process, so a short race could admit one +run too many; the wall-clock limit and the reaper bound the cost of that. +""" +import asyncio +import uuid +from datetime import datetime, timedelta, timezone + +from sqlalchemy import func, select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.core.config import settings +from app.models.run import Run, RunStatus + +ACTIVE_STATUSES = (RunStatus.pending, RunStatus.running) + + +class QuotaExceeded(Exception): + """A usage limit was hit. str(exc) is a readable message for the caller.""" + + def __init__(self, message: str, retry_after_s: int) -> None: + super().__init__(message) + self.retry_after_s = retry_after_s + + +def utc_now() -> datetime: + # A function (not inline) so tests can pin the clock. + return datetime.now(timezone.utc) + + +def utc_day_start(now: datetime) -> datetime: + return now.replace(hour=0, minute=0, second=0, microsecond=0) + + +_lock_state: dict = {"loop": None, "lock": None} + + +def admission_lock() -> asyncio.Lock: + """One lock per running event loop (a module-level Lock would bind to the first loop).""" + loop = asyncio.get_running_loop() + if _lock_state["loop"] is not loop: + _lock_state["loop"] = loop + _lock_state["lock"] = asyncio.Lock() + return _lock_state["lock"] + + +async def _count_active(db: AsyncSession, code_id: uuid.UUID | None = None) -> int: + stmt = select(func.count()).select_from(Run).where(Run.status.in_(ACTIVE_STATUSES)) + if code_id is not None: + stmt = stmt.where(Run.access_code_id == code_id) + return int((await db.execute(stmt)).scalar_one()) + + +async def _requests_since( + db: AsyncSession, since: datetime, code_id: uuid.UUID | None = None +) -> int: + # Every run counts, whatever its final status: the traffic was (or could + # have been) sent either way. + stmt = select(func.coalesce(func.sum(Run.num_requests), 0)).where(Run.created_at >= since) + if code_id is not None: + stmt = stmt.where(Run.access_code_id == code_id) + return int((await db.execute(stmt)).scalar_one()) + + +async def check_quotas(db: AsyncSession, code_id: uuid.UUID | None, requested: int) -> None: + """Raise QuotaExceeded if starting a run of `requested` requests is not allowed now.""" + if not settings.quotas_enforced: + return + + now = utc_now() + next_reset = utc_day_start(now) + timedelta(days=1) + seconds_to_reset = max(1, int((next_reset - now).total_seconds())) + + if code_id is not None: + if await _count_active(db, code_id) >= settings.max_active_runs_per_code: + raise QuotaExceeded( + "You already have a benchmark running. Wait for it to finish, then start another.", + retry_after_s=15, + ) + if await _count_active(db) >= settings.max_concurrent_runs: + raise QuotaExceeded( + "The demo is busy with other benchmarks right now. Please try again in a minute.", + retry_after_s=30, + ) + + day_start = utc_day_start(now) + if code_id is not None: + used = await _requests_since(db, day_start, code_id) + budget = settings.daily_budget_per_code + if used + requested > budget: + remaining = max(0, budget - used) + raise QuotaExceeded( + f"Daily request budget reached for your access code: {used:,} of {budget:,} " + f"requests used today, and this run needs {requested:,} " + f"({remaining:,} left). The budget resets at 00:00 UTC.", + retry_after_s=seconds_to_reset, + ) + used_global = await _requests_since(db, day_start) + if used_global + requested > settings.daily_budget_global: + raise QuotaExceeded( + "The demo has used its request capacity for today. " + "Please try again after 00:00 UTC.", + retry_after_s=seconds_to_reset, + ) diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 3d3b0a0..1117965 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -128,16 +128,19 @@ async def make_run( p50: float = 100.0, baseline: bool = False, age_minutes: int = 0, + status: RunStatus = RunStatus.done, + num_requests: int = 10, + created_at: datetime | None = None, ) -> uuid.UUID: run = Run( target_url="https://httpbin.org/get", method="GET", - num_requests=10, + num_requests=num_requests, concurrency=2, - status=RunStatus.done, + status=status, is_baseline=baseline, access_code_id=owner, - created_at=datetime.now(timezone.utc) - timedelta(minutes=age_minutes), + created_at=created_at or (datetime.now(timezone.utc) - timedelta(minutes=age_minutes)), ) async with AsyncSessionLocal() as session: session.add(run) diff --git a/backend/tests/test_quotas.py b/backend/tests/test_quotas.py new file mode 100644 index 0000000..776d2c9 --- /dev/null +++ b/backend/tests/test_quotas.py @@ -0,0 +1,180 @@ +import asyncio +from datetime import datetime, timedelta, timezone + +import pytest +from sqlalchemy import func, select + +from app.core.config import settings +from app.core.db import AsyncSessionLocal +from app.models.run import Run, RunStatus +from tests.conftest import login, make_code, make_run + +NOW = datetime(2026, 11, 2, 12, 0, 0, tzinfo=timezone.utc) +TODAY = NOW.replace(hour=1) # earlier today (UTC) +YESTERDAY = NOW - timedelta(days=1, hours=1) + + +@pytest.fixture(autouse=True) +def _fixed_clock_and_noop_task(monkeypatch): + monkeypatch.setattr("app.services.quotas.utc_now", lambda: NOW) + + async def _noop(run_id, req): + return None + + monkeypatch.setattr("app.api.runs._execute_and_persist", _noop) + + +async def start(client, h, n=10): + return await client.post( + "/benchmark", headers=h, + json={"target_url": "https://httpbin.org/get", "method": "GET", "num_requests": n, "concurrency": 2}, + ) + + +async def user(client, label): + code_id, code = await make_code(label) + return code_id, await login(client, code) + + +async def run_count() -> int: + async with AsyncSessionLocal() as session: + return (await session.execute(select(func.count()).select_from(Run))).scalar_one() + + +# --- active runs --------------------------------------------------------------- + +async def test_second_active_run_for_the_same_code_is_429(client): + a_id, a_h = await user(client, "alpha-recruiter") + await make_run(a_id, status=RunStatus.running, created_at=TODAY) + resp = await start(client, a_h) + assert resp.status_code == 429 + assert "already have a benchmark running" in resp.json()["detail"] + assert "Retry-After" in resp.headers + assert await run_count() == 1 + + +async def test_pending_counts_as_active_but_finished_runs_do_not(client): + a_id, a_h = await user(client, "alpha-recruiter") + await make_run(a_id, status=RunStatus.done, created_at=TODAY) + await make_run(a_id, status=RunStatus.failed, created_at=TODAY) + assert (await start(client, a_h)).status_code == 202 # a new pending run now exists + assert (await start(client, a_h)).status_code == 429 # pending counts + + +async def test_another_code_is_not_blocked_by_my_active_run(client): + a_id, a_h = await user(client, "alpha-recruiter") + _, b_h = await user(client, "bravo-recruiter") + await make_run(a_id, status=RunStatus.running, created_at=TODAY) + assert (await start(client, a_h)).status_code == 429 + assert (await start(client, b_h)).status_code == 202 + + +async def test_at_most_two_runs_are_active_globally(client): + a_id, a_h = await user(client, "alpha-recruiter") + b_id, b_h = await user(client, "bravo-recruiter") + _, c_h = await user(client, "charlie-recruiter") + await make_run(a_id, status=RunStatus.running, created_at=TODAY) + await make_run(b_id, status=RunStatus.pending, created_at=TODAY) + resp = await start(client, c_h) + assert resp.status_code == 429 + assert "busy" in resp.json()["detail"] + # Once one of them finishes there is room again. + async with AsyncSessionLocal() as session: + run = (await session.execute(select(Run).where(Run.status == RunStatus.running))).scalars().one() + run.status = RunStatus.done + await session.commit() + assert (await start(client, c_h)).status_code == 202 + + +async def test_limits_are_read_from_settings(client, monkeypatch): + monkeypatch.setattr(settings, "max_active_runs_per_code", 2) + monkeypatch.setattr(settings, "max_concurrent_runs", 3) + a_id, a_h = await user(client, "alpha-recruiter") + await make_run(a_id, status=RunStatus.running, created_at=TODAY) + assert (await start(client, a_h)).status_code == 202 # 2nd for this code allowed + assert (await start(client, a_h)).status_code == 429 # 3rd is not + + +async def test_simultaneous_requests_cannot_both_pass_the_check(client): + _, a_h = await user(client, "alpha-recruiter") + responses = await asyncio.gather(start(client, a_h), start(client, a_h), start(client, a_h)) + codes = sorted(r.status_code for r in responses) + assert codes == [202, 429, 429] + assert await run_count() == 1 + + +# --- daily budget -------------------------------------------------------------- + +async def test_per_code_budget_counts_todays_runs_only(client): + a_id, a_h = await user(client, "alpha-recruiter") + await make_run(a_id, num_requests=400, created_at=YESTERDAY) # not today + await make_run(a_id, num_requests=500, created_at=TODAY) + await make_run(a_id, num_requests=500, created_at=TODAY, status=RunStatus.failed) + await make_run(a_id, num_requests=500, created_at=TODAY) + await make_run(a_id, num_requests=100, created_at=TODAY) + # 1,600 used today (failed runs count too); budget 2,000. + resp = await start(client, a_h, n=500) + assert resp.status_code == 429 + detail = resp.json()["detail"] + assert "Daily request budget" in detail and "1,600 of 2,000" in detail + assert "(400 left)" in detail and "00:00 UTC" in detail + assert 0 < int(resp.headers["Retry-After"]) <= 12 * 3600 + assert (await start(client, a_h, n=400)).status_code == 202 # exactly reaches the budget + + +async def test_budget_message_when_nothing_is_left(client): + a_id, a_h = await user(client, "alpha-recruiter") + for _ in range(4): + await make_run(a_id, num_requests=500, created_at=TODAY) + resp = await start(client, a_h, n=10) + assert resp.status_code == 429 + assert "(0 left)" in resp.json()["detail"] + + +async def test_other_codes_budgets_are_independent(client): + a_id, a_h = await user(client, "alpha-recruiter") + _, b_h = await user(client, "bravo-recruiter") + for _ in range(4): + await make_run(a_id, num_requests=500, created_at=TODAY) + assert (await start(client, a_h, n=10)).status_code == 429 + assert (await start(client, b_h, n=10)).status_code == 202 + + +async def test_global_budget_counts_every_owner(client): + a_id, _ = await user(client, "alpha-recruiter") + _, b_h = await user(client, "bravo-recruiter") + for _ in range(16): + await make_run(a_id, num_requests=500, created_at=TODAY) + # 8,000 by alpha, plus 1,800 by the demo owner = 9,800 of 10,000 today. + await make_run(None, num_requests=1800, created_at=TODAY) + resp = await start(client, b_h, n=300) + assert resp.status_code == 429 + assert "capacity for today" in resp.json()["detail"] + assert (await start(client, b_h, n=200)).status_code == 202 + + +async def test_budgets_come_from_settings(client, monkeypatch): + monkeypatch.setattr(settings, "daily_budget_per_code", 100) + _, a_h = await user(client, "alpha-recruiter") + assert (await start(client, a_h, n=101)).status_code == 429 + assert (await start(client, a_h, n=100)).status_code == 202 + + +async def test_usage_survives_a_restart(client): + """Nothing is kept in memory: a fresh process sees the same usage from the DB.""" + a_id, a_h = await user(client, "alpha-recruiter") + for _ in range(4): + await make_run(a_id, num_requests=500, created_at=TODAY) + from app.core.db import engine + + await engine.dispose() # drop every pooled connection, as a restart would + assert (await start(client, a_h, n=10)).status_code == 429 + + +# --- not enforced locally ------------------------------------------------------ + +async def test_quotas_are_off_when_auth_is_off(client, monkeypatch): + monkeypatch.setattr(settings, "auth_enabled", False) + for _ in range(5): + await make_run(None, status=RunStatus.running, num_requests=500, created_at=TODAY) + assert (await start(client, {}, n=500)).status_code == 202 From 306a74e83d78cd144229eaef232af22c9d28e86c Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 12:22:49 -0800 Subject: [PATCH 08/45] feat: add stale-run reaper at startup and on a timer Runs left pending or running longer than the wall-clock limit plus a grace period (their worker died or was restarted) are marked failed, which also frees their active-run slot. It runs once in the app lifespan before serving and then every REAPER_INTERVAL_SECONDS; a failed pass is logged and retried. Co-Authored-By: Claude Sonnet 5.5 --- backend/app/main.py | 25 ++++++- backend/app/services/reaper.py | 54 +++++++++++++++ backend/tests/test_reaper.py | 119 +++++++++++++++++++++++++++++++++ 3 files changed, 197 insertions(+), 1 deletion(-) create mode 100644 backend/app/services/reaper.py create mode 100644 backend/tests/test_reaper.py diff --git a/backend/app/main.py b/backend/app/main.py index b595df3..c0baa31 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -1,4 +1,6 @@ +import asyncio import logging +from contextlib import asynccontextmanager from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware @@ -11,6 +13,27 @@ from app.api.runs import router as runs_router from app.core.config import settings from app.core.security import validate_auth_settings +from app.services.reaper import reap_stale_runs, reaper_loop + + +@asynccontextmanager +async def lifespan(app: FastAPI): + # Runs that were mid-flight when the previous process stopped will never be + # finished by anyone: fail them now, then keep checking while we run. + try: + await reap_stale_runs() + except Exception as exc: + # The database may not be reachable yet; the periodic pass retries. + logging.getLogger(__name__).warning("Startup reaper pass failed: %s", exc) + task = asyncio.create_task(reaper_loop()) + try: + yield + finally: + task.cancel() + try: + await task + except asyncio.CancelledError: + pass def create_app() -> FastAPI: @@ -21,7 +44,7 @@ def create_app() -> FastAPI: "AUTH_ENABLED is false: all routes are open. Local development only." ) - app = FastAPI(title=settings.app_name, debug=settings.debug) + app = FastAPI(title=settings.app_name, debug=settings.debug, lifespan=lifespan) # Auth uses a Bearer header, not cookies, so credentials are not needed and # stay off. Origins must be an explicit list (never "*") in production. diff --git a/backend/app/services/reaper.py b/backend/app/services/reaper.py new file mode 100644 index 0000000..81395b6 --- /dev/null +++ b/backend/app/services/reaper.py @@ -0,0 +1,54 @@ +""" +Stale-run reaper. + +A run is created as pending, the background task moves it to running, and the +task always ends it as done or failed. If the process dies or is restarted in +between (a deploy, an OOM kill), nothing is left to update the row and it would +look active forever, holding one of the limited active-run slots. This marks +such rows failed once they are older than the wall-clock limit plus a grace +period, which no live run can exceed. +""" +import asyncio +import logging +from datetime import datetime, timedelta, timezone + +from sqlalchemy import update + +from app.core.config import settings +from app.core.db import AsyncSessionLocal +from app.models.run import Run, RunStatus + +logger = logging.getLogger(__name__) + + +async def reap_stale_runs(now: datetime | None = None) -> int: + """Mark overdue pending/running runs as failed. Returns how many were changed.""" + current = now if now is not None else datetime.now(timezone.utc) + cutoff = current - timedelta( + seconds=settings.run_wall_clock_limit_s + settings.reaper_grace_seconds + ) + async with AsyncSessionLocal() as session: + result = await session.execute( + update(Run) + .where(Run.status.in_([RunStatus.pending, RunStatus.running])) + .where(Run.created_at < cutoff) + .values(status=RunStatus.failed) + .execution_options(synchronize_session=False) + ) + await session.commit() + reaped = int(result.rowcount or 0) + if reaped: + logger.warning("Reaper marked %d stale run(s) as failed", reaped) + return reaped + + +async def reaper_loop() -> None: + """Run reap_stale_runs forever; a failed pass is logged and retried next tick.""" + while True: + try: + await asyncio.sleep(settings.reaper_interval_seconds) + await reap_stale_runs() + except asyncio.CancelledError: + raise + except Exception as exc: + logger.warning("Stale-run reaper pass failed: %s", exc) diff --git a/backend/tests/test_reaper.py b/backend/tests/test_reaper.py new file mode 100644 index 0000000..a7b03d5 --- /dev/null +++ b/backend/tests/test_reaper.py @@ -0,0 +1,119 @@ +import asyncio +from datetime import datetime, timedelta, timezone + +from sqlalchemy import select + +from app.core.config import settings +from app.core.db import AsyncSessionLocal +from app.main import app +from app.models.run import Run, RunStatus +from app.services.reaper import reap_stale_runs, reaper_loop +from tests.conftest import make_run + +NOW = datetime(2026, 11, 2, 12, 0, 0, tzinfo=timezone.utc) +# Default limit is 60 s plus a 120 s grace period: 180 s. + + +def ago(seconds: float) -> datetime: + return NOW - timedelta(seconds=seconds) + + +async def status_of(run_id) -> RunStatus: + async with AsyncSessionLocal() as session: + return (await session.execute(select(Run.status).where(Run.id == run_id))).scalar_one() + + +async def test_overdue_pending_and_running_runs_are_failed(): + pending = await make_run(None, status=RunStatus.pending, created_at=ago(600)) + running = await make_run(None, status=RunStatus.running, created_at=ago(3600)) + assert await reap_stale_runs(now=NOW) == 2 + assert await status_of(pending) == RunStatus.failed + assert await status_of(running) == RunStatus.failed + + +async def test_runs_inside_the_limit_plus_grace_are_left_alone(): + fresh_running = await make_run(None, status=RunStatus.running, created_at=ago(30)) + fresh_pending = await make_run(None, status=RunStatus.pending, created_at=ago(179)) + assert await reap_stale_runs(now=NOW) == 0 + assert await status_of(fresh_running) == RunStatus.running + assert await status_of(fresh_pending) == RunStatus.pending + + +async def test_boundary_is_limit_plus_grace(): + just_over = await make_run(None, status=RunStatus.running, created_at=ago(181)) + assert await reap_stale_runs(now=NOW) == 1 + assert await status_of(just_over) == RunStatus.failed + + +async def test_finished_runs_are_never_touched(): + done = await make_run(None, status=RunStatus.done, created_at=ago(9999)) + failed = await make_run(None, status=RunStatus.failed, created_at=ago(9999)) + assert await reap_stale_runs(now=NOW) == 0 + assert await status_of(done) == RunStatus.done + assert await status_of(failed) == RunStatus.failed + + +async def test_it_is_idempotent_and_frees_the_active_slot(): + owner = await make_run(None, status=RunStatus.running, created_at=ago(900)) + assert await reap_stale_runs(now=NOW) == 1 + assert await reap_stale_runs(now=NOW) == 0 + assert await status_of(owner) == RunStatus.failed + + +async def test_thresholds_come_from_settings(monkeypatch): + monkeypatch.setattr(settings, "run_wall_clock_limit_s", 10.0) + monkeypatch.setattr(settings, "reaper_grace_seconds", 5.0) + stale = await make_run(None, status=RunStatus.running, created_at=ago(16)) + live = await make_run(None, status=RunStatus.running, created_at=ago(14)) + assert await reap_stale_runs(now=NOW) == 1 + assert await status_of(stale) == RunStatus.failed + assert await status_of(live) == RunStatus.running + + +async def test_periodic_loop_reaps_runs_that_become_stale_later(monkeypatch): + monkeypatch.setattr(settings, "reaper_interval_seconds", 0.05) + task = asyncio.create_task(reaper_loop()) + try: + # Created after the loop started, already overdue by the real clock. + stuck = await make_run(None, status=RunStatus.running, age_minutes=30) + for _ in range(60): + if await status_of(stuck) == RunStatus.failed: + break + await asyncio.sleep(0.05) + assert await status_of(stuck) == RunStatus.failed + finally: + task.cancel() + try: + await task + except asyncio.CancelledError: + pass + + +async def test_loop_survives_a_failing_pass(monkeypatch): + monkeypatch.setattr(settings, "reaper_interval_seconds", 0.02) + calls = {"n": 0} + + async def _flaky(now=None): + calls["n"] += 1 + if calls["n"] == 1: + raise RuntimeError("database unavailable") + return 0 + + monkeypatch.setattr("app.services.reaper.reap_stale_runs", _flaky) + task = asyncio.create_task(reaper_loop()) + await asyncio.sleep(0.3) + task.cancel() + try: + await task + except asyncio.CancelledError: + pass + assert calls["n"] >= 2 + + +async def test_startup_reaps_and_shutdown_stops_the_loop(): + stuck = await make_run(None, status=RunStatus.running, age_minutes=30) + live = await make_run(None, status=RunStatus.running, age_minutes=0) + async with app.router.lifespan_context(app): + assert await status_of(stuck) == RunStatus.failed # reaped by the startup pass + assert await status_of(live) == RunStatus.running + # Leaving the context cancelled the periodic task without errors. From 42bc09b47792a16098fdedb69f21d905693b91b6 Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 12:23:49 -0800 Subject: [PATCH 09/45] feat: gate the LLM benchmark route behind LLM_BENCHMARK_ENABLED The flag defaults to off when auth is enabled and on when it is not. When off, authenticated callers get a 404 identical to an unknown route; callers without a session still get 401. When on, the route gets the same protection as the REST benchmark: SSRF and allowlist checks, pinned connections, capped request counts, timeout, and the wall-clock limit. Co-Authored-By: Claude Sonnet 5.5 --- backend/app/api/deps.py | 11 ++++ backend/app/api/runs.py | 42 +++++++++++---- backend/app/services/runner.py | 11 ++-- backend/tests/test_llm_flag.py | 96 ++++++++++++++++++++++++++++++++++ 4 files changed, 148 insertions(+), 12 deletions(-) create mode 100644 backend/tests/test_llm_flag.py diff --git a/backend/app/api/deps.py b/backend/app/api/deps.py index 1cf526d..d496528 100644 --- a/backend/app/api/deps.py +++ b/backend/app/api/deps.py @@ -101,3 +101,14 @@ async def require_admin( AdminOnly = Depends(require_admin) + + +async def require_llm_benchmark_enabled() -> None: + """ + Feature flag for POST /benchmark/llm. The route forwards a caller-supplied API + key to a caller-supplied endpoint, so it is off by default on a hosted + (auth-enabled) deployment. 404, not 403: when off it should look like it + does not exist, with the same body as an unknown route. + """ + if not settings.llm_benchmark_active: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not Found") diff --git a/backend/app/api/runs.py b/backend/app/api/runs.py index 088a044..5eb3a8b 100644 --- a/backend/app/api/runs.py +++ b/backend/app/api/runs.py @@ -7,7 +7,7 @@ from sqlalchemy import and_, delete, func, select, update from sqlalchemy.ext.asyncio import AsyncSession -from app.api.deps import AdminOnly, CurrentPrincipal, get_principal +from app.api.deps import AdminOnly, CurrentPrincipal, get_principal, require_llm_benchmark_enabled from app.core.config import settings from app.core.db import get_db from app.models.run import Metrics, Run, RunStatus @@ -360,13 +360,21 @@ async def _execute_llm_benchmark(run_id: str, req: LLMBenchmarkRequest) -> None: logger.info("LLM benchmark task started for run_id=%s", run_id) try: - result = await run_llm_benchmark( - endpoint_url=str(req.endpoint_url), - api_key=req.api_key, - model=req.model, - prompt=req.prompt, - num_requests=req.num_requests, - concurrency=req.concurrency, + # Same guards as the REST benchmark: resolve again right before + # connecting, pin the connections, and bound the whole run. + target = await validate_target(str(req.endpoint_url)) + result = await asyncio.wait_for( + run_llm_benchmark( + endpoint_url=str(req.endpoint_url), + api_key=req.api_key, + model=req.model, + prompt=req.prompt, + num_requests=req.num_requests, + concurrency=req.concurrency, + pins={target.host: target.addresses}, + timeout_s=_request_timeout(req), + ), + timeout=settings.run_wall_clock_limit_s, ) ttft = np.array(result["ttft_latencies"], dtype=float) @@ -390,15 +398,31 @@ async def _execute_llm_benchmark(run_id: str, req: LLMBenchmarkRequest) -> None: avg_tps, result["error_count"], ) + except TargetRejected as rejected: + logger.warning("LLM benchmark %s refused before connecting: %s", run_id, rejected) + except asyncio.TimeoutError: + logger.warning("LLM benchmark %s exceeded the wall-clock limit", run_id) except Exception as exc: logger.exception("LLM benchmark task failed for run_id=%s: %s", run_id, exc) -@router.post("/llm", response_model=RunCreatedResponse, status_code=202) +@router.post( + "/llm", + response_model=RunCreatedResponse, + status_code=202, + # Runs after the router-level session check: callers without a valid token + # still get 401; authenticated callers get 404 while the feature is off. + dependencies=[Depends(require_llm_benchmark_enabled)], +) async def create_llm_benchmark( req: LLMBenchmarkRequest, background_tasks: BackgroundTasks, ) -> RunCreatedResponse: + try: + await validate_target(str(req.endpoint_url)) + except TargetRejected as rejected: + raise HTTPException(status_code=422, detail=str(rejected)) + # Generate a client-visible run_id without a DB row — LLM runs aren't # persisted to the runs table yet. The id still lets callers correlate # log lines with the request that triggered them. diff --git a/backend/app/services/runner.py b/backend/app/services/runner.py index 1eb32ef..64c8a3d 100644 --- a/backend/app/services/runner.py +++ b/backend/app/services/runner.py @@ -96,6 +96,8 @@ async def run_llm_benchmark( prompt: str, num_requests: int, concurrency: int, + pins: dict[str, list[str]], + timeout_s: float, ) -> dict: """ Benchmark an OpenAI-compatible streaming LLM endpoint. @@ -130,9 +132,12 @@ async def run_llm_benchmark( "stream": True, } - # LLM endpoints can be slow — 120 s covers long generations without - # hanging forever on a stalled connection. - async with httpx.AsyncClient(headers=headers, timeout=120.0) as client: + # Same pinned, no-redirect client as the REST engine. The per-request + # timeout is capped by the caller (MAX_REQUEST_TIMEOUT_S); it applies to + # each connect/read, and the whole run is bounded by the wall-clock limit. + async with build_pinned_client( + pins, headers=headers, timeout=timeout_s, max_connections=concurrency + ) as client: async def _single_llm_request() -> None: nonlocal error_count diff --git a/backend/tests/test_llm_flag.py b/backend/tests/test_llm_flag.py new file mode 100644 index 0000000..ebb9604 --- /dev/null +++ b/backend/tests/test_llm_flag.py @@ -0,0 +1,96 @@ +import pytest + +from app.api import runs as runs_module +from app.core.config import settings +from app.schemas.run import LLMBenchmarkRequest +from tests.conftest import login, make_code + +# Captured at import time, before the autouse fixture replaces the task. +REAL_LLM_TASK = runs_module._execute_llm_benchmark + +BODY = { + "endpoint_url": "https://httpbin.org/post", "api_key": "test-key-not-real", "model": "m", + "prompt": "hello", "num_requests": 3, "concurrency": 2, +} + + +@pytest.fixture(autouse=True) +def _tasks_off(monkeypatch): + async def _noop(run_id, req): + return None + + monkeypatch.setattr("app.api.runs._execute_llm_benchmark", _noop) + + +async def auth(client): + _, code = await make_code("llm-recruiter") + return await login(client, code) + + +async def test_route_is_404_when_auth_is_on_and_flag_is_unset(client): + h = await auth(client) + resp = await client.post("/benchmark/llm", headers=h, json=BODY) + assert resp.status_code == 404 + # Same body as a route that does not exist. + unknown = await client.post("/benchmark/does-not-exist", headers=h, json=BODY) + assert resp.json() == unknown.json() + + +async def test_route_is_404_when_flag_is_false(client, monkeypatch): + monkeypatch.setattr(settings, "llm_benchmark_enabled", False) + h = await auth(client) + assert (await client.post("/benchmark/llm", headers=h, json=BODY)).status_code == 404 + + +async def test_route_still_requires_a_session_first(client): + assert (await client.post("/benchmark/llm", json=BODY)).status_code == 401 + + +async def test_route_works_when_the_flag_is_on(client, monkeypatch): + monkeypatch.setattr(settings, "llm_benchmark_enabled", True) + h = await auth(client) + resp = await client.post("/benchmark/llm", headers=h, json=BODY) + assert resp.status_code == 202 + assert "run_id" in resp.json() + + +async def test_flag_defaults_to_on_when_auth_is_off(client, monkeypatch): + monkeypatch.setattr(settings, "auth_enabled", False) + monkeypatch.setattr(settings, "llm_benchmark_enabled", None) + assert (await client.post("/benchmark/llm", json=BODY)).status_code == 202 + monkeypatch.setattr(settings, "llm_benchmark_enabled", False) + assert (await client.post("/benchmark/llm", json=BODY)).status_code == 404 + + +async def test_enabled_route_applies_ssrf_allowlist_and_caps(client, dns, monkeypatch): + monkeypatch.setattr(settings, "llm_benchmark_enabled", True) + monkeypatch.setattr(settings, "target_allowlist_enabled", None) + monkeypatch.setattr(settings, "allowed_target_hosts", "httpbin.org,internal.example.test") + dns["internal.example.test"] = ["10.0.0.5"] + h = await auth(client) + for url in ["http://169.254.169.254/v1/chat", "http://internal.example.test/v1/chat", + "https://example.com/v1/chat", "ftp://httpbin.org/x"]: + resp = await client.post("/benchmark/llm", headers=h, json={**BODY, "endpoint_url": url}) + assert resp.status_code == 422, url + assert (await client.post("/benchmark/llm", headers=h, json={**BODY, "num_requests": 501})).status_code == 422 + assert (await client.post("/benchmark/llm", headers=h, json={**BODY, "concurrency": 21})).status_code == 422 + + +async def test_background_task_pins_connections_and_rechecks_dns(dns, monkeypatch): + req = LLMBenchmarkRequest(**BODY) + seen = [] + + async def _fake_engine(**kwargs): + seen.append(kwargs) + return {"ttft_latencies": [1.0], "total_latencies": [2.0], "tokens_per_second_list": [3.0], "error_count": 0} + + monkeypatch.setattr("app.api.runs.run_llm_benchmark", _fake_engine) + await REAL_LLM_TASK("run-1", req) + assert seen[0]["pins"] == {"httpbin.org": ["93.184.216.34"]} + assert seen[0]["timeout_s"] == settings.max_request_timeout_s + + # DNS now answers with the metadata address: nothing may be sent. + dns["httpbin.org"] = ["169.254.169.254"] + seen.clear() + await REAL_LLM_TASK("run-2", req) + assert seen == [] From de057342eae81c5d90976c84eeadd15dd4a81ccf Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 12:24:11 -0800 Subject: [PATCH 10/45] feat: make /health check database connectivity GET /health now runs SELECT 1 with a timeout and returns 503 when the database is unreachable. The body says only that the database is down; the error type goes to the log, not to the public response. Co-Authored-By: Claude Sonnet 5.5 --- backend/app/main.py | 25 ++++++++++++++++-- backend/tests/test_health.py | 49 ++++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 2 deletions(-) create mode 100644 backend/tests/test_health.py diff --git a/backend/app/main.py b/backend/app/main.py index c0baa31..15e92fa 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -4,6 +4,8 @@ from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware +from fastapi.responses import JSONResponse +from sqlalchemy import text logging.basicConfig(level=logging.INFO) @@ -12,10 +14,16 @@ from app.api.runs import admin_router as runs_admin_router from app.api.runs import router as runs_router from app.core.config import settings +from app.core.db import engine from app.core.security import validate_auth_settings from app.services.reaper import reap_stale_runs, reaper_loop +async def _probe_database() -> None: + async with engine.connect() as conn: + await conn.execute(text("SELECT 1")) + + @asynccontextmanager async def lifespan(app: FastAPI): # Runs that were mid-flight when the previous process stopped will never be @@ -57,8 +65,21 @@ def create_app() -> FastAPI: ) @app.get("/health") - async def health() -> dict: - return {"status": "ok"} + async def health(): + # Readiness, not just liveness: an orchestrator should stop sending + # traffic to an instance that cannot reach its database. The response + # says only that the database is down, never why (no hostnames or + # driver errors in a public endpoint); the reason goes to the log. + try: + await asyncio.wait_for(_probe_database(), timeout=settings.health_db_timeout_s) + except Exception as exc: + logging.getLogger(__name__).warning( + "Health check: database unavailable (%s)", type(exc).__name__ + ) + return JSONResponse( + status_code=503, content={"status": "unavailable", "database": "down"} + ) + return {"status": "ok", "database": "ok"} app.include_router(auth_router) app.include_router(admin_router) diff --git a/backend/tests/test_health.py b/backend/tests/test_health.py new file mode 100644 index 0000000..0f68580 --- /dev/null +++ b/backend/tests/test_health.py @@ -0,0 +1,49 @@ +import asyncio + +from sqlalchemy.exc import OperationalError + +from app.core.config import settings + + +async def test_healthy_database_returns_200(client): + resp = await client.get("/health") + assert resp.status_code == 200 + assert resp.json() == {"status": "ok", "database": "ok"} + + +async def test_health_needs_no_credentials(client): + assert (await client.get("/health")).status_code == 200 + + +async def test_database_error_returns_503_without_details(client, monkeypatch): + async def _down(): + raise OperationalError("SELECT 1", {}, Exception("connection refused to db.internal:5432")) + + monkeypatch.setattr("app.main._probe_database", _down) + resp = await client.get("/health") + assert resp.status_code == 503 + assert resp.json() == {"status": "unavailable", "database": "down"} + assert "internal" not in resp.text and "5432" not in resp.text + + +async def test_hanging_database_returns_503_within_the_timeout(client, monkeypatch): + async def _hang(): + await asyncio.sleep(30) + + monkeypatch.setattr("app.main._probe_database", _hang) + monkeypatch.setattr(settings, "health_db_timeout_s", 0.1) + loop = asyncio.get_running_loop() + began = loop.time() + resp = await client.get("/health") + assert resp.status_code == 503 + assert loop.time() - began < 3 + + +async def test_it_really_queries_the_database(client, monkeypatch): + """The probe goes through the engine: a broken engine means 503.""" + class _Broken: + def connect(self): + raise OperationalError("connect", {}, Exception("no route")) + + monkeypatch.setattr("app.main.engine", _Broken()) + assert (await client.get("/health")).status_code == 503 From 2de63d19391b2d0556acede73bde72abfc2cf176 Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 12:25:43 -0800 Subject: [PATCH 11/45] feat: delete Azure search documents when runs are deleted index_run now uses the run id as the document id, so a run's document can be found by an exact doc_id filter; older documents are found by their text and only deleted when the full run id is in it. The admin reset route removes the documents of exactly the runs it is about to delete, before deleting them; if Azure fails it returns 502 and keeps the rows so no orphan can be left. Deletion is skipped when Azure Search is not configured. Co-Authored-By: Claude Sonnet 5.5 --- backend/app/api/runs.py | 34 ++++- backend/app/services/indexer.py | 77 ++++++++++ backend/tests/test_index_cleanup.py | 223 ++++++++++++++++++++++++++++ 3 files changed, 326 insertions(+), 8 deletions(-) create mode 100644 backend/tests/test_index_cleanup.py diff --git a/backend/app/api/runs.py b/backend/app/api/runs.py index 5eb3a8b..b0038e6 100644 --- a/backend/app/api/runs.py +++ b/backend/app/api/runs.py @@ -24,7 +24,7 @@ SlaResult, ) from app.services.aggregator import compute_metrics -from app.services.indexer import index_run +from app.services.indexer import delete_run_documents, index_run from app.services.quotas import QuotaExceeded, admission_lock, check_quotas from app.services.runner import run_benchmark, run_llm_benchmark from app.services.ssrf import TargetRejected, validate_target @@ -452,14 +452,32 @@ async def reset_session( if include_demo is None: include_demo = not settings.auth_enabled - # Bulk ORM delete: issues a single DELETE FROM runs to the DB. - # The DB-level ondelete="CASCADE" on metrics.run_id handles removing - # all child metrics rows — ORM-level cascade doesn't fire for bulk deletes, - # so relying on the FK cascade here is intentional and correct. - stmt = delete(Run) + # Select first: the same ids drive both the index cleanup and the delete, + # so a run created meanwhile is neither orphaned nor removed unexpectedly. + id_query = select(Run.id) if not include_demo: - stmt = stmt.where(Run.access_code_id.is_not(None)) - await db.execute(stmt) + id_query = id_query.where(Run.access_code_id.is_not(None)) + run_ids: list[uuid.UUID] = [] + for run_id in (await db.execute(id_query)).scalars(): + run_ids.append(run_id) + + # Index documents go first. If Azure fails, nothing is deleted and the admin + # can retry; the other order could leave documents with no run behind them. + try: + await delete_run_documents(run_ids) + except Exception as exc: + logger.error("Could not delete search documents (%s); no runs were deleted", type(exc).__name__) + raise HTTPException( + status_code=502, + detail="Could not delete the runs' search documents; no runs were deleted. Try again.", + ) + + # Bulk ORM delete in batches of ids. The DB-level ondelete="CASCADE" on + # metrics.run_id removes child metrics rows (ORM-level cascade doesn't fire + # for bulk deletes, so relying on the FK cascade here is intentional). + batch_size = 500 + for start in range(0, len(run_ids), batch_size): + await db.execute(delete(Run).where(Run.id.in_(run_ids[start : start + batch_size]))) await db.commit() return {"message": "Session reset successfully"} diff --git a/backend/app/services/indexer.py b/backend/app/services/indexer.py index 5a299ff..325e74f 100644 --- a/backend/app/services/indexer.py +++ b/backend/app/services/indexer.py @@ -52,8 +52,11 @@ async def index_run( # access_code_id is the owner ("demo" or a code UUID). It is also a # filterable index field (see filterable_metadata_field_keys below) so # diagnose can restrict retrieval to own-or-demo runs inside the query. + # id_ is the run id so the stored doc_id field equals it; that is what lets + # delete_run_documents find (and remove) this run's document later. doc = Document( text=summary, + id_=str(run_id), metadata={"run_id": str(run_id), "access_code_id": access_code_id}, ) @@ -114,3 +117,77 @@ async def index_run( finally: await async_index_client.close() sync_index_client.close() + + +# --------------------------------------------------------------------------- +# Deleting documents +# --------------------------------------------------------------------------- + +def _search_client(): + """Async client for the configured index. A function so tests can replace it.""" + from azure.search.documents.aio import SearchClient + + return SearchClient( + endpoint=settings.azure_search_endpoint, + index_name=settings.azure_search_index, # the index name comes only from config + credential=AzureKeyCredential(settings.azure_search_key), + ) + + +async def _find_document_ids(client, run_id: uuid.UUID) -> list[str]: + """Index keys of every document that belongs to this run.""" + run_text = str(run_id) # a UUID prints as hex and hyphens: safe inside an OData string + found: list[str] = [] + + # Documents indexed by this version have doc_id == run id (exact, filterable). + results = await client.search( + search_text="*", filter=f"doc_id eq '{run_text}'", select=["id"], top=1000 + ) + async for item in results: + if item["id"] not in found: + found.append(item["id"]) + + # Documents indexed before that change have a random doc_id, but their text + # starts "Benchmark run against ...". Find them by phrase and confirm the + # id really is in the text before deleting, so a fuzzy match never deletes + # another run's document. + results = await client.search( + search_text=f'"{run_text}"', search_fields=["content"], select=["id", "content"], top=50 + ) + async for item in results: + if run_text in (item.get("content") or "") and item["id"] not in found: + found.append(item["id"]) + return found + + +async def delete_run_documents(run_ids: list[uuid.UUID]) -> int: + """ + Remove the search documents of the given runs, so deleting runs leaves no + orphans behind. Returns how many documents were deleted. Raises if Azure + reports a failure, so the caller can keep the database rows and retry. + Does nothing when Azure Search is not configured (local development). + """ + if not run_ids: + return 0 + if not settings.azure_search_endpoint or not settings.azure_search_key: + logger.info("Azure Search not configured; no index documents to delete") + return 0 + + client = _search_client() + deleted = 0 + try: + for run_id in run_ids: + keys = await _find_document_ids(client, run_id) + if not keys: + continue + documents = [] + for key in keys: + documents.append({"id": key}) + outcomes = await client.delete_documents(documents=documents) + for outcome in outcomes: + if not outcome.succeeded: + raise RuntimeError(f"Azure Search did not delete a document of run {run_id}") + deleted += len(keys) + finally: + await client.close() + return deleted diff --git a/backend/tests/test_index_cleanup.py b/backend/tests/test_index_cleanup.py new file mode 100644 index 0000000..e47b425 --- /dev/null +++ b/backend/tests/test_index_cleanup.py @@ -0,0 +1,223 @@ +import pathlib +import uuid + +import pytest +from sqlalchemy import func, select + +from app.core.config import settings +from app.core.db import AsyncSessionLocal +from app.models.run import Run +from app.services import indexer +from tests.conftest import ADMIN, login, make_code, make_run + +RUN_A = uuid.UUID("11111111-1111-1111-1111-111111111111") +RUN_B = uuid.UUID("22222222-2222-2222-2222-222222222222") + + +class _Result: + def __init__(self, succeeded=True): + self.succeeded = succeeded + + +class _Pager: + def __init__(self, items): + self._items = items + + def __aiter__(self): + return self._gen() + + async def _gen(self): + for item in self._items: + yield item + + +class FakeIndex: + """Just enough of azure.search.documents.aio.SearchClient.""" + + def __init__(self, docs): + self.docs = docs # key -> {"doc_id":..., "content":...} + self.deleted: list[str] = [] + self.closed = False + self.fail_delete = False + self.queries: list[dict] = [] + + async def search(self, search_text, filter=None, select=None, top=None, search_fields=None): + self.queries.append({"text": search_text, "filter": filter, "fields": search_fields}) + items = [] + for key, doc in self.docs.items(): + if filter is not None: + wanted = filter.split("'")[1] + if doc["doc_id"] == wanted: + items.append({"id": key}) + else: + # Fuzzy text search: returns anything sharing a token with the phrase. + token = search_text.strip('"').split("-")[0] + if token in doc["content"]: + items.append({"id": key, "content": doc["content"]}) + return _Pager(items) + + async def delete_documents(self, documents): + results = [] + for document in documents: + if self.fail_delete: + results.append(_Result(False)) + else: + self.deleted.append(document["id"]) + self.docs.pop(document["id"], None) + results.append(_Result(True)) + return results + + async def close(self): + self.closed = True + + +@pytest.fixture +def azure_on(monkeypatch): + monkeypatch.setattr(settings, "azure_search_endpoint", "https://search.example.test") + monkeypatch.setattr(settings, "azure_search_key", "test-key-not-real") + + +def install(monkeypatch, fake): + monkeypatch.setattr(indexer, "_search_client", lambda: fake) + + +async def test_documents_are_found_by_doc_id_and_deleted(azure_on, monkeypatch): + fake = FakeIndex({ + "k1": {"doc_id": str(RUN_A), "content": f"Benchmark run {RUN_A} against x"}, + "k2": {"doc_id": str(RUN_B), "content": f"Benchmark run {RUN_B} against y"}, + }) + install(monkeypatch, fake) + assert await indexer.delete_run_documents([RUN_A]) == 1 + assert fake.deleted == ["k1"] + assert "k2" in fake.docs + assert fake.closed is True + + +async def test_old_documents_with_a_random_doc_id_are_found_by_their_text(azure_on, monkeypatch): + fake = FakeIndex({ + "old": {"doc_id": "some-random-uuid", "content": f"Benchmark run {RUN_A} against x"}, + # Shares the first token (so the fuzzy search returns it) but is another run. + "other": {"doc_id": "another-random", "content": f"Benchmark run {uuid.UUID('11111111-9999-9999-9999-999999999999')} against z"}, + }) + install(monkeypatch, fake) + assert await indexer.delete_run_documents([RUN_A]) == 1 + assert fake.deleted == ["old"] + assert "other" in fake.docs # a fuzzy hit is not deleted unless the full id is in its text + + +async def test_a_run_with_no_documents_is_fine(azure_on, monkeypatch): + install(monkeypatch, FakeIndex({})) + assert await indexer.delete_run_documents([RUN_A, RUN_B]) == 0 + + +async def test_failure_to_delete_raises(azure_on, monkeypatch): + fake = FakeIndex({"k1": {"doc_id": str(RUN_A), "content": str(RUN_A)}}) + fake.fail_delete = True + install(monkeypatch, fake) + with pytest.raises(RuntimeError): + await indexer.delete_run_documents([RUN_A]) + assert fake.closed is True + + +async def test_nothing_happens_when_azure_is_not_configured(monkeypatch): + monkeypatch.setattr(settings, "azure_search_endpoint", "") + monkeypatch.setattr(settings, "azure_search_key", "") + + def _boom(): + raise AssertionError("must not create a client") + + monkeypatch.setattr(indexer, "_search_client", _boom) + assert await indexer.delete_run_documents([RUN_A]) == 0 + + +async def test_filter_uses_only_a_uuid_string(azure_on, monkeypatch): + fake = FakeIndex({}) + install(monkeypatch, fake) + await indexer.delete_run_documents([RUN_A]) + assert fake.queries[0]["filter"] == f"doc_id eq '{RUN_A}'" + + +def test_index_run_uses_the_run_id_as_the_document_id(): + from llama_index.core import Document + + doc = Document(text="t", id_=str(RUN_A), metadata={"run_id": str(RUN_A)}) + assert doc.doc_id == str(RUN_A) + source = pathlib.Path(indexer.__file__).read_text() + assert "id_=str(run_id)" in source + + +# --- through the API ----------------------------------------------------------- + +async def run_ids() -> set: + async with AsyncSessionLocal() as session: + return set((await session.execute(select(Run.id))).scalars().all()) + + +async def test_reset_deletes_index_documents_for_exactly_the_deleted_runs(client, monkeypatch): + a_id, _ = await make_code("alpha-recruiter") + own1, own2 = await make_run(a_id), await make_run(a_id) + demo = await make_run(None) + seen = [] + + async def _record(ids): + seen.append(set(ids)) + return len(ids) + + monkeypatch.setattr("app.api.runs.delete_run_documents", _record) + resp = await client.delete("/benchmark/runs", headers=ADMIN) + assert resp.status_code == 200 + # Default on a hosted deployment keeps the demo runs, so their documents stay too. + assert seen == [{own1, own2}] + assert await run_ids() == {demo} + + seen.clear() + resp = await client.delete("/benchmark/runs?include_demo=true", headers=ADMIN) + assert resp.status_code == 200 + assert seen == [{demo}] + assert await run_ids() == set() + + +async def test_reset_keeps_the_runs_if_the_index_cannot_be_cleaned(client, monkeypatch): + a_id, _ = await make_code("alpha-recruiter") + own = await make_run(a_id) + + async def _fail(ids): + raise RuntimeError("azure unavailable") + + monkeypatch.setattr("app.api.runs.delete_run_documents", _fail) + resp = await client.delete("/benchmark/runs", headers=ADMIN) + assert resp.status_code == 502 + assert "no runs were deleted" in resp.json()["detail"] + assert "azure unavailable" not in resp.text + assert await run_ids() == {own} + + +async def test_reset_with_nothing_to_delete_succeeds(client, monkeypatch): + called = [] + + async def _record(ids): + called.append(ids) + return 0 + + monkeypatch.setattr("app.api.runs.delete_run_documents", _record) + assert (await client.delete("/benchmark/runs", headers=ADMIN)).status_code == 200 + assert called == [[]] + + +async def test_metrics_are_still_removed_with_their_runs(client, monkeypatch): + from app.core.db import engine + from app.models.run import Metrics + + if engine.dialect.name == "sqlite": + pytest.skip("SQLite ignores ON DELETE CASCADE unless PRAGMA foreign_keys is on") + a_id, _ = await make_code("alpha-recruiter") + await make_run(a_id) + + async def _ok(ids): + return 0 + + monkeypatch.setattr("app.api.runs.delete_run_documents", _ok) + await client.delete("/benchmark/runs", headers=ADMIN) + async with AsyncSessionLocal() as session: + count = (await session.execute(select(func.count()).select_from(Metrics))).scalar_one() + assert count == 0 From a4cc9f5d05eee26a76b9f023dfd6ae91a07f44eb Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 12:27:08 -0800 Subject: [PATCH 12/45] feat: add standalone demo target service with Dockerfile A small FastAPI service (separate from the backend, since the backend must refuse loopback targets) with latency_ms, jitter_ms, error_rate and error_status query parameters. It has its own caps: delay limit with 422 on excess, an in-flight limit with immediate 503, no body reads, a fixed tiny response, GET/POST only and no docs endpoints. The Dockerfile runs it as an unprivileged user with a connection limit and a health check. Co-Authored-By: Claude Sonnet 5.5 --- demo-target/.dockerignore | 6 ++ demo-target/Dockerfile | 27 +++++++ demo-target/README.md | 73 +++++++++++++++++ demo-target/pytest.ini | 3 + demo-target/requirements.txt | 2 + demo-target/server.py | 130 +++++++++++++++++++++++++++++++ demo-target/tests/test_server.py | 129 ++++++++++++++++++++++++++++++ 7 files changed, 370 insertions(+) create mode 100644 demo-target/.dockerignore create mode 100644 demo-target/Dockerfile create mode 100644 demo-target/README.md create mode 100644 demo-target/pytest.ini create mode 100644 demo-target/requirements.txt create mode 100644 demo-target/server.py create mode 100644 demo-target/tests/test_server.py diff --git a/demo-target/.dockerignore b/demo-target/.dockerignore new file mode 100644 index 0000000..4cde88d --- /dev/null +++ b/demo-target/.dockerignore @@ -0,0 +1,6 @@ +tests/ +__pycache__/ +*.pyc +.pytest_cache/ +README.md +pytest.ini diff --git a/demo-target/Dockerfile b/demo-target/Dockerfile new file mode 100644 index 0000000..f78c71b --- /dev/null +++ b/demo-target/Dockerfile @@ -0,0 +1,27 @@ +FROM python:3.11-slim + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 + +# Run as an unprivileged user with no home directory and no shell. +RUN useradd --system --uid 10001 --no-create-home --shell /usr/sbin/nologin demo + +WORKDIR /srv + +# Dependencies first so this layer is cached until requirements.txt changes. +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY server.py . + +USER 10001 +EXPOSE 8080 + +# Container-level liveness check using only the standard library. +HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ + CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8080/health', timeout=2).status == 200 else 1)" + +# --limit-concurrency makes uvicorn itself answer 503 beyond 100 open connections, +# on top of the app's own in-flight cap. Caps can be changed with DEMO_MAX_* env vars. +CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "8080", \ + "--limit-concurrency", "100", "--timeout-keep-alive", "5", "--no-server-header"] diff --git a/demo-target/README.md b/demo-target/README.md new file mode 100644 index 0000000..9c68567 --- /dev/null +++ b/demo-target/README.md @@ -0,0 +1,73 @@ +# QueryScope demo target + +A small standalone service that QueryScope benchmarks can safely call. It has +configurable artificial latency and error rate, and its own limits so it cannot be +abused. + +It is a separate service on purpose. The QueryScope backend refuses loopback and +private addresses (SSRF protection), so a demo route inside the backend would be +unreachable. Deploy this with a public hostname instead. + +## Endpoints + +| Path | Methods | Purpose | +|---|---|---| +| `/work` | GET, POST | The benchmark target (query parameters below) | +| `/health` | GET | Liveness | + +`/work` parameters, all optional: + +| Parameter | Default | Meaning | +|---|---|---| +| `latency_ms` | 0 | Fixed delay before answering | +| `jitter_ms` | 0 | Extra random delay, uniform between 0 and this value | +| `error_rate` | 0 | Probability (0 to 1) of answering with an error status | +| `error_status` | 500 | Status for errors: 500, 502, 503 or 504 | + +Example: `/work?latency_ms=120&jitter_ms=40&error_rate=0.05&error_status=503` + +## Limits + +| Limit | Default | Setting | +|---|---|---| +| `latency_ms + jitter_ms` | 2000 ms (larger values get 422, not clamped) | `DEMO_MAX_LATENCY_MS` | +| Requests handled at once | 50 (more get an immediate 503) | `DEMO_MAX_INFLIGHT` | +| Declared request body | 10 KB (larger gets 413); bodies are never read | fixed | +| Open connections | 100 (uvicorn answers 503 beyond it) | `--limit-concurrency` in the Dockerfile | + +Responses are a fixed tiny JSON body and nothing from the request is echoed. There +are no docs or OpenAPI endpoints. For a stronger guarantee against raw request +floods, also put platform rate limiting in front of it. + +## Run it + +``` +pip install -r requirements.txt +uvicorn server:app --port 8080 +``` + +or + +``` +docker build -t queryscope-demo-target . +docker run --rm -p 8080:8080 queryscope-demo-target +``` + +## Use it from QueryScope + +1. Deploy it somewhere with a public hostname, for example `demo.example.com`. +2. Add that exact hostname to the backend's allowlist (exact match, no wildcards): + `ALLOWED_TARGET_HOSTS=httpbin.org,demo.example.com` +3. Benchmark `https://demo.example.com/work?latency_ms=100&error_rate=0.02`. + +The backend's SSRF checks still apply to it: the hostname must resolve to a public +address. For local development against a demo target on localhost, run the backend +with `BLOCK_PRIVATE_TARGETS=false` (and `AUTH_ENABLED=false`, which also turns the +allowlist off). + +## Tests + +``` +pip install -r requirements.txt pytest pytest-asyncio httpx +pytest +``` diff --git a/demo-target/pytest.ini b/demo-target/pytest.ini new file mode 100644 index 0000000..78c5011 --- /dev/null +++ b/demo-target/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +asyncio_mode = auto +testpaths = tests diff --git a/demo-target/requirements.txt b/demo-target/requirements.txt new file mode 100644 index 0000000..7dfa88d --- /dev/null +++ b/demo-target/requirements.txt @@ -0,0 +1,2 @@ +fastapi==0.111.1 +uvicorn==0.29.0 diff --git a/demo-target/server.py b/demo-target/server.py new file mode 100644 index 0000000..d4e3aab --- /dev/null +++ b/demo-target/server.py @@ -0,0 +1,130 @@ +""" +QueryScope demo target: a tiny HTTP service that benchmarks can safely hit. + +It is deliberately NOT a route on the QueryScope backend. The backend refuses to +call loopback and private addresses (SSRF protection), so a demo target inside +the backend process would be unreachable by design. Deploy this as its own +service with a public hostname and put that hostname on ALLOWED_TARGET_HOSTS. + + GET|POST /work?latency_ms=120&jitter_ms=40&error_rate=0.05&error_status=503 + GET /health + + latency_ms fixed delay before answering 0 .. DEMO_MAX_LATENCY_MS + jitter_ms extra random delay, uniform 0..jitter latency_ms + jitter_ms <= max + error_rate probability of an error response 0 .. 1 + error_status status used for errors 500, 502, 503 or 504 + +Its own caps, so it cannot be turned into a slow-response or load amplifier: + - delay is capped (default 2000 ms) and out-of-range values are rejected, not clamped + - at most DEMO_MAX_INFLIGHT requests are handled at once (default 50); more get + an immediate 503, so held-open connections cannot pile up + - responses are a fixed tiny JSON body; nothing from the request is echoed + - request bodies are never read, and a declared body over 10 KB gets 413 + - only GET and POST (and /health); no docs or OpenAPI endpoints +The Dockerfile also sets uvicorn's own connection limit. +""" +import asyncio +import os +import random +from dataclasses import dataclass + +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse + + +def _env_number(name: str, default: float) -> float: + raw = os.environ.get(name) + if raw is None or raw == "": + return default + try: + value = float(raw) + except ValueError: + return default + return value if value > 0 else default + + +@dataclass +class Limits: + max_latency_ms: float + max_inflight: int + max_body_bytes: int + + +# Read once at import. Tests change the attributes of this object. +LIMITS = Limits( + max_latency_ms=_env_number("DEMO_MAX_LATENCY_MS", 2000.0), + max_inflight=int(_env_number("DEMO_MAX_INFLIGHT", 50)), + max_body_bytes=10_240, +) + +ERROR_STATUSES = (500, 502, 503, 504) + +# Single event loop thread: the counter needs no lock because there is no +# await between the check and the increment. +_state = {"inflight": 0} +_rng = random.Random() + +app = FastAPI( + title="QueryScope demo target", + docs_url=None, + redoc_url=None, + openapi_url=None, +) + + +def _number_param(request: Request, name: str, default: float) -> float: + raw = request.query_params.get(name) + if raw is None or raw == "": + return default + try: + value = float(raw) + except ValueError: + raise HTTPException(status_code=422, detail=f"{name} must be a number") + if value != value or value in (float("inf"), float("-inf")): + raise HTTPException(status_code=422, detail=f"{name} must be a finite number") + return value + + +@app.get("/health") +async def health() -> dict: + return {"status": "ok"} + + +@app.api_route("/work", methods=["GET", "POST"]) +async def work(request: Request) -> JSONResponse: + declared = request.headers.get("content-length") + if declared is not None and declared.isdigit() and int(declared) > LIMITS.max_body_bytes: + return JSONResponse({"detail": "request body too large"}, status_code=413) + + latency_ms = _number_param(request, "latency_ms", 0.0) + jitter_ms = _number_param(request, "jitter_ms", 0.0) + error_rate = _number_param(request, "error_rate", 0.0) + status_raw = _number_param(request, "error_status", 500.0) + + if latency_ms < 0 or jitter_ms < 0: + raise HTTPException(status_code=422, detail="latency_ms and jitter_ms must be 0 or more") + if latency_ms + jitter_ms > LIMITS.max_latency_ms: + raise HTTPException( + status_code=422, + detail=f"latency_ms + jitter_ms must be at most {LIMITS.max_latency_ms:g}", + ) + if error_rate < 0 or error_rate > 1: + raise HTTPException(status_code=422, detail="error_rate must be between 0 and 1") + if status_raw != int(status_raw) or int(status_raw) not in ERROR_STATUSES: + raise HTTPException(status_code=422, detail="error_status must be one of 500, 502, 503, 504") + error_status = int(status_raw) + + if _state["inflight"] >= LIMITS.max_inflight: + return JSONResponse( + {"detail": "demo target is at capacity"}, status_code=503, headers={"Retry-After": "1"} + ) + _state["inflight"] += 1 + try: + delay_ms = latency_ms + (_rng.random() * jitter_ms if jitter_ms > 0 else 0.0) + if delay_ms > 0: + await asyncio.sleep(delay_ms / 1000.0) + if error_rate > 0 and _rng.random() < error_rate: + return JSONResponse({"ok": False}, status_code=error_status) + return JSONResponse({"ok": True, "delay_ms": round(delay_ms, 1)}) + finally: + _state["inflight"] -= 1 diff --git a/demo-target/tests/test_server.py b/demo-target/tests/test_server.py new file mode 100644 index 0000000..d82c22c --- /dev/null +++ b/demo-target/tests/test_server.py @@ -0,0 +1,129 @@ +import asyncio + +import httpx +import pytest + +import server + + +@pytest.fixture(autouse=True) +def _reset(monkeypatch): + monkeypatch.setattr(server.LIMITS, "max_latency_ms", 2000.0) + monkeypatch.setattr(server.LIMITS, "max_inflight", 50) + server._state["inflight"] = 0 + + +@pytest.fixture +async def client(): + transport = httpx.ASGITransport(app=server.app) + async with httpx.AsyncClient(transport=transport, base_url="http://demo") as c: + yield c + + +async def test_health(client): + resp = await client.get("/health") + assert resp.status_code == 200 and resp.json() == {"status": "ok"} + + +async def test_defaults_answer_immediately_with_ok(client): + resp = await client.get("/work") + assert resp.status_code == 200 + assert resp.json() == {"ok": True, "delay_ms": 0.0} + + +async def test_post_is_accepted_and_the_body_is_ignored(client): + resp = await client.post("/work", json={"anything": "here"}) + assert resp.status_code == 200 + + +async def test_latency_is_applied(client): + loop = asyncio.get_running_loop() + began = loop.time() + resp = await client.get("/work?latency_ms=150") + assert resp.status_code == 200 + assert loop.time() - began >= 0.14 + assert resp.json()["delay_ms"] == 150.0 + + +async def test_jitter_adds_a_bounded_random_delay(client, monkeypatch): + monkeypatch.setattr(server._rng, "random", lambda: 0.5) + resp = await client.get("/work?latency_ms=20&jitter_ms=40") + assert resp.json()["delay_ms"] == 40.0 # 20 + 0.5 * 40 + + +async def test_error_rate_one_always_fails_with_the_chosen_status(client): + for status in (500, 502, 503, 504): + resp = await client.get(f"/work?error_rate=1&error_status={status}") + assert resp.status_code == status + assert resp.json() == {"ok": False} + + +async def test_error_rate_zero_never_fails(client): + for _ in range(100): + assert (await client.get("/work?error_rate=0")).status_code == 200 + + +async def test_error_rate_is_a_probability(client, monkeypatch): + draws = iter([0.01, 0.99, 0.30, 0.04]) + monkeypatch.setattr(server._rng, "random", lambda: next(draws)) + statuses = [] + for _ in range(4): + statuses.append((await client.get("/work?error_rate=0.05")).status_code) + assert statuses == [500, 200, 200, 500] + + +async def test_values_beyond_the_caps_are_rejected_not_clamped(client): + for query in [ + "latency_ms=2001", "latency_ms=1500&jitter_ms=600", "jitter_ms=99999", "latency_ms=-1", + "jitter_ms=-5", "error_rate=1.01", "error_rate=-0.1", "error_status=200", "error_status=404", + "error_status=500.5", "latency_ms=abc", "latency_ms=nan", "latency_ms=inf", "error_rate=nan", + ]: + resp = await client.get(f"/work?{query}") + assert resp.status_code == 422, query + + +async def test_the_latency_cap_is_a_setting(client, monkeypatch): + monkeypatch.setattr(server.LIMITS, "max_latency_ms", 100.0) + assert (await client.get("/work?latency_ms=101")).status_code == 422 + assert (await client.get("/work?latency_ms=100")).status_code == 200 + + +async def test_requests_beyond_the_inflight_cap_get_503_immediately(client, monkeypatch): + monkeypatch.setattr(server.LIMITS, "max_inflight", 2) + slow = [] + for _ in range(2): + slow.append(asyncio.create_task(client.get("/work?latency_ms=400"))) + await asyncio.sleep(0.1) # both are now sleeping inside the handler + loop = asyncio.get_running_loop() + began = loop.time() + extra = await client.get("/work?latency_ms=400") + assert extra.status_code == 503 + assert extra.headers["retry-after"] == "1" + assert loop.time() - began < 0.2 # refused at once, not queued + for response in await asyncio.gather(*slow): + assert response.status_code == 200 + assert server._state["inflight"] == 0 # slots are released + assert (await client.get("/work")).status_code == 200 + + +async def test_inflight_is_released_when_a_request_errors(client): + for _ in range(5): + await client.get("/work?error_rate=1") + assert server._state["inflight"] == 0 + + +async def test_a_declared_large_body_is_refused(client): + resp = await client.post("/work", content=b"x" * 20_000) + assert resp.status_code == 413 + + +async def test_other_methods_and_paths_are_not_available(client): + for method in ("PUT", "DELETE", "PATCH"): + assert (await client.request(method, "/work")).status_code == 405 + for path in ("/docs", "/redoc", "/openapi.json", "/", "/admin"): + assert (await client.get(path)).status_code == 404 + + +async def test_nothing_from_the_request_is_echoed(client): + resp = await client.get("/work?latency_ms=1&x=") + assert "script" not in resp.text From eb8cca6fce2c14382a0e54da42beadc3d67094c5 Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 12:27:20 -0800 Subject: [PATCH 13/45] test: use an explicit loop instead of a generator expression Co-Authored-By: Claude Sonnet 5.5 --- backend/tests/test_quotas.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/backend/tests/test_quotas.py b/backend/tests/test_quotas.py index 776d2c9..0a106d8 100644 --- a/backend/tests/test_quotas.py +++ b/backend/tests/test_quotas.py @@ -98,8 +98,10 @@ async def test_limits_are_read_from_settings(client, monkeypatch): async def test_simultaneous_requests_cannot_both_pass_the_check(client): _, a_h = await user(client, "alpha-recruiter") responses = await asyncio.gather(start(client, a_h), start(client, a_h), start(client, a_h)) - codes = sorted(r.status_code for r in responses) - assert codes == [202, 429, 429] + codes = [] + for response in responses: + codes.append(response.status_code) + assert sorted(codes) == [202, 429, 429] assert await run_count() == 1 From 11ad7a071b1173ea74129d4a14e97bd1e820ffc8 Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 12:27:47 -0800 Subject: [PATCH 14/45] docs: document guardrail settings and guard the index name config Add the guardrail variables and defaults to .env.example and a Guardrails section to the backend README. A test asserts that no code hard-codes the Azure index name, so a separate production index only needs AZURE_SEARCH_INDEX. Co-Authored-By: Claude Sonnet 5.5 --- backend/.env.example | 25 +++++++++++++++++++++++++ backend/README.md | 20 ++++++++++++++++++++ backend/tests/test_index_config.py | 23 +++++++++++++++++++++++ 3 files changed, 68 insertions(+) create mode 100644 backend/tests/test_index_config.py diff --git a/backend/.env.example b/backend/.env.example index 0b79e05..50e6651 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -15,3 +15,28 @@ CODE_PEPPER= ADMIN_API_KEY= # Hosted only: number of trusted proxy hops in front of the app (see config.py). TRUSTED_PROXY_HOPS=0 + +# --- Guardrails (hosted demo). Every value below shows its default. --------- +# Hard caps, enforced in the request schemas for every client. +MAX_NUM_REQUESTS=500 +MAX_CONCURRENCY=20 +MAX_REQUEST_TIMEOUT_S=10 +RUN_WALL_CLOCK_LIMIT_S=60 +# Usage limits, computed from the runs table. Enforced only when AUTH_ENABLED=true. +MAX_CONCURRENT_RUNS=2 +MAX_ACTIVE_RUNS_PER_CODE=1 +DAILY_BUDGET_PER_CODE=2000 +DAILY_BUDGET_GLOBAL=10000 +# Runs stuck pending/running past the wall-clock limit plus this grace are marked failed. +REAPER_GRACE_SECONDS=120 +REAPER_INTERVAL_SECONDS=60 +# SSRF protection: refuse loopback, private, link-local, CGNAT, multicast and +# reserved targets. Keep true when hosted; false only for local development +# against localhost services. +BLOCK_PRIVATE_TARGETS=true +# Exact hostnames, comma-separated (no wildcards). Add your demo target's public +# hostname here. Enforced when AUTH_ENABLED=true unless TARGET_ALLOWLIST_ENABLED overrides it. +ALLOWED_TARGET_HOSTS=httpbin.org +# TARGET_ALLOWLIST_ENABLED= +# LLM benchmark route: off when AUTH_ENABLED=true unless set here. +# LLM_BENCHMARK_ENABLED=false diff --git a/backend/README.md b/backend/README.md index d177b5d..9c05a7e 100644 --- a/backend/README.md +++ b/backend/README.md @@ -29,3 +29,23 @@ app/ ├── services/ # Business logic └── main.py # App factory ``` + +## Guardrails + +The hosted demo limits what a run can do. All limits are settings (see +`.env.example`): + +- **SSRF**: targets must be http(s) and must not be, or resolve to, loopback, + private, link-local (including 169.254.169.254), CGNAT, multicast or reserved + addresses, or their IPv6 equivalents. The name is resolved before each run and + the connections are pinned to the validated addresses, so DNS cannot change + the destination afterwards. Redirects are not followed. +- **Allowlist**: `ALLOWED_TARGET_HOSTS`, exact hostnames, on by default when auth + is enabled. The demo target service in `../demo-target` goes on this list. +- **Caps**: 500 requests, concurrency 20, 10 s per request, 60 s per run. +- **Quotas** (auth enabled): 2 runs at once overall, 1 per access code, and a daily + request budget per code and overall; exceeding one returns 429. +- **Reaper**: runs stuck pending/running past the wall-clock limit plus a grace + period are marked failed at startup and every minute. +- **LLM benchmark**: `POST /benchmark/llm` returns 404 unless `LLM_BENCHMARK_ENABLED`. +- **/health** returns 503 when the database cannot be reached. diff --git a/backend/tests/test_index_config.py b/backend/tests/test_index_config.py new file mode 100644 index 0000000..166d25a --- /dev/null +++ b/backend/tests/test_index_config.py @@ -0,0 +1,23 @@ +import pathlib + +BACKEND = pathlib.Path(__file__).resolve().parent.parent + + +def test_index_name_comes_only_from_config(): + """ + Production uses its own Azure index (AZURE_SEARCH_INDEX), so local development + documents never reach it. That only holds if no code hard-codes an index name: + the single literal allowed is the default value in app/core/config.py. + """ + offenders = [] + for folder in ("app", "scripts"): + for path in sorted((BACKEND / folder).rglob("*.py")): + if "benchmark-runs" in path.read_text(): + offenders.append(str(path.relative_to(BACKEND))) + assert offenders == ["app/core/config.py"] + + +def test_every_index_client_reads_the_configured_name(): + for relative in ("app/services/indexer.py", "app/services/rca.py", "scripts/create_azure_index.py"): + source = (BACKEND / relative).read_text() + assert "settings.azure_search_index" in source, relative From d4a4c9d446292978726dcc6a7fbb59702432db9e Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 14:07:45 -0800 Subject: [PATCH 15/45] feat: add authenticated GET /config for caps, targets and feature flags --- backend/app/api/config.py | 61 +++++++++++++++++++++++++++ backend/app/core/config.py | 4 ++ backend/app/main.py | 2 + backend/tests/test_config_endpoint.py | 60 ++++++++++++++++++++++++++ 4 files changed, 127 insertions(+) create mode 100644 backend/app/api/config.py create mode 100644 backend/tests/test_config_endpoint.py diff --git a/backend/app/api/config.py b/backend/app/api/config.py new file mode 100644 index 0000000..acf6aa4 --- /dev/null +++ b/backend/app/api/config.py @@ -0,0 +1,61 @@ +from urllib.parse import urlsplit + +from fastapi import APIRouter, Depends +from pydantic import BaseModel + +from app.api.deps import get_principal +from app.core.config import settings + +router = APIRouter(tags=["config"], dependencies=[Depends(get_principal)]) + + +class TargetOption(BaseModel): + label: str + url: str + + +class CapsOut(BaseModel): + max_num_requests: int + max_concurrency: int + max_request_timeout_s: float + run_wall_clock_limit_s: float + + +class ConfigResponse(BaseModel): + caps: CapsOut + targets: list[TargetOption] + # True when the allowlist is off (local use): the UI may offer a free URL. + allow_custom_target: bool + llm_benchmark_enabled: bool + auth_enabled: bool + + +def _targets() -> list[TargetOption]: + """One option per allowed host, with a sensible default URL for each.""" + demo_host = (urlsplit(settings.demo_target_url).hostname or "").lower() + options: list[TargetOption] = [] + for host in settings.allowed_target_host_list: + if demo_host and host == demo_host: + options.append(TargetOption(label="QueryScope demo target", url=settings.demo_target_url)) + elif host == "httpbin.org": + options.append(TargetOption(label="httpbin.org", url="https://httpbin.org/get")) + else: + options.append(TargetOption(label=host, url=f"https://{host}/")) + return options + + +@router.get("/config", response_model=ConfigResponse) +async def get_config() -> ConfigResponse: + # Public limits only: nothing here is a secret, and no resolved addresses. + return ConfigResponse( + caps=CapsOut( + max_num_requests=settings.max_num_requests, + max_concurrency=settings.max_concurrency, + max_request_timeout_s=settings.max_request_timeout_s, + run_wall_clock_limit_s=settings.run_wall_clock_limit_s, + ), + targets=_targets(), + allow_custom_target=not settings.allowlist_enforced, + llm_benchmark_enabled=settings.llm_benchmark_active, + auth_enabled=settings.auth_enabled, + ) diff --git a/backend/app/core/config.py b/backend/app/core/config.py index fe20b28..4f6f3ce 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -76,6 +76,10 @@ class Settings(BaseSettings): # TARGET_ALLOWLIST_ENABLED overrides it either way. allowed_target_hosts: str = "httpbin.org" target_allowlist_enabled: bool | None = None + # Full URL of our own demo target (for example https://demo.example.com/work). + # Only used by GET /config so the UI can offer it; its host must also be in + # ALLOWED_TARGET_HOSTS to be accepted by the allowlist. + demo_target_url: str = "" # LLM benchmark route. Defaults to OFF when auth is on (it forwards a # caller-supplied API key to a caller-supplied endpoint); LLM_BENCHMARK_ENABLED # overrides it either way. diff --git a/backend/app/main.py b/backend/app/main.py index 15e92fa..7af8d88 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -11,6 +11,7 @@ from app.api.admin import router as admin_router from app.api.auth import router as auth_router +from app.api.config import router as config_router from app.api.runs import admin_router as runs_admin_router from app.api.runs import router as runs_router from app.core.config import settings @@ -83,6 +84,7 @@ async def health(): app.include_router(auth_router) app.include_router(admin_router) + app.include_router(config_router) app.include_router(runs_admin_router) # prefix="" because the router already carries /benchmark and /runs prefixes app.include_router(runs_router) diff --git a/backend/tests/test_config_endpoint.py b/backend/tests/test_config_endpoint.py new file mode 100644 index 0000000..c34e774 --- /dev/null +++ b/backend/tests/test_config_endpoint.py @@ -0,0 +1,60 @@ +from app.core.config import settings +from tests.conftest import login, make_code, make_run + + +async def auth(client, label="cfg-recruiter"): + code_id, code = await make_code(label) + return code_id, await login(client, code) + + +async def test_config_requires_a_session(client): + assert (await client.get("/config")).status_code == 401 + + +async def test_config_reports_caps_targets_and_flags(client, monkeypatch): + monkeypatch.setattr(settings, "allowed_target_hosts", "httpbin.org,demo.example.com") + monkeypatch.setattr(settings, "demo_target_url", "https://demo.example.com/work") + monkeypatch.setattr(settings, "llm_benchmark_enabled", None) + _, h = await auth(client) + body = (await client.get("/config", headers=h)).json() + + assert body["caps"]["max_num_requests"] == settings.max_num_requests + assert body["caps"]["max_concurrency"] == settings.max_concurrency + assert body["caps"]["max_request_timeout_s"] == settings.max_request_timeout_s + assert body["targets"] == [ + {"label": "httpbin.org", "url": "https://httpbin.org/get"}, + {"label": "QueryScope demo target", "url": "https://demo.example.com/work"}, + ] + assert body["allow_custom_target"] is False + assert body["llm_benchmark_enabled"] is False + + +async def test_config_follows_the_llm_flag(client, monkeypatch): + monkeypatch.setattr(settings, "llm_benchmark_enabled", True) + _, h = await auth(client) + assert (await client.get("/config", headers=h)).json()["llm_benchmark_enabled"] is True + + +async def test_config_allows_custom_target_when_allowlist_is_off(client, monkeypatch): + monkeypatch.setattr(settings, "target_allowlist_enabled", False) + _, h = await auth(client) + assert (await client.get("/config", headers=h)).json()["allow_custom_target"] is True + + +async def test_runs_are_flagged_demo_unless_owned(client): + code_id, h = await auth(client, "demo-flag") + own = await make_run(code_id) + demo = await make_run(None) + items = (await client.get("/benchmark/runs", headers=h)).json()["items"] + flags = {} + for item in items: + flags[item["id"]] = item["is_demo"] + assert flags[str(own)] is False + assert flags[str(demo)] is True + + +async def test_nothing_is_demo_when_auth_is_off(client, monkeypatch): + monkeypatch.setattr(settings, "auth_enabled", False) + await make_run(None) + items = (await client.get("/benchmark/runs")).json()["items"] + assert items[0]["is_demo"] is False From 6c179cc8412eb103e1e50836728b7a95fc4824fb Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 14:07:45 -0800 Subject: [PATCH 16/45] feat: flag runs the caller cannot modify as is_demo --- backend/app/api/runs.py | 15 ++++++++++----- backend/app/schemas/run.py | 2 ++ 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/backend/app/api/runs.py b/backend/app/api/runs.py index b0038e6..89f0efb 100644 --- a/backend/app/api/runs.py +++ b/backend/app/api/runs.py @@ -276,7 +276,7 @@ async def list_runs( items = [] for r in runs: - items.append(_run_to_response(r, baseline=baseline)) + items.append(_run_to_response(r, baseline=baseline, caller_id=principal.code_id)) return PaginatedRuns(total=total, offset=offset, limit=limit, items=items) @@ -290,7 +290,7 @@ async def get_baseline_run(db: DB, principal: CurrentPrincipal) -> RunResponse: baseline = await effective_baseline(db, principal.code_id) if baseline is None: raise HTTPException(status_code=404, detail="No baseline run is set") - return _run_to_response(baseline, baseline=baseline) + return _run_to_response(baseline, baseline=baseline, caller_id=principal.code_id) # --------------------------------------------------------------------------- @@ -309,7 +309,7 @@ async def set_baseline( raise HTTPException(status_code=400, detail="Run is already the baseline") await _replace_baseline(db, run, owned_clause(principal.code_id)) - return _run_to_response(run, baseline=run) + return _run_to_response(run, baseline=run, caller_id=principal.code_id) # --------------------------------------------------------------------------- @@ -320,7 +320,7 @@ async def set_baseline( async def get_run(run_id: uuid.UUID, db: DB, principal: CurrentPrincipal) -> RunResponse: run = await _get_visible_run(db, run_id, principal) baseline = await effective_baseline(db, principal.code_id) - return _run_to_response(run, baseline=baseline) + return _run_to_response(run, baseline=baseline, caller_id=principal.code_id) # --------------------------------------------------------------------------- @@ -550,7 +550,9 @@ async def _replace_baseline(db: AsyncSession, run: Run, owner_scope) -> None: await db.refresh(run) -def _run_to_response(run: Run, baseline: "Run | None" = None) -> RunResponse: +def _run_to_response( + run: Run, baseline: "Run | None" = None, caller_id: uuid.UUID | None = None +) -> RunResponse: """ Map ORM Run → RunResponse. @@ -607,6 +609,9 @@ def _run_to_response(run: Run, baseline: "Run | None" = None) -> RunResponse: concurrency=run.concurrency, status=run.status, is_baseline=is_baseline, + # Not owned by the caller. With auth off the caller is the demo owner, + # so nothing is read-only locally. + is_demo=run.access_code_id != caller_id, created_at=run.created_at, metrics=metrics_summary, delta_p50_pct=delta_p50_pct, diff --git a/backend/app/schemas/run.py b/backend/app/schemas/run.py index 7ae3ff6..5cd3282 100644 --- a/backend/app/schemas/run.py +++ b/backend/app/schemas/run.py @@ -136,6 +136,8 @@ class RunResponse(BaseModel): concurrency: int status: RunStatus is_baseline: bool = False + # True for runs the caller cannot modify (shared demo runs). Read-only. + is_demo: bool = False created_at: datetime # None until the background task finishes persisting results. metrics: MetricsSummary | None = None From 253364d8a8297c08372aac286880053febff2c90 Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 14:10:06 -0800 Subject: [PATCH 17/45] feat: let callers clear their own baseline and expose Retry-After to browsers --- backend/app/api/runs.py | 19 ++++++++++++++++++ backend/app/main.py | 3 +++ backend/tests/test_config_endpoint.py | 29 +++++++++++++++++++++++++++ 3 files changed, 51 insertions(+) diff --git a/backend/app/api/runs.py b/backend/app/api/runs.py index 89f0efb..1d47d9e 100644 --- a/backend/app/api/runs.py +++ b/backend/app/api/runs.py @@ -293,6 +293,25 @@ async def get_baseline_run(db: DB, principal: CurrentPrincipal) -> RunResponse: return _run_to_response(baseline, baseline=baseline, caller_id=principal.code_id) +# --------------------------------------------------------------------------- +# DELETE /runs/baseline — clear the caller's own baseline. Afterwards the +# demo baseline (if any) applies again. Callers never touch the demo baseline. +# --------------------------------------------------------------------------- + +@router.delete("/runs/baseline", status_code=200) +async def clear_baseline(db: DB, principal: CurrentPrincipal) -> dict[str, str]: + result = await db.execute( + update(Run) + .where(and_(owned_clause(principal.code_id), Run.is_baseline == True)) # noqa: E712 + .values(is_baseline=False) + .execution_options(synchronize_session=False) + ) + if result.rowcount == 0: + raise HTTPException(status_code=404, detail="You have no baseline to clear") + await db.commit() + return {"message": "Baseline cleared"} + + # --------------------------------------------------------------------------- # PATCH /runs/{run_id}/baseline # --------------------------------------------------------------------------- diff --git a/backend/app/main.py b/backend/app/main.py index 7af8d88..e46ad82 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -63,6 +63,9 @@ def create_app() -> FastAPI: allow_methods=["*"], allow_headers=["*"], allow_credentials=False, + # Browsers hide Retry-After from cross-origin scripts unless exposed; + # the UI uses it for "try again in N minutes". + expose_headers=["Retry-After"], ) @app.get("/health") diff --git a/backend/tests/test_config_endpoint.py b/backend/tests/test_config_endpoint.py index c34e774..39ba648 100644 --- a/backend/tests/test_config_endpoint.py +++ b/backend/tests/test_config_endpoint.py @@ -58,3 +58,32 @@ async def test_nothing_is_demo_when_auth_is_off(client, monkeypatch): await make_run(None) items = (await client.get("/benchmark/runs")).json()["items"] assert items[0]["is_demo"] is False + + +async def test_caller_can_clear_their_own_baseline(client): + code_id, h = await auth(client, "clear-own") + run = await make_run(code_id, baseline=True) + demo = await make_run(None, baseline=True) + + assert (await client.delete("/benchmark/runs/baseline", headers=h)).status_code == 200 + # Own baseline is gone, so the demo baseline applies again. + baseline = (await client.get("/benchmark/runs/baseline", headers=h)).json() + assert baseline["id"] == str(demo) + assert baseline["id"] != str(run) + + +async def test_clearing_never_touches_the_demo_baseline(client): + _, h = await auth(client, "clear-demo") + demo = await make_run(None, baseline=True) + # Nothing of their own to clear: 404, and the demo baseline stays. + assert (await client.delete("/benchmark/runs/baseline", headers=h)).status_code == 404 + assert (await client.get("/benchmark/runs/baseline", headers=h)).json()["id"] == str(demo) + + +async def test_clear_baseline_requires_a_session(client): + assert (await client.delete("/benchmark/runs/baseline")).status_code == 401 + + +async def test_retry_after_is_exposed_to_browsers(client): + resp = await client.get("/health", headers={"Origin": "http://localhost:5173"}) + assert "retry-after" in resp.headers.get("access-control-expose-headers", "").lower() From 6049492cabc645886cd9f7eb3786ac6fb54f0b00 Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 14:13:53 -0800 Subject: [PATCH 18/45] build: add Vitest with jsdom and testing-library --- frontend/package-lock.json | 1633 +++++++++++++++++++++++++++++++++- frontend/package.json | 10 +- frontend/src/test/fakeApi.ts | 41 + frontend/src/test/setup.ts | 8 + frontend/vite.config.ts | 12 +- 5 files changed, 1659 insertions(+), 45 deletions(-) create mode 100644 frontend/src/test/fakeApi.ts create mode 100644 frontend/src/test/setup.ts diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 5f643ae..acc5af4 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -15,6 +15,9 @@ }, "devDependencies": { "@eslint/js": "^9.39.4", + "@testing-library/jest-dom": "^7.0.1", + "@testing-library/react": "^16.3.3", + "@testing-library/user-event": "^14.6.8", "@types/node": "^24.12.0", "@types/react": "^19.2.14", "@types/react-dom": "^19.2.3", @@ -24,11 +27,71 @@ "eslint-plugin-react-hooks": "^7.0.1", "eslint-plugin-react-refresh": "^0.5.2", "globals": "^17.4.0", + "jsdom": "^29.1.1", "typescript": "~5.9.3", "typescript-eslint": "^8.57.0", - "vite": "^8.0.1" + "vite": "^8.0.1", + "vitest": "^5.1.0" } }, + "node_modules/@adobe/css-tools": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.5.0.tgz", + "integrity": "sha512-6OzddxPio9UiWTCemp4N8cYLV2ZN1ncRnV1cVGtve7dhPOtRkleRyx32GQCYSwDYgaHU3USMm84tNsvKzRCa1Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@asamuzakjp/css-color": { + "version": "5.1.11", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-5.1.11.tgz", + "integrity": "sha512-KVw6qIiCTUQhByfTd78h2yD1/00waTmm9uy/R7Ck/ctUyAPj+AEDLkQIdJW0T8+qGgj3j5bpNKK7Q3G+LedJWg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/generational-cache": "^1.0.1", + "@csstools/css-calc": "^3.2.0", + "@csstools/css-color-parser": "^4.1.0", + "@csstools/css-parser-algorithms": "^4.0.0", + "@csstools/css-tokenizer": "^4.0.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, + "node_modules/@asamuzakjp/dom-selector": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-7.1.1.tgz", + "integrity": "sha512-67RZDnYRc8H/8MLDgQCDE//zoqVFwajkepHZgmXrbwybzXOEwOWGPYGmALYl9J2DOLfFPPs6kKCqmbzV895hTQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/generational-cache": "^1.0.1", + "@asamuzakjp/nwsapi": "^2.3.9", + "bidi-js": "^1.0.3", + "css-tree": "^3.2.1", + "is-potential-custom-element-name": "^1.0.1" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, + "node_modules/@asamuzakjp/generational-cache": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@asamuzakjp/generational-cache/-/generational-cache-1.0.1.tgz", + "integrity": "sha512-wajfB8KqzMCN2KGNFdLkReeHncd0AslUSrvHVvvYWuU8ghncRJoA50kT3zP9MVL0+9g4/67H+cdvBskj9THPzg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, + "node_modules/@asamuzakjp/nwsapi": { + "version": "2.3.9", + "resolved": "https://registry.npmjs.org/@asamuzakjp/nwsapi/-/nwsapi-2.3.9.tgz", + "integrity": "sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==", + "dev": true, + "license": "MIT" + }, "node_modules/@babel/code-frame": { "version": "7.29.0", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz", @@ -221,6 +284,16 @@ "node": ">=6.0.0" } }, + "node_modules/@babel/runtime": { + "version": "7.29.10", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.10.tgz", + "integrity": "sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, "node_modules/@babel/template": { "version": "7.28.6", "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz", @@ -261,46 +334,667 @@ "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==", "dev": true, "license": "MIT", - "dependencies": { - "@babel/helper-string-parser": "^7.27.1", - "@babel/helper-validator-identifier": "^7.28.5" - }, + "dependencies": { + "@babel/helper-string-parser": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@bramus/specificity": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.3.tgz", + "integrity": "sha512-0GEz8qJWokkUVYQYRukmkSHIFNoBH8QTreeHrAFbvz1XFYc3Y+puhMs8PQ5x8GNugiC2l5jvDBXKLbBIByeSBw==", + "dev": true, + "license": "MIT", + "dependencies": { + "css-tree": "^3.2.1" + }, + "bin": { + "specificity": "bin/cli.js" + } + }, + "node_modules/@csstools/color-helpers": { + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.2.tgz", + "integrity": "sha512-grhRy3OKmniaAEKXMjua5z/EODX0MSqBGjunw8+j/3HQjOnahs2AGhvEOIYVUWcU6ScApbhLhVrQTX8XqrMrow==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/@csstools/css-calc": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.4.3.tgz", + "integrity": "sha512-iex20d8CHVkyvg6B7UKV7uHnI2Bqo9g+EFfT9E0y+GvTvhZ/DwONJ+9aKb1dlqm0ZiGsL5RXjp0fCoJYnkeDjA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.2", + "@csstools/css-tokenizer": "^4.0.2" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "4.2.7", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.7.tgz", + "integrity": "sha512-zgm9yjQz5iJB4VL8RyVwd71TWB8Q89FSxt/NzXoWqPSkEBOVtn9L6vAPtSc9hpKfB0Awo/AL2VKFHjYetBLFHQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^6.1.2", + "@csstools/css-calc": "^3.4.3" + }, + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.2", + "@csstools/css-tokenizer": "^4.0.2" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.2.tgz", + "integrity": "sha512-40cSKyMvK+tq4qz6Awrlye2WGuOKt3FwPgtGg6KTfbHOWNw+Rk1rzbAtZnZ6IBhsY491HLRnDXwoyBAijmmILA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^4.0.2" + } + }, + "node_modules/@csstools/css-syntax-patches-for-csstree": { + "version": "1.1.16", + "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.16.tgz", + "integrity": "sha512-LsDbJPP/B8cPasUJyTA5S99F7C4G93ngW8hUluXz8CFeOaaRnBPtBiIlvgcPYU0HmHNz8CXg+1vwFrIB4F6Dgw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "peerDependencies": { + "css-tree": "^3.2.1" + }, + "peerDependenciesMeta": { + "css-tree": { + "optional": true + } + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.2.tgz", + "integrity": "sha512-OoKoR0f76dCY666JlcbhmVTs2drYj1GUXZTYTcbUgJjh9Nv41aFfZ21bPQTERm5+L5cBDo466NltB2lplS5GBw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/@emnapi/core": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.1.tgz", + "integrity": "sha512-mukuNALVsoix/w1BJwFzwXBN/dHeejQtuVzcDsfOEsdpCumXb/E9j8w11h5S54tT1xhifGfbbSm/ICrObRb3KA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.0", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.9.1.tgz", + "integrity": "sha512-VYi5+ZVLhpgK4hQ0TAjiQiZ6ol0oe4mBx7mVv7IflsiEp0OWoVsp/+f9Vc1hOhE0TtkORVrI1GvzyreqpgWtkA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.0.tgz", + "integrity": "sha512-N10dEJNSsUx41Z6pZsXU8FjPjpBEplgH24sfkmITrBED1/U2Esum9F3lfLrMjKHHjmi557zQn7kR9R+XWXu5Rg==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz", + "integrity": "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.7.tgz", + "integrity": "sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.7.tgz", + "integrity": "sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.7.tgz", + "integrity": "sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.7.tgz", + "integrity": "sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.7.tgz", + "integrity": "sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.7.tgz", + "integrity": "sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.7.tgz", + "integrity": "sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.7.tgz", + "integrity": "sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.7.tgz", + "integrity": "sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.7.tgz", + "integrity": "sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.7.tgz", + "integrity": "sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.7.tgz", + "integrity": "sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.7.tgz", + "integrity": "sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.7.tgz", + "integrity": "sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.7.tgz", + "integrity": "sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.7.tgz", + "integrity": "sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.7.tgz", + "integrity": "sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.7.tgz", + "integrity": "sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.7.tgz", + "integrity": "sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.7.tgz", + "integrity": "sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.7.tgz", + "integrity": "sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "peer": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.7.tgz", + "integrity": "sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "peer": true, "engines": { - "node": ">=6.9.0" + "node": ">=18" } }, - "node_modules/@emnapi/core": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.9.1.tgz", - "integrity": "sha512-mukuNALVsoix/w1BJwFzwXBN/dHeejQtuVzcDsfOEsdpCumXb/E9j8w11h5S54tT1xhifGfbbSm/ICrObRb3KA==", + "node_modules/@esbuild/win32-arm64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.7.tgz", + "integrity": "sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==", + "cpu": [ + "arm64" + ], "dev": true, "license": "MIT", "optional": true, - "dependencies": { - "@emnapi/wasi-threads": "1.2.0", - "tslib": "^2.4.0" + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": ">=18" } }, - "node_modules/@emnapi/runtime": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.9.1.tgz", - "integrity": "sha512-VYi5+ZVLhpgK4hQ0TAjiQiZ6ol0oe4mBx7mVv7IflsiEp0OWoVsp/+f9Vc1hOhE0TtkORVrI1GvzyreqpgWtkA==", + "node_modules/@esbuild/win32-ia32": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.7.tgz", + "integrity": "sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==", + "cpu": [ + "ia32" + ], "dev": true, "license": "MIT", "optional": true, - "dependencies": { - "tslib": "^2.4.0" + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": ">=18" } }, - "node_modules/@emnapi/wasi-threads": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.0.tgz", - "integrity": "sha512-N10dEJNSsUx41Z6pZsXU8FjPjpBEplgH24sfkmITrBED1/U2Esum9F3lfLrMjKHHjmi557zQn7kR9R+XWXu5Rg==", + "node_modules/@esbuild/win32-x64": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.7.tgz", + "integrity": "sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==", + "cpu": [ + "x64" + ], "dev": true, "license": "MIT", "optional": true, - "dependencies": { - "tslib": "^2.4.0" + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": ">=18" } }, "node_modules/@eslint-community/eslint-utils": { @@ -460,6 +1154,24 @@ "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, + "node_modules/@exodus/bytes": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz", + "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "@noble/hashes": "^1.8.0 || ^2.0.0" + }, + "peerDependenciesMeta": { + "@noble/hashes": { + "optional": true + } + } + }, "node_modules/@humanfs/core": { "version": "0.19.1", "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz", @@ -545,9 +1257,9 @@ } }, "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.5", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", - "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", "dev": true, "license": "MIT" }, @@ -899,6 +1611,105 @@ "integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==", "license": "MIT" }, + "node_modules/@testing-library/dom": { + "version": "10.4.2", + "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.2.tgz", + "integrity": "sha512-yzr2S9HyAIdhz2/6qHgbs665Q7PKVcDF05vsOlHPxG1mo36gKVesdYVeDLnXgfjJ03CrKRk08knc6+E/9m8v2Q==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@babel/code-frame": "^7.10.4", + "@babel/runtime": "^7.12.5", + "@types/aria-query": "^5.0.1", + "aria-query": "5.3.0", + "dom-accessibility-api": "^0.5.9", + "lz-string": "^1.5.0", + "picocolors": "1.1.1", + "pretty-format": "^27.0.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@testing-library/jest-dom": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-7.0.1.tgz", + "integrity": "sha512-oMDTC3oA+6CXSO2JZnvOI7CA6oVub6kij5ggk9ohwye5slmkwxYDXcPOVxgMw/RQlticjtO0C1RZkR97HgrWMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@adobe/css-tools": "^4.4.0", + "aria-query": "^5.0.0", + "css.escape": "^1.5.1", + "dom-accessibility-api": "^0.6.3", + "picocolors": "^1.1.1", + "redent": "^3.0.0" + }, + "engines": { + "node": ">=22", + "npm": ">=6", + "yarn": ">=1" + }, + "peerDependencies": { + "@testing-library/dom": ">=10 <11", + "vitest": ">= 0.32" + }, + "peerDependenciesMeta": { + "vitest": { + "optional": true + } + } + }, + "node_modules/@testing-library/jest-dom/node_modules/dom-accessibility-api": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.6.3.tgz", + "integrity": "sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@testing-library/react": { + "version": "16.3.3", + "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-16.3.3.tgz", + "integrity": "sha512-Uo193NgQbPMz6lrrhtRQQFcMC6Re/ELLFbbuVL30WDlZxlpZf9/lMHTAVxPRLw1q1iu9OJmR1c2BLiENRstdBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.12.5" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@testing-library/dom": "^10.0.0", + "@types/react": "^18.0.0 || ^19.0.0", + "@types/react-dom": "^18.0.0 || ^19.0.0", + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, + "node_modules/@testing-library/user-event": { + "version": "14.6.8", + "resolved": "https://registry.npmjs.org/@testing-library/user-event/-/user-event-14.6.8.tgz", + "integrity": "sha512-vgSSqnANMnkcYR/vUNDbwS7aM3OErRLNUG8vCVVlj4oc6cKffUrccX7UAS5AmJQQNZTSibi9z5GvvRZ0aYgUCQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12", + "npm": ">=6" + }, + "peerDependencies": { + "@testing-library/dom": ">=7.21.4" + } + }, "node_modules/@tybys/wasm-util": { "version": "0.10.1", "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.1.tgz", @@ -910,6 +1721,25 @@ "tslib": "^2.4.0" } }, + "node_modules/@types/aria-query": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz", + "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, "node_modules/@types/d3-array": { "version": "3.2.2", "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz", @@ -973,10 +1803,17 @@ "integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==", "license": "MIT" }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/estree": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", - "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", "dev": true, "license": "MIT" }, @@ -1372,6 +2209,44 @@ } } }, + "node_modules/@vitest/mocker": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.1.0.tgz", + "integrity": "sha512-5umB9/jlWcqVS6fsrFmv5Gdnpu6wAUio/lEOwAmvB7v+lFo/IW2B9FhAD0p19GCULTgMzLCdUmuCDCnAzWgppQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.1.0", + "estree-walker": "^3.0.3", + "magic-string": "^1.4.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9 || ^3.0.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/spy": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.1.0.tgz", + "integrity": "sha512-2DPO5OMHWKrBngC+fCmTQqemNF0gidRhp3lxbBmRhW+M1XJrfgPpqNqWVevXtn2f2ufD5ZaR1B6B641aAlcX5A==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, "node_modules/acorn": { "version": "8.16.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", @@ -1412,6 +2287,17 @@ "url": "https://github.com/sponsors/epoberezkin" } }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8" + } + }, "node_modules/ansi-styles": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", @@ -1435,6 +2321,26 @@ "dev": true, "license": "Python-2.0" }, + "node_modules/aria-query": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz", + "integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "dequal": "^2.0.3" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, "node_modules/asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", @@ -1472,6 +2378,16 @@ "node": ">=6.0.0" } }, + "node_modules/bidi-js": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.1.0.tgz", + "integrity": "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==", + "dev": true, + "license": "MIT", + "dependencies": { + "require-from-string": "^2.0.2" + } + }, "node_modules/brace-expansion": { "version": "1.1.12", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", @@ -1561,6 +2477,16 @@ ], "license": "CC-BY-4.0" }, + "node_modules/chai": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/chalk": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", @@ -1648,6 +2574,27 @@ "node": ">= 8" } }, + "node_modules/css-tree": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", + "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "mdn-data": "2.27.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, + "node_modules/css.escape": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/css.escape/-/css.escape-1.5.1.tgz", + "integrity": "sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==", + "dev": true, + "license": "MIT" + }, "node_modules/csstype": { "version": "3.2.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", @@ -1776,6 +2723,20 @@ "node": ">=12" } }, + "node_modules/data-urls": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-7.0.0.tgz", + "integrity": "sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^16.0.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", @@ -1794,6 +2755,13 @@ } } }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, "node_modules/decimal.js-light": { "version": "2.5.1", "resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz", @@ -1816,6 +2784,16 @@ "node": ">=0.4.0" } }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -1826,6 +2804,14 @@ "node": ">=8" } }, + "node_modules/dom-accessibility-api": { + "version": "0.5.16", + "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", + "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==", + "dev": true, + "license": "MIT", + "peer": true + }, "node_modules/dunder-proto": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", @@ -1847,6 +2833,19 @@ "dev": true, "license": "ISC" }, + "node_modules/entities": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-9.0.0.tgz", + "integrity": "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, "node_modules/es-define-property": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", @@ -1865,6 +2864,13 @@ "node": ">= 0.4" } }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, "node_modules/es-object-atoms": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", @@ -1902,6 +2908,50 @@ "benchmarks" ] }, + "node_modules/esbuild": { + "version": "0.27.7", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.7.tgz", + "integrity": "sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "peer": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.7", + "@esbuild/android-arm": "0.27.7", + "@esbuild/android-arm64": "0.27.7", + "@esbuild/android-x64": "0.27.7", + "@esbuild/darwin-arm64": "0.27.7", + "@esbuild/darwin-x64": "0.27.7", + "@esbuild/freebsd-arm64": "0.27.7", + "@esbuild/freebsd-x64": "0.27.7", + "@esbuild/linux-arm": "0.27.7", + "@esbuild/linux-arm64": "0.27.7", + "@esbuild/linux-ia32": "0.27.7", + "@esbuild/linux-loong64": "0.27.7", + "@esbuild/linux-mips64el": "0.27.7", + "@esbuild/linux-ppc64": "0.27.7", + "@esbuild/linux-riscv64": "0.27.7", + "@esbuild/linux-s390x": "0.27.7", + "@esbuild/linux-x64": "0.27.7", + "@esbuild/netbsd-arm64": "0.27.7", + "@esbuild/netbsd-x64": "0.27.7", + "@esbuild/openbsd-arm64": "0.27.7", + "@esbuild/openbsd-x64": "0.27.7", + "@esbuild/openharmony-arm64": "0.27.7", + "@esbuild/sunos-x64": "0.27.7", + "@esbuild/win32-arm64": "0.27.7", + "@esbuild/win32-ia32": "0.27.7", + "@esbuild/win32-x64": "0.27.7" + } + }, "node_modules/escalade": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", @@ -2099,6 +3149,16 @@ "node": ">=4.0" } }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, "node_modules/esutils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", @@ -2115,6 +3175,16 @@ "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==", "license": "MIT" }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", @@ -2413,7 +3483,20 @@ "dev": true, "license": "MIT", "dependencies": { - "hermes-estree": "0.25.1" + "hermes-estree": "0.25.1" + } + }, + "node_modules/html-encoding-sniffer": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz", + "integrity": "sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.6.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" } }, "node_modules/ignore": { @@ -2463,6 +3546,16 @@ "node": ">=0.8.19" } }, + "node_modules/indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/internmap": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz", @@ -2495,6 +3588,13 @@ "node": ">=0.10.0" } }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, "node_modules/isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", @@ -2522,6 +3622,57 @@ "js-yaml": "bin/js-yaml.js" } }, + "node_modules/jsdom": { + "version": "29.1.1", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-29.1.1.tgz", + "integrity": "sha512-ECi4Fi2f7BdJtUKTflYRTiaMxIB0O6zfR1fX0GXpUrf6flp8QIYn1UT20YQqdSOfk2dfkCwS8LAFoJDEppNK5Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^5.1.11", + "@asamuzakjp/dom-selector": "^7.1.1", + "@bramus/specificity": "^2.4.2", + "@csstools/css-syntax-patches-for-csstree": "^1.1.3", + "@exodus/bytes": "^1.15.0", + "css-tree": "^3.2.1", + "data-urls": "^7.0.0", + "decimal.js": "^10.6.0", + "html-encoding-sniffer": "^6.0.0", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.3.5", + "parse5": "^8.0.1", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^6.0.1", + "undici": "^7.25.0", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^8.0.1", + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^16.0.1", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24.0.0" + }, + "peerDependencies": { + "canvas": "^3.0.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, + "node_modules/jsdom/node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, "node_modules/jsesc": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", @@ -2887,6 +4038,27 @@ "yallist": "^3.0.2" } }, + "node_modules/lz-string": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz", + "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==", + "dev": true, + "license": "MIT", + "peer": true, + "bin": { + "lz-string": "bin/bin.js" + } + }, + "node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", @@ -2896,6 +4068,13 @@ "node": ">= 0.4" } }, + "node_modules/mdn-data": { + "version": "2.27.1", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", + "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", + "dev": true, + "license": "CC0-1.0" + }, "node_modules/mime-db": { "version": "1.52.0", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", @@ -2917,6 +4096,16 @@ "node": ">= 0.6" } }, + "node_modules/min-indent": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz", + "integrity": "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, "node_modules/minimatch": { "version": "3.1.5", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", @@ -2970,6 +4159,20 @@ "dev": true, "license": "MIT" }, + "node_modules/obug": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", + "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, "node_modules/optionator": { "version": "0.9.4", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", @@ -3033,6 +4236,19 @@ "node": ">=6" } }, + "node_modules/parse5": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.0.tgz", + "integrity": "sha512-sq3qBFpee5jeocbFbO48VHlGr8sT7mbXS0vxlKN6sottBtJzrOG3998sr0llSZcQAGgfpdmEYAIZE0P9z0dE8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^9.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -3061,9 +4277,9 @@ "license": "ISC" }, "node_modules/picomatch": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", - "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", "dev": true, "license": "MIT", "engines": { @@ -3112,6 +4328,44 @@ "node": ">= 0.8.0" } }, + "node_modules/pretty-format": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz", + "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "ansi-regex": "^5.0.1", + "ansi-styles": "^5.0.0", + "react-is": "^17.0.1" + }, + "engines": { + "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + } + }, + "node_modules/pretty-format/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/pretty-format/node_modules/react-is": { + "version": "17.0.2", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", + "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", + "dev": true, + "license": "MIT", + "peer": true + }, "node_modules/proxy-from-env": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", @@ -3209,6 +4463,20 @@ "react-is": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, + "node_modules/redent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/redent/-/redent-3.0.0.tgz", + "integrity": "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "indent-string": "^4.0.0", + "strip-indent": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/redux": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz", @@ -3224,6 +4492,16 @@ "redux": "^5.0.0" } }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/reselect": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/reselect/-/reselect-5.1.1.tgz", @@ -3281,6 +4559,19 @@ "dev": true, "license": "MIT" }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, "node_modules/scheduler": { "version": "0.27.0", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz", @@ -3330,6 +4621,26 @@ "node": ">=0.10.0" } }, + "node_modules/std-env": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", + "dev": true, + "license": "MIT" + }, + "node_modules/strip-indent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz", + "integrity": "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "min-indent": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/strip-json-comments": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", @@ -3356,21 +4667,48 @@ "node": ">=8" } }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "dev": true, + "license": "MIT" + }, "node_modules/tiny-invariant": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz", "integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==", "license": "MIT" }, + "node_modules/tinybench": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.3.tgz", + "integrity": "sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/tinyglobby": { - "version": "0.2.15", - "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", - "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", "dev": true, "license": "MIT", "dependencies": { "fdir": "^6.5.0", - "picomatch": "^4.0.3" + "picomatch": "^4.0.4" }, "engines": { "node": ">=12.0.0" @@ -3379,6 +4717,52 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/tldts": { + "version": "7.4.19", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.19.tgz", + "integrity": "sha512-48dH6aSpQnpbzDUc4vIQZ1VjB8tkK+e8c1yx05/SZK+rkssgjEOlxDd/yU8/a4vGYQ9vRgJr9dwMq9TJ0b3X2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^7.4.19" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "7.4.20", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.20.tgz", + "integrity": "sha512-C630TWXZCZmLq0F2bW4QqwnaaxCQ/svpAqvJwnC4JvgEM5ohhBnGsEzTLSOXcN+xjz+kEaHS5uoWIw2klnqd0A==", + "dev": true, + "license": "MIT" + }, + "node_modules/tough-cookie": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz", + "integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^7.0.5" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz", + "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/ts-api-utils": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", @@ -3451,6 +4835,16 @@ "typescript": ">=4.8.4 <6.0.0" } }, + "node_modules/undici": { + "version": "7.30.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.1.tgz", + "integrity": "sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, "node_modules/undici-types": { "version": "7.16.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", @@ -3608,6 +5002,137 @@ } } }, + "node_modules/vitest": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.1.0.tgz", + "integrity": "sha512-MzmNFnrwa8v8lF1bLxw3UJ4EREwVOVb75VqJZmUDRjJ6EluK/x9th7qTbaeDk41WxE1GxWqmTXcdsfobfH5sOA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.1.0", + "chai": "^6.3.0", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.4.3", + "obug": "^3.0.0", + "picomatch": "^4.0.7", + "std-env": "^4.3.0", + "tinybench": "^6.2.2", + "tinyexec": "^1.3.1", + "tinyglobby": "^0.2.17", + "why-is-node-running": "3.2.1" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.1.0", + "@vitest/browser-preview": "5.1.0", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.1.0", + "@vitest/coverage-v8": "5.1.0", + "@vitest/ui": "5.1.0", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/w3c-xmlserializer": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/webidl-conversions": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", + "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-mimetype": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", + "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-url": { + "version": "16.0.1", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-16.0.1.tgz", + "integrity": "sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.11.0", + "tr46": "^6.0.0", + "webidl-conversions": "^8.0.1" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -3624,6 +5149,19 @@ "node": ">= 8" } }, + "node_modules/why-is-node-running": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", + "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", + "dev": true, + "license": "MIT", + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=20.11" + } + }, "node_modules/word-wrap": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", @@ -3634,6 +5172,23 @@ "node": ">=0.10.0" } }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + }, "node_modules/yallist": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", diff --git a/frontend/package.json b/frontend/package.json index 6d176cb..e58cede 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -7,7 +7,8 @@ "dev": "vite", "build": "tsc -b && vite build", "lint": "eslint .", - "preview": "vite preview" + "preview": "vite preview", + "test": "vitest run" }, "dependencies": { "axios": "^1.13.6", @@ -17,6 +18,9 @@ }, "devDependencies": { "@eslint/js": "^9.39.4", + "@testing-library/jest-dom": "^7.0.1", + "@testing-library/react": "^16.3.3", + "@testing-library/user-event": "^14.6.8", "@types/node": "^24.12.0", "@types/react": "^19.2.14", "@types/react-dom": "^19.2.3", @@ -26,8 +30,10 @@ "eslint-plugin-react-hooks": "^7.0.1", "eslint-plugin-react-refresh": "^0.5.2", "globals": "^17.4.0", + "jsdom": "^29.1.1", "typescript": "~5.9.3", "typescript-eslint": "^8.57.0", - "vite": "^8.0.1" + "vite": "^8.0.1", + "vitest": "^5.1.0" } } diff --git a/frontend/src/test/fakeApi.ts b/frontend/src/test/fakeApi.ts new file mode 100644 index 0000000..8b1750e --- /dev/null +++ b/frontend/src/test/fakeApi.ts @@ -0,0 +1,41 @@ +import type { AxiosAdapter, AxiosResponse, InternalAxiosRequestConfig } from "axios"; +import { AxiosError } from "axios"; +import client from "../api/client"; + +export interface FakeReply { + status: number; + data?: unknown; + headers?: Record; +} +export type Handler = (config: InternalAxiosRequestConfig) => FakeReply; + +// Replace the network with a function; non-2xx replies reject like real axios. +export function installFakeApi(handler: Handler): InternalAxiosRequestConfig[] { + const seen: InternalAxiosRequestConfig[] = []; + const adapter: AxiosAdapter = (config) => { + seen.push(config); + const reply = handler(config); + const response: AxiosResponse = { + status: reply.status, + statusText: String(reply.status), + data: reply.data ?? {}, + headers: reply.headers ?? {}, + config, + }; + if (reply.status >= 200 && reply.status < 300) return Promise.resolve(response); + return Promise.reject(new AxiosError("failed", String(reply.status), config, null, response)); + }; + client.defaults.adapter = adapter; + return seen; +} + +export const CONFIG = { + caps: { max_num_requests: 500, max_concurrency: 20, max_request_timeout_s: 10, run_wall_clock_limit_s: 60 }, + targets: [ + { label: "httpbin.org", url: "https://httpbin.org/get" }, + { label: "QueryScope demo target", url: "https://demo.example.com/work" }, + ], + allow_custom_target: false, + llm_benchmark_enabled: false, + auth_enabled: true, +}; diff --git a/frontend/src/test/setup.ts b/frontend/src/test/setup.ts new file mode 100644 index 0000000..a15f705 --- /dev/null +++ b/frontend/src/test/setup.ts @@ -0,0 +1,8 @@ +import "@testing-library/jest-dom/vitest"; +import { cleanup } from "@testing-library/react"; +import { afterEach } from "vitest"; + +afterEach(() => { + cleanup(); + window.sessionStorage.clear(); +}); diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index 8b0f57b..a3b6dbf 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -1,7 +1,11 @@ -import { defineConfig } from 'vite' -import react from '@vitejs/plugin-react' +import { defineConfig } from "vitest/config"; +import react from "@vitejs/plugin-react"; -// https://vite.dev/config/ export default defineConfig({ plugins: [react()], -}) + test: { + environment: "jsdom", + setupFiles: ["./src/test/setup.ts"], + globals: false, + }, +}); From 49a7d879c1c012981c780df5d60a8154c2270d2d Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 14:13:53 -0800 Subject: [PATCH 19/45] feat: add session token storage, auth client, and friendly API errors --- frontend/src/api/auth.test.ts | 65 ++++++++++++++++++++++ frontend/src/api/auth.ts | 86 ++++++++++++++++++++++++++++++ frontend/src/api/client.ts | 24 +++++++++ frontend/src/api/errors.test.ts | 40 ++++++++++++++ frontend/src/api/errors.ts | 58 ++++++++++++++++++++ frontend/src/api/session.ts | 54 +++++++++++++++++++ frontend/src/config.ts | 9 ++++ frontend/src/lib/magicLink.test.ts | 22 ++++++++ frontend/src/lib/magicLink.ts | 15 ++++++ frontend/src/lib/numbers.test.ts | 14 +++++ frontend/src/lib/numbers.ts | 6 +++ frontend/src/types/config.ts | 17 ++++++ 12 files changed, 410 insertions(+) create mode 100644 frontend/src/api/auth.test.ts create mode 100644 frontend/src/api/auth.ts create mode 100644 frontend/src/api/errors.test.ts create mode 100644 frontend/src/api/errors.ts create mode 100644 frontend/src/api/session.ts create mode 100644 frontend/src/config.ts create mode 100644 frontend/src/lib/magicLink.test.ts create mode 100644 frontend/src/lib/magicLink.ts create mode 100644 frontend/src/lib/numbers.test.ts create mode 100644 frontend/src/lib/numbers.ts create mode 100644 frontend/src/types/config.ts diff --git a/frontend/src/api/auth.test.ts b/frontend/src/api/auth.test.ts new file mode 100644 index 0000000..bb0a5df --- /dev/null +++ b/frontend/src/api/auth.test.ts @@ -0,0 +1,65 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { bootstrap, loginWithCode } from "./auth"; +import { getToken } from "./session"; +import { CONFIG, installFakeApi } from "../test/fakeApi"; + +beforeEach(() => { + window.history.replaceState(null, "", "/"); +}); + +describe("loginWithCode", () => { + it("stores the token in sessionStorage only", async () => { + installFakeApi(() => ({ status: 200, data: { token: "tok-1", label: "demo" } })); + expect(await loginWithCode("some-code")).toBeNull(); + expect(getToken()).toBe("tok-1"); + expect(window.localStorage.length).toBe(0); + }); + + it("gives one generic message for a bad code", async () => { + installFakeApi(() => ({ status: 401, data: { detail: "Invalid access code" } })); + const msg = await loginWithCode("nope"); + expect(msg).toMatch(/not recognized/i); + expect(getToken()).toBeNull(); + }); + + it("explains throttling with a wait time", async () => { + installFakeApi(() => ({ status: 429, data: {}, headers: { "retry-after": "600" } })); + expect(await loginWithCode("x")).toBe("Too many attempts. Try again in 10 minutes."); + }); +}); + +describe("bootstrap", () => { + it("exchanges a #code= link, strips the fragment, then loads config", async () => { + window.history.replaceState(null, "", "/#code=lbl.abcDEF1234"); + const seen = installFakeApi((c) => + c.url === "/auth/login" + ? { status: 200, data: { token: "tok-2", label: "lbl" } } + : { status: 200, data: CONFIG }, + ); + const result = await bootstrap(); + expect(result.kind).toBe("authed"); + expect(window.location.hash).toBe(""); + const cfgReq = seen[seen.length - 1]; + expect(cfgReq.headers.Authorization).toBe("Bearer tok-2"); + }); + + it("shows the landing page with a message when the link fails", async () => { + window.history.replaceState(null, "", "/#code=revoked.zzzzzzzzzz"); + installFakeApi((c) => (c.url === "/auth/login" ? { status: 401 } : { status: 401 })); + const result = await bootstrap(); + expect(result.kind).toBe("anon"); + if (result.kind === "anon") expect(result.message).toMatch(/link is not valid/i); + expect(window.location.hash).toBe(""); + expect(getToken()).toBeNull(); + }); + + it("goes straight to the app when the server has auth disabled", async () => { + installFakeApi(() => ({ status: 200, data: { ...CONFIG, auth_enabled: false } })); + expect((await bootstrap()).kind).toBe("authed"); + }); + + it("returns to landing without a message on a first visit", async () => { + installFakeApi(() => ({ status: 401 })); + expect(await bootstrap()).toEqual({ kind: "anon", message: null }); + }); +}); diff --git a/frontend/src/api/auth.ts b/frontend/src/api/auth.ts new file mode 100644 index 0000000..341a82e --- /dev/null +++ b/frontend/src/api/auth.ts @@ -0,0 +1,86 @@ +import axios from "axios"; +import client from "./client"; +import { codeFromHash, stripFragment } from "../lib/magicLink"; +import { clearSession, getToken, saveSession } from "./session"; +import { formatWait } from "./errors"; +import type { AppConfig } from "../types/config"; + +interface LoginResponse { + token: string; + label: string; +} + +export const BAD_CODE_MESSAGE = + "That access code was not recognized. Check it and try again, or request access below."; + +/** Exchange a code for a token and store it. Returns null on success, else a message. */ +export async function loginWithCode(code: string): Promise { + try { + const res = await client.post("/auth/login", { code }); + saveSession(res.data.token, res.data.label ?? null); + return null; + } catch (err: unknown) { + if (axios.isAxiosError(err) && err.response) { + const status = err.response.status; + if (status === 429) { + const raw = Number(err.response.headers["retry-after"]); + const wait = Number.isFinite(raw) && raw > 0 ? ` Try again in ${formatWait(raw)}.` : ""; + return "Too many attempts." + wait; + } + if (status === 401) return BAD_CODE_MESSAGE; + if (status === 404) return null; // Auth disabled on the server: nothing to log into. + } + return "Could not reach the QueryScope API. Please try again."; + } +} + +export type BootResult = + | { kind: "authed"; config: AppConfig } + | { kind: "anon"; message: string | null }; + +/** + * Decide what to show on load: + * 1. a #code= link is exchanged (and the fragment removed first) + * 2. otherwise GET /config tells us whether the token (or an open server) works + */ +export async function bootstrap(): Promise { + const linkCode = codeFromHash(window.location.hash); + if (linkCode !== null) { + // Strip before the network call so the code never lingers in the URL. + stripFragment(); + clearSession(); + const failure = await loginWithCode(linkCode); + if (failure !== null) { + return { kind: "anon", message: failure === BAD_CODE_MESSAGE ? "This access link is not valid or has been revoked. Enter your code below or request access." : failure }; + } + } + return fetchConfig(); +} + +export async function fetchConfig(): Promise { + try { + const res = await client.get("/config"); + return { kind: "authed", config: res.data }; + } catch (err: unknown) { + if (axios.isAxiosError(err) && err.response?.status === 401) { + const hadToken = getToken() !== null; + clearSession(); + return { + kind: "anon", + message: hadToken ? "Your session has expired. Enter your access code to continue." : null, + }; + } + return { kind: "anon", message: "Could not reach the QueryScope API. Please try again shortly." }; + } +} + +// Memoised so React StrictMode's double effect run does not exchange a magic +// link twice (the second pass would find the fragment already stripped). +let bootPromise: Promise | null = null; +export function getBoot(): Promise { + if (bootPromise === null) bootPromise = bootstrap(); + return bootPromise; +} +export function resetBootForTests(): void { + bootPromise = null; +} diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index bca02e3..533be3f 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -1,8 +1,32 @@ import axios from "axios"; +import { clearSession, getToken, notifyUnauthorized } from "./session"; const client = axios.create({ baseURL: import.meta.env.VITE_API_URL || "http://localhost:8000", headers: { "Content-Type": "application/json" }, }); +client.interceptors.request.use((config) => { + const token = getToken(); + if (token) config.headers.Authorization = `Bearer ${token}`; + return config; +}); + +client.interceptors.response.use( + (response) => response, + (error: unknown) => { + // A 401 from login just means a bad code; the login flow reports it. + // Any other 401 means the session is gone: drop the token and go back to + // the landing page. + if (axios.isAxiosError(error) && error.response?.status === 401) { + const url = error.config?.url ?? ""; + if (!url.startsWith("/auth/login")) { + clearSession(); + notifyUnauthorized(); + } + } + return Promise.reject(error); + }, +); + export default client; diff --git a/frontend/src/api/errors.test.ts b/frontend/src/api/errors.test.ts new file mode 100644 index 0000000..c41ca0f --- /dev/null +++ b/frontend/src/api/errors.test.ts @@ -0,0 +1,40 @@ +import { AxiosError } from "axios"; +import { describe, expect, it } from "vitest"; +import { describeError, formatWait } from "./errors"; + +function httpError(status: number, data: unknown, headers: Record = {}) { + const response = { status, data, headers, statusText: "", config: {} } as never; + return new AxiosError("x", String(status), undefined, null, response); +} + +describe("formatWait", () => { + it("rounds up to whole minutes", () => { + expect(formatWait(61)).toBe("2 minutes"); + expect(formatWait(600)).toBe("10 minutes"); + }); + it("handles very short and very long waits", () => { + expect(formatWait(20)).toBe("about a minute"); + expect(formatWait(7200)).toBe("about 2 hours"); + }); +}); + +describe("describeError", () => { + it("shows the reason for a rejected target", () => { + expect(describeError(httpError(422, { detail: "Target host is not on the allowlist" }))).toBe( + "Target host is not on the allowlist", + ); + }); + it("falls back to a form message for validation arrays", () => { + expect(describeError(httpError(422, { detail: [{ msg: "bad" }] }))).toMatch(/check the form/i); + }); + it("adds a retry time to 429 messages", () => { + const msg = describeError(httpError(429, { detail: "Daily request budget used." }, { "retry-after": "1800" })); + expect(msg).toBe("Daily request budget used. Try again in 30 minutes."); + }); + it("still reads well without Retry-After", () => { + expect(describeError(httpError(429, { detail: "Too many runs." }))).toBe("Too many runs."); + }); + it("hides server internals on 500", () => { + expect(describeError(httpError(500, { detail: "Traceback ..." }))).not.toMatch(/Traceback/); + }); +}); diff --git a/frontend/src/api/errors.ts b/frontend/src/api/errors.ts new file mode 100644 index 0000000..eab2788 --- /dev/null +++ b/frontend/src/api/errors.ts @@ -0,0 +1,58 @@ +import axios from "axios"; + +export function formatWait(seconds: number): string { + if (seconds <= 60) return "about a minute"; + const minutes = Math.ceil(seconds / 60); + if (minutes < 60) return `${minutes} minutes`; + const hours = Math.ceil(minutes / 60); + return hours === 1 ? "about an hour" : `about ${hours} hours`; +} + +function readRetryAfter(headers: unknown): number | null { + if (!headers || typeof headers !== "object") return null; + const raw = (headers as Record)["retry-after"]; + if (raw === undefined || raw === null) return null; + const n = Number(raw); + return Number.isFinite(n) && n > 0 ? n : null; +} + +/** + * Turn any request error into text a person can act on. + * 401 -> handled by the interceptor, but give a fallback message + * 422 -> the server's reason (target rejected) or a generic form message + * 429 -> the server's reason plus "try again in N minutes" from Retry-After + * Never includes request bodies, codes or tokens. + */ +export function describeError(err: unknown): string { + if (!axios.isAxiosError(err)) { + return "Something went wrong. Please try again."; + } + if (!err.response) { + return "Cannot reach the QueryScope API. Check your connection and try again."; + } + const status = err.response.status; + const data = err.response.data as { detail?: unknown } | undefined; + const detail = typeof data?.detail === "string" ? data.detail : null; + + if (status === 401) { + return "Your session has expired. Enter your access code to continue."; + } + if (status === 422) { + return detail ?? "Those values were not accepted. Check the form and try again."; + } + if (status === 429) { + const wait = readRetryAfter(err.response.headers); + const base = detail ?? "You have reached a usage limit."; + return wait === null ? base : `${base} Try again in ${formatWait(wait)}.`; + } + if (status === 404) { + return detail ?? "That item was not found."; + } + if (status === 403) { + return detail ?? "That action is not allowed."; + } + if (status >= 500) { + return "The server had a problem. Please try again in a moment."; + } + return detail ?? "Request failed. Please try again."; +} diff --git a/frontend/src/api/session.ts b/frontend/src/api/session.ts new file mode 100644 index 0000000..b8d1000 --- /dev/null +++ b/frontend/src/api/session.ts @@ -0,0 +1,54 @@ +// Token storage. sessionStorage, never localStorage: the token disappears when +// the tab closes and is not shared across tabs. Nothing here logs its values. + +const TOKEN_KEY = "qs_token"; +const LABEL_KEY = "qs_label"; + +export function getToken(): string | null { + try { + return window.sessionStorage.getItem(TOKEN_KEY); + } catch { + return null; + } +} + +export function getLabel(): string | null { + try { + return window.sessionStorage.getItem(LABEL_KEY); + } catch { + return null; + } +} + +export function saveSession(token: string, label: string | null): void { + try { + window.sessionStorage.setItem(TOKEN_KEY, token); + if (label) window.sessionStorage.setItem(LABEL_KEY, label); + } catch { + // Storage blocked: the session lasts until reload, which is acceptable. + } +} + +export function clearSession(): void { + try { + window.sessionStorage.removeItem(TOKEN_KEY); + window.sessionStorage.removeItem(LABEL_KEY); + } catch { + // Nothing to clear. + } +} + +// ── Unauthorized notification ────────────────────────────────────────────── +// The axios interceptor cannot touch React state, so it calls a listener that +// the App registers. + +type Listener = () => void; +let unauthorizedListener: Listener | null = null; + +export function setUnauthorizedListener(fn: Listener | null): void { + unauthorizedListener = fn; +} + +export function notifyUnauthorized(): void { + if (unauthorizedListener) unauthorizedListener(); +} diff --git a/frontend/src/config.ts b/frontend/src/config.ts new file mode 100644 index 0000000..4f5de36 --- /dev/null +++ b/frontend/src/config.ts @@ -0,0 +1,9 @@ +// Site-level settings that are not secrets. + +// Where "request access" emails go. Placeholder: replace before publishing. +export const CONTACT_EMAIL = "access@example.com"; + +export const GITHUB_URL = "https://github.com/kavishkartha05/QueryScope"; + +export const REQUEST_ACCESS_HREF = + "mailto:" + CONTACT_EMAIL + "?subject=" + encodeURIComponent("QueryScope demo access request"); diff --git a/frontend/src/lib/magicLink.test.ts b/frontend/src/lib/magicLink.test.ts new file mode 100644 index 0000000..ed91aad --- /dev/null +++ b/frontend/src/lib/magicLink.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "vitest"; +import { codeFromHash, stripFragment } from "./magicLink"; + +describe("codeFromHash", () => { + it("reads the code", () => { + expect(codeFromHash("#code=stripe-rebecca.aB3dE5gH7k")).toBe("stripe-rebecca.aB3dE5gH7k"); + }); + it("returns null when absent or empty", () => { + expect(codeFromHash("")).toBeNull(); + expect(codeFromHash("#other=1")).toBeNull(); + expect(codeFromHash("#code=")).toBeNull(); + }); +}); + +describe("stripFragment", () => { + it("removes the fragment and keeps the path", () => { + window.history.replaceState(null, "", "/app?x=1#code=abc"); + stripFragment(); + expect(window.location.hash).toBe(""); + expect(window.location.pathname + window.location.search).toBe("/app?x=1"); + }); +}); diff --git a/frontend/src/lib/magicLink.ts b/frontend/src/lib/magicLink.ts new file mode 100644 index 0000000..491c780 --- /dev/null +++ b/frontend/src/lib/magicLink.ts @@ -0,0 +1,15 @@ +/** Read `code` from a URL fragment like "#code=abc.def". Null if absent. */ +export function codeFromHash(hash: string): string | null { + const raw = hash.startsWith("#") ? hash.slice(1) : hash; + if (raw === "") return null; + const code = new URLSearchParams(raw).get("code"); + return code && code.trim() !== "" ? code.trim() : null; +} + +/** + * Remove the fragment (and only the fragment) so the code is not left in the + * address bar, history entry or a later copy-paste of the URL. + */ +export function stripFragment(): void { + window.history.replaceState(null, "", window.location.pathname + window.location.search); +} diff --git a/frontend/src/lib/numbers.test.ts b/frontend/src/lib/numbers.test.ts new file mode 100644 index 0000000..4d2e193 --- /dev/null +++ b/frontend/src/lib/numbers.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from "vitest"; +import { clampInt } from "./numbers"; + +describe("clampInt", () => { + it("keeps values inside the range", () => { + expect(clampInt("9999", 1, 500)).toBe(500); + expect(clampInt("0", 1, 500)).toBe(1); + expect(clampInt("42", 1, 500)).toBe(42); + }); + it("falls back to the minimum for junk", () => { + expect(clampInt("", 1, 500)).toBe(1); + expect(clampInt("abc", 1, 20)).toBe(1); + }); +}); diff --git a/frontend/src/lib/numbers.ts b/frontend/src/lib/numbers.ts new file mode 100644 index 0000000..38a7b3b --- /dev/null +++ b/frontend/src/lib/numbers.ts @@ -0,0 +1,6 @@ +// Keep a typed number inside [min, max]; blanks and junk fall back to min. +export function clampInt(raw: string | number, min: number, max: number): number { + const n = typeof raw === "number" ? raw : parseInt(raw, 10); + if (!Number.isFinite(n)) return min; + return Math.min(max, Math.max(min, Math.trunc(n))); +} diff --git a/frontend/src/types/config.ts b/frontend/src/types/config.ts new file mode 100644 index 0000000..36b02f5 --- /dev/null +++ b/frontend/src/types/config.ts @@ -0,0 +1,17 @@ +export interface TargetOption { + label: string; + url: string; +} + +export interface AppConfig { + caps: { + max_num_requests: number; + max_concurrency: number; + max_request_timeout_s: number; + run_wall_clock_limit_s: number; + }; + targets: TargetOption[]; + allow_custom_target: boolean; + llm_benchmark_enabled: boolean; + auth_enabled: boolean; +} From 279ac922ba1e84996bd7e87123f367b129d3ece7 Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 14:13:53 -0800 Subject: [PATCH 20/45] feat: add landing page, access code login, magic link, and 401 handling --- frontend/index.html | 2 +- frontend/src/App.test.tsx | 80 +++++++++ frontend/src/App.tsx | 255 +++++++++++++++++++--------- frontend/src/components/Landing.tsx | 159 +++++++++++++++++ frontend/src/index.css | 41 ++++- 5 files changed, 458 insertions(+), 79 deletions(-) create mode 100644 frontend/src/App.test.tsx create mode 100644 frontend/src/components/Landing.tsx diff --git a/frontend/index.html b/frontend/index.html index 0fca6f0..5a8e054 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -4,7 +4,7 @@ - frontend + QueryScope
diff --git a/frontend/src/App.test.tsx b/frontend/src/App.test.tsx new file mode 100644 index 0000000..b0749c6 --- /dev/null +++ b/frontend/src/App.test.tsx @@ -0,0 +1,80 @@ +import { render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import App from "./App"; +import { resetBootForTests } from "./api/auth"; +import { getToken } from "./api/session"; +import { CONFIG, installFakeApi } from "./test/fakeApi"; + +// Recharts needs layout APIs jsdom lacks; the chart is not under test here. +vi.mock("./components/LatencyChart", () => ({ default: () =>
chart
})); +vi.mock("./components/DiagnosePanel", () => ({ default: () =>
diagnose
})); + +const RUNS = { total: 0, offset: 0, limit: 20, items: [] }; + +beforeEach(() => { + resetBootForTests(); + window.history.replaceState(null, "", "/"); +}); + +describe("App", () => { + it("shows the landing page with no token", async () => { + installFakeApi(() => ({ status: 401 })); + render(); + expect(await screen.findByRole("heading", { name: /enter your access code/i })).toBeInTheDocument(); + expect(screen.getByRole("link", { name: /request access/i }).getAttribute("href")).toMatch(/^mailto:/); + expect(screen.getByRole("link", { name: /github/i }).getAttribute("href")).toBe( + "https://github.com/kavishkartha05/QueryScope", + ); + }); + + it("logs in with a code and reaches the dashboard", async () => { + let authed = false; + installFakeApi((c) => { + if (c.url === "/auth/login") { + authed = true; + return { status: 200, data: { token: "tok", label: "demo" } }; + } + if (!authed) return { status: 401 }; + return c.url === "/config" ? { status: 200, data: CONFIG } : { status: 200, data: RUNS }; + }); + render(); + await userEvent.type(await screen.findByLabelText(/^access code$/i), "demo.abc1234567"); + await userEvent.click(screen.getByRole("button", { name: /enter/i })); + expect(await screen.findByRole("button", { name: /run benchmark/i })).toBeInTheDocument(); + expect(getToken()).toBe("tok"); + }); + + it("shows a generic error for a bad code and stays on the landing page", async () => { + installFakeApi((c) => (c.url === "/auth/login" ? { status: 401, data: { detail: "Invalid access code" } } : { status: 401 })); + render(); + await userEvent.type(await screen.findByLabelText(/^access code$/i), "wrong"); + await userEvent.click(screen.getByRole("button", { name: /enter/i })); + expect(await screen.findByRole("alert")).toHaveTextContent(/not recognized/i); + }); + + it("returns to the landing page with a message when a request gets a 401", async () => { + window.sessionStorage.setItem("qs_token", "stale"); + let calls = 0; + installFakeApi((c) => { + if (c.url === "/config") return { status: 200, data: CONFIG }; + calls += 1; + return { status: 401 }; + }); + render(); + expect(await screen.findByRole("alert")).toHaveTextContent(/expired or was revoked/i); + expect(getToken()).toBeNull(); + expect(calls).toBeGreaterThan(0); + }); + + it("exchanges a magic link on load and removes the fragment", async () => { + window.history.replaceState(null, "", "/#code=lbl.abcdefghij"); + installFakeApi((c) => { + if (c.url === "/auth/login") return { status: 200, data: { token: "tok", label: "lbl" } }; + return c.url === "/config" ? { status: 200, data: CONFIG } : { status: 200, data: RUNS }; + }); + render(); + await waitFor(() => expect(screen.getByRole("button", { name: /run benchmark/i })).toBeInTheDocument()); + expect(window.location.hash).toBe(""); + }); +}); diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 96b4c11..18dd24a 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,9 +1,14 @@ import { useEffect, useRef, useState } from "react"; import client from "./api/client"; +import { fetchConfig, getBoot, loginWithCode } from "./api/auth"; +import { describeError } from "./api/errors"; +import { clearSession, getLabel, setUnauthorizedListener } from "./api/session"; import BenchmarkForm from "./components/BenchmarkForm"; import DiagnosePanel from "./components/DiagnosePanel"; +import Landing from "./components/Landing"; import LatencyChart from "./components/LatencyChart"; import RunsTable from "./components/RunsTable"; +import type { AppConfig } from "./types/config"; import type { PaginatedRuns, Run } from "./types/run"; // ── Mouse-follow glow ────────────────────────────────────────────────────── @@ -42,9 +47,21 @@ function MouseGlow() { // ── Navbar ───────────────────────────────────────────────────────────────── -function Navbar({ connected }: { connected: boolean | null }) { +function Navbar({ + connected, + label, + onSignOut, +}: { + connected: boolean | null; + label: string | null; + onSignOut: (() => void) | null; +}) { + const dot = connected === null ? "#6b7280" : connected ? "#10b981" : "#ef4444"; + const text = connected === null ? "Connecting…" : connected ? "API connected" : "API disconnected"; return ( ); @@ -113,39 +135,43 @@ function Navbar({ connected }: { connected: boolean | null }) { // ── Card ─────────────────────────────────────────────────────────────────── -function Card({ - children, - style, -}: { - children: React.ReactNode; - style?: React.CSSProperties; -}) { +function Card({ children, label }: { children: React.ReactNode; label: string }) { return ( -
{children} -
+ ); } -// ── App ──────────────────────────────────────────────────────────────────── +// ── Dashboard (signed in) ────────────────────────────────────────────────── -export default function App() { +const POLL_MS = 3000; + +function Dashboard({ + config, + label, + onSignOut, +}: { + config: AppConfig; + label: string | null; + onSignOut: () => void; +}) { const [runs, setRuns] = useState([]); const [total, setTotal] = useState(0); const [fetchError, setFetchError] = useState(null); + const [actionError, setActionError] = useState(null); const [connected, setConnected] = useState(null); const [visible, setVisible] = useState(false); - const [formResetKey, setFormResetKey] = useState(0); const intervalRef = useRef | null>(null); async function fetchRuns() { @@ -156,51 +182,58 @@ export default function App() { setFetchError(null); setConnected(true); } catch (err: unknown) { - setFetchError(err instanceof Error ? err.message : "Failed to fetch runs"); + // A 401 is handled globally (back to the landing page); show the rest. + setFetchError(describeError(err)); setConnected(false); } } useEffect(() => { + // Fetch on mount; the state updates happen after the request resolves. + // eslint-disable-next-line react-hooks/set-state-in-effect void fetchRuns(); - intervalRef.current = setInterval(() => void fetchRuns(), 3000); + intervalRef.current = setInterval(() => { + // No point polling a tab nobody is looking at. + if (!document.hidden) void fetchRuns(); + }, POLL_MS); requestAnimationFrame(() => setVisible(true)); return () => { if (intervalRef.current) clearInterval(intervalRef.current); }; }, []); - function handleRunCreated(_runId: string) { - void fetchRuns(); - } - - async function handleReset() { - await client.delete("/benchmark/runs"); - // Clear state immediately so the table and chart empty before the next - // poll cycle fires — avoids a brief flash of stale data. - setRuns([]); - setTotal(0); - // Incrementing the key signals BenchmarkForm to clear its SLA fields. - setFormResetKey((k) => k + 1); + async function handleSetBaseline(runId: string) { + setActionError(null); + try { + await client.patch(`/benchmark/runs/${runId}/baseline`); + // Refresh now so the new baseline and every delta render without + // waiting for the next poll. + await fetchRuns(); + } catch (err: unknown) { + setActionError(describeError(err)); + } } - async function handleSetBaseline(runId: string) { - await client.patch(`/benchmark/runs/${runId}/baseline`); - // Refresh immediately so the new baseline and all deltas render without - // waiting for the next 3-second poll cycle. - void fetchRuns(); + async function handleClearBaseline() { + setActionError(null); + try { + await client.delete("/benchmark/runs/baseline"); + await fetchRuns(); + } catch (err: unknown) { + setActionError(describeError(err)); + } } return (
- +
- - + + void fetchRuns()} /> - - + + - + - +
); } + +// ── App: decides between loading, landing and dashboard ──────────────────── + +type View = + | { kind: "loading" } + | { kind: "landing"; notice: string | null } + | { kind: "dashboard"; config: AppConfig }; + +export default function App() { + const [view, setView] = useState({ kind: "loading" }); + + useEffect(() => { + let cancelled = false; + void getBoot().then((result) => { + if (cancelled) return; + if (result.kind === "authed") setView({ kind: "dashboard", config: result.config }); + else setView({ kind: "landing", notice: result.message }); + }); + return () => { + cancelled = true; + }; + }, []); + + // Any 401 after load (expired or revoked) returns to the landing page. + useEffect(() => { + setUnauthorizedListener(() => { + setView({ + kind: "landing", + notice: "Your session has expired or was revoked. Enter your access code to continue.", + }); + }); + return () => setUnauthorizedListener(null); + }, []); + + async function handleLogin(code: string): Promise { + const failure = await loginWithCode(code); + if (failure !== null) return failure; + const result = await fetchConfig(); + if (result.kind === "authed") { + setView({ kind: "dashboard", config: result.config }); + return null; + } + return result.message ?? "Could not start your session. Please try again."; + } + + function handleSignOut() { + clearSession(); + setView({ kind: "landing", notice: null }); + } + + if (view.kind === "loading") { + return ( +
+ Loading… +
+ ); + } + if (view.kind === "landing") { + return ; + } + return ; +} diff --git a/frontend/src/components/Landing.tsx b/frontend/src/components/Landing.tsx new file mode 100644 index 0000000..5388259 --- /dev/null +++ b/frontend/src/components/Landing.tsx @@ -0,0 +1,159 @@ +import { useState } from "react"; +import { GITHUB_URL, REQUEST_ACCESS_HREF } from "../config"; + +interface LandingProps { + // Why the visitor is here (expired session, bad link, ...). Null on first visit. + notice: string | null; + // Resolves to an error message, or null when login worked. + onLogin: (code: string) => Promise; +} + +const MONO = "ui-monospace, SFMono-Regular, Fira Code, Consolas, monospace"; + +const linkStyle: React.CSSProperties = { color: "#a78bfa", textDecoration: "underline" }; + +export default function Landing({ notice, onLogin }: LandingProps) { + const [code, setCode] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + async function submit(e: React.FormEvent) { + e.preventDefault(); + if (code.trim() === "" || busy) return; + setBusy(true); + setError(null); + const failure = await onLogin(code.trim()); + // Success unmounts this component; only reset state when it stays on screen. + if (failure !== null) { + setError(failure); + setBusy(false); + } + } + + const message = error ?? notice; + + return ( +
+
+
+

+ QueryScope +

+

+ Load-test an API, then ask what changed in plain English +

+

+ QueryScope runs benchmarks against REST endpoints, stores every request latency in + PostgreSQL, and flags regressions against a baseline run. A retrieval pipeline over + Azure AI Search lets you ask questions like "which run got slower and why?". This + hosted demo is invite-only and limited to a small set of safe targets. +

+
+ + {/* Replace with a screenshot or GIF of the dashboard. */} +
+ Screenshot or GIF placeholder +
+ +
+

+ Enter your access code +

+ + {message && ( +
+ {message} +
+ )} + +
void submit(e)} style={{ display: "flex", flexDirection: "column", gap: 10 }}> + + setCode(e.target.value)} + style={{ + padding: "9px 12px", + background: "#13131f", + border: "1px solid #2e3150", + borderRadius: 8, + color: "#e6f1ff", + fontFamily: MONO, + fontSize: 14, + }} + /> + +
+
+ +

+ No code yet?{" "} + + Request access by email + + . The source is on{" "} + + GitHub + + . +

+
+
+ ); +} diff --git a/frontend/src/index.css b/frontend/src/index.css index 88fb7f8..2a9f417 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -1,7 +1,7 @@ /* ── QueryScope global styles ─────────────────────────────────────────────── */ :root { - /* Color palette — dark theme as default */ + /* Color palette, dark theme as default */ --bg: #0d0e14; --surface: #13141c; --surface-2: #1a1b26; @@ -104,3 +104,42 @@ body { /* Selection */ ::selection { background: var(--accent-glow); color: var(--text-bright); } + +/* ── Shared UI helpers (focus, responsive layout) ─────────────────────────── */ + +:focus-visible { + outline: 2px solid #a78bfa; + outline-offset: 2px; +} + +.qs-visually-hidden { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; +} + +.qs-nav { padding: 0 32px; } +.qs-main { padding: 36px 24px 96px; } +.qs-card { padding: 28px 32px; } +.qs-grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; } +.qs-grid-url { display: grid; grid-template-columns: 1fr 130px; gap: 12px; } +.qs-grid-3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 12px; } + +button, input, select { min-height: 40px; } + +@media (max-width: 640px) { + .qs-nav { padding: 0 14px; } + .qs-main { padding: 20px 12px 64px; } + .qs-card { padding: 18px 14px; } + .qs-grid-2, .qs-grid-url, .qs-grid-3 { grid-template-columns: 1fr; } + .qs-hide-mobile { display: none; } + /* 16px stops iOS Safari from zooming into inputs on focus. */ + input, select, textarea { font-size: 16px !important; } +} + +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; } +} From 9b1a94a10dda14650897668d2517feff8577553a Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 14:13:53 -0800 Subject: [PATCH 21/45] feat: constrain the benchmark form to server caps and the target allowlist --- .../src/components/BenchmarkForm.test.tsx | 59 +++++ frontend/src/components/BenchmarkForm.tsx | 220 +++++++++++------- frontend/src/types/run.ts | 7 +- 3 files changed, 198 insertions(+), 88 deletions(-) create mode 100644 frontend/src/components/BenchmarkForm.test.tsx diff --git a/frontend/src/components/BenchmarkForm.test.tsx b/frontend/src/components/BenchmarkForm.test.tsx new file mode 100644 index 0000000..4af6e9c --- /dev/null +++ b/frontend/src/components/BenchmarkForm.test.tsx @@ -0,0 +1,59 @@ +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, expect, it } from "vitest"; +import BenchmarkForm from "./BenchmarkForm"; +import { CONFIG, installFakeApi } from "../test/fakeApi"; + +describe("BenchmarkForm", () => { + it("offers the allowed targets and states the limits", () => { + render( {}} />); + expect(screen.getByRole("option", { name: "httpbin.org" })).toBeInTheDocument(); + expect(screen.getByRole("option", { name: "QueryScope demo target" })).toBeInTheDocument(); + expect(screen.queryByRole("option", { name: /custom url/i })).toBeNull(); + expect(screen.getByLabelText(/requests \(max 500\)/i)).toHaveAttribute("max", "500"); + expect(screen.getByLabelText(/concurrency \(max 20\)/i)).toHaveAttribute("max", "20"); + expect(screen.getByLabelText(/timeout s \(max 10\)/i)).toHaveAttribute("max", "10"); + }); + + it("clamps typed values to the caps", async () => { + render( {}} />); + const reqs = screen.getByLabelText(/requests \(max 500\)/i); + await userEvent.clear(reqs); + await userEvent.type(reqs, "9999"); + expect(reqs).toHaveValue(500); + }); + + it("allows a custom URL only when the server says so", () => { + render( {}} />); + expect(screen.getByRole("option", { name: /custom url/i })).toBeInTheDocument(); + }); + + it("sends the chosen target and caps-bound values", async () => { + const seen = installFakeApi(() => ({ status: 202, data: { run_id: "12345678-aaaa" } })); + render( {}} />); + await userEvent.selectOptions(screen.getByLabelText(/^target/i), "https://demo.example.com/work"); + await userEvent.click(screen.getByRole("button", { name: /run benchmark/i })); + const body = JSON.parse(String(seen[0].data)); + expect(body.target_url).toBe("https://demo.example.com/work"); + expect(body.timeout_s).toBeLessThanOrEqual(10); + expect(await screen.findByRole("status")).toHaveTextContent(/12345678/); + }); + + it("shows a friendly retry message on 429", async () => { + installFakeApi(() => ({ + status: 429, + data: { detail: "Daily request budget used." }, + headers: { "retry-after": "1800" }, + })); + render( {}} />); + await userEvent.click(screen.getByRole("button", { name: /run benchmark/i })); + expect(await screen.findByRole("alert")).toHaveTextContent("Try again in 30 minutes."); + }); + + it("shows the server's reason on 422", async () => { + installFakeApi(() => ({ status: 422, data: { detail: "That target is not allowed." } })); + render( {}} />); + await userEvent.click(screen.getByRole("button", { name: /run benchmark/i })); + expect(await screen.findByRole("alert")).toHaveTextContent("That target is not allowed."); + }); +}); diff --git a/frontend/src/components/BenchmarkForm.tsx b/frontend/src/components/BenchmarkForm.tsx index e24ba53..1429db0 100644 --- a/frontend/src/components/BenchmarkForm.tsx +++ b/frontend/src/components/BenchmarkForm.tsx @@ -1,14 +1,18 @@ -import { useEffect, useState } from "react"; +import { useState } from "react"; import client from "../api/client"; +import { describeError } from "../api/errors"; +import { clampInt } from "../lib/numbers"; +import type { AppConfig } from "../types/config"; import type { BenchmarkRequest, RunCreatedResponse } from "../types/run"; interface BenchmarkFormProps { + config: AppConfig; onRunCreated: (runId: string) => void; - // Incrementing this value triggers a reset of the SLA fields so they don't - // carry over into the next benchmark after a session reset. - resetKey?: number; } +const CUSTOM = "__custom__"; + + const HTTP_METHODS = ["GET", "POST", "PUT", "DELETE"] as const; type HttpMethod = (typeof HTTP_METHODS)[number]; @@ -26,6 +30,13 @@ const baseInput: React.CSSProperties = { boxSizing: "border-box", }; +const hintStyle: React.CSSProperties = { + margin: "6px 0 0", + fontSize: 12, + color: "#8892b0", + lineHeight: 1.5, +}; + const labelStyle: React.CSSProperties = { display: "block", fontSize: 11, @@ -36,11 +47,16 @@ const labelStyle: React.CSSProperties = { marginBottom: 6, }; -export default function BenchmarkForm({ onRunCreated, resetKey }: BenchmarkFormProps) { - const [targetUrl, setTargetUrl] = useState(""); +export default function BenchmarkForm({ config, onRunCreated }: BenchmarkFormProps) { + const { caps } = config; + // Picker value: a target URL from the allowlist, or CUSTOM (local use only). + const firstTarget = config.targets.length > 0 ? config.targets[0].url : CUSTOM; + const [targetChoice, setTargetChoice] = useState(firstTarget); + const [customUrl, setCustomUrl] = useState(""); const [method, setMethod] = useState("GET"); - const [numRequests, setNumRequests] = useState(50); - const [concurrency, setConcurrency] = useState(5); + const [numRequests, setNumRequests] = useState(Math.min(50, caps.max_num_requests)); + const [concurrency, setConcurrency] = useState(Math.min(5, caps.max_concurrency)); + const [timeoutS, setTimeoutS] = useState(Math.min(5, caps.max_request_timeout_s)); const [submitting, setSubmitting] = useState(false); const [error, setError] = useState(null); const [successId, setSuccessId] = useState(null); @@ -54,17 +70,30 @@ export default function BenchmarkForm({ onRunCreated, resetKey }: BenchmarkFormP const [slaAvg, setSlaAvg] = useState(""); const [slaErr, setSlaErr] = useState(""); - // Clear SLA fields and collapse the section whenever the parent resets the - // session. resetKey starts at 0, so the effect is skipped on first render. - useEffect(() => { - if (!resetKey) return; - setSlaP50(""); - setSlaP95(""); - setSlaP99(""); - setSlaAvg(""); - setSlaErr(""); - setSlaOpen(false); - }, [resetKey]); + const targetOptions: React.ReactNode[] = []; + for (const t of config.targets) { + targetOptions.push( + , + ); + } + if (config.allow_custom_target) { + targetOptions.push( + , + ); + } + + const methodOptions: React.ReactNode[] = []; + for (const m of HTTP_METHODS) { + methodOptions.push( + , + ); + } function inputStyle(name: string): React.CSSProperties { return { @@ -86,10 +115,11 @@ export default function BenchmarkForm({ onRunCreated, resetKey }: BenchmarkFormP setSubmitting(true); const payload: BenchmarkRequest = { - target_url: targetUrl, + target_url: targetChoice === CUSTOM ? customUrl : targetChoice, method, num_requests: numRequests, concurrency, + timeout_s: timeoutS, }; // Only include SLA fields that the user actually filled in. @@ -109,7 +139,7 @@ export default function BenchmarkForm({ onRunCreated, resetKey }: BenchmarkFormP setSuccessId(res.data.run_id); onRunCreated(res.data.run_id); } catch (err: unknown) { - setError(err instanceof Error ? err.message : "Request failed"); + setError(describeError(err)); } finally { setSubmitting(false); } @@ -130,82 +160,78 @@ export default function BenchmarkForm({ onRunCreated, resetKey }: BenchmarkFormP New Benchmark - {/* Row 1: URL + Method */} -
+ {/* Row 1: Target + Method */} +
- - setTargetUrl(e.target.value)} + + + {targetChoice === CUSTOM && ( + setCustomUrl(e.target.value)} + placeholder="https://api.example.com/endpoint" + required + style={{ ...inputStyle("custom"), marginTop: 8 }} + /> + )} + {!config.allow_custom_target && ( +

+ This demo only allows the targets listed here, so nothing private is ever called. +

+ )}
- +
- {/* Row 2: Requests + Concurrency */} -
+ {/* Row 2: Requests + Concurrency + Timeout, all inside the server caps */} +
- + setNumRequests(Number(e.target.value))} + onChange={(e) => setNumRequests(clampInt(e.target.value, 1, caps.max_num_requests))} onFocus={() => setFocused("reqs")} onBlur={() => setFocused(null)} style={inputStyle("reqs")} />
-
+
+ + setTimeoutS(clampInt(e.target.value, 1, caps.max_request_timeout_s))} + onFocus={() => setFocused("timeout")} + onBlur={() => setFocused(null)} + style={inputStyle("timeout")} + /> +
+

+ Limits: up to {caps.max_num_requests} requests, {caps.max_concurrency} at a time, each run + stops after {caps.run_wall_clock_limit_s} s. +

- {/* SLA Thresholds — collapsible */} + {/* SLA Thresholds, collapsible */}
+ ); + } + return (

- {EXAMPLE_QUESTIONS.map((q) => ( - - ))} + {chips}

-
- - {error && ( -
- {error} -
- )} - - {runs.length > 0 && !hasBaseline && ( -
- - - - - Pin a completed run as baseline to track regressions across future runs -
- )} - -
- - - - {["", "ID", "URL", "Method", "Status", "SLA", "p50 ms", "p95 ms", "p99 ms", "When"].map( - (col) => ( - - ) - )} - - - - {runs.map((run) => { + const rowList: React.ReactNode[] = []; + for (const run of runs) { const slaStatus = run.sla_result?.status; const slaExpanded = expandedSla === run.id; - return ( + rowList.push( setHoveredRow(run.id)} @@ -602,6 +536,7 @@ export default function RunsTable({ runs, total, error, onReset, onSetBaseline } {run.status === "done" && ( void onSetBaseline(run.id)} /> )} @@ -618,6 +553,7 @@ export default function RunsTable({ runs, total, error, onReset, onSetBaseline } > {run.id.slice(0, 8)}… {run.is_baseline && } + {run.is_demo === true && } {/* URL */} @@ -719,7 +655,7 @@ export default function RunsTable({ runs, total, error, onReset, onSetBaseline } - {/* Expandable SLA breakdown — rendered below the run row */} + {/* Expandable SLA breakdown, rendered below the run row */} {slaExpanded && run.sla_result && run.sla_result.thresholds.length > 0 && ( )} - ); - })} + ); + } + + return ( +
+
+
+

+ Benchmark Runs +

+ + {total} + +
+ + {ownBaseline && ( + + )} +
+ + {error && ( +
+ {error} +
+ )} + + {baselineRun !== null && ( +

+ Comparing against {ownBaseline ? "your baseline" : "the example baseline"}{" "} + {baselineRun.id.slice(0, 8)}. Percent chips + show change versus it: red is slower, green is faster. + {!ownBaseline && " Pin one of your own completed runs to compare against that instead."} +

+ )} + + {runs.length > 0 && !hasBaseline && ( +
+ + + + + Pin one of your completed runs as the baseline to track regressions +
+ )} + +
+
- {col} -
+ + + {headerCells} + + + + {rowList} {runs.length === 0 && ( -
Date: Mon, 2 Nov 2026 14:13:53 -0800 Subject: [PATCH 23/45] build: accept VITE_API_URL as a Docker build arg; document DEMO_TARGET_URL --- backend/README.md | 1 + frontend/Dockerfile | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/backend/README.md b/backend/README.md index 9c05a7e..78a3014 100644 --- a/backend/README.md +++ b/backend/README.md @@ -40,6 +40,7 @@ The hosted demo limits what a run can do. All limits are settings (see addresses, or their IPv6 equivalents. The name is resolved before each run and the connections are pinned to the validated addresses, so DNS cannot change the destination afterwards. Redirects are not followed. +- **Demo target URL**: `DEMO_TARGET_URL` is the full URL of the demo target (its host must also be in `ALLOWED_TARGET_HOSTS`); `GET /config` offers it in the UI target picker. - **Allowlist**: `ALLOWED_TARGET_HOSTS`, exact hostnames, on by default when auth is enabled. The demo target service in `../demo-target` goes on this list. - **Caps**: 500 requests, concurrency 20, 10 s per request, 60 s per run. diff --git a/frontend/Dockerfile b/frontend/Dockerfile index 5102411..eb183cb 100644 --- a/frontend/Dockerfile +++ b/frontend/Dockerfile @@ -9,6 +9,11 @@ RUN npm ci --ignore-scripts COPY . . +# Vite bakes VITE_* values into the bundle at build time, so the API URL has to +# be a build argument (docker build --build-arg VITE_API_URL=https://api.example.com). +ARG VITE_API_URL +ENV VITE_API_URL=$VITE_API_URL + # Build the Vite production bundle. RUN npm run build From 29702462890a879a00d049b78a5f026586a92294 Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 14:23:00 -0800 Subject: [PATCH 24/45] chore: remove stray root-level app/core/config.py --- app/core/config.py | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 app/core/config.py diff --git a/app/core/config.py b/app/core/config.py deleted file mode 100644 index 7b97ea1..0000000 --- a/app/core/config.py +++ /dev/null @@ -1,3 +0,0 @@ -azure_search_endpoint: str = "https://queryscope-search.search.windows.net" -azure_search_key: str = "REDACTED" -azure_search_index: str = "benchmark-runs" From 160258cae2c93ecb2b1e371b8e9b49ca140db955 Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 14:23:12 -0800 Subject: [PATCH 25/45] build: multi-stage non-root backend image; migrations opt-in via RUN_MIGRATIONS --- backend/.dockerignore | 11 +++++++ backend/Dockerfile | 60 ++++++++++++++++++++++++++------------- backend/entrypoint.sh | 18 ++++++------ demo-target/.dockerignore | 5 ++-- docker-compose.yml | 3 ++ frontend/.dockerignore | 6 ++++ 6 files changed, 73 insertions(+), 30 deletions(-) create mode 100644 backend/.dockerignore create mode 100644 frontend/.dockerignore diff --git a/backend/.dockerignore b/backend/.dockerignore new file mode 100644 index 0000000..a751131 --- /dev/null +++ b/backend/.dockerignore @@ -0,0 +1,11 @@ +.env +.env.* +.venv/ +__pycache__/ +*.pyc +.pytest_cache/ +tests/ +*.db +.git/ +Dockerfile +.dockerignore diff --git a/backend/Dockerfile b/backend/Dockerfile index 4b02a95..605a91e 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -1,32 +1,52 @@ -FROM python:3.11-slim +# syntax=docker/dockerfile:1 -# System deps needed by asyncpg (C extension) and Poetry itself. -RUN apt-get update && apt-get install -y --no-install-recommends \ - curl \ - build-essential \ - libpq-dev \ - && rm -rf /var/lib/apt/lists/* +# ---- builder: Poetry and compilers live here only ------------------------- +FROM python:3.11-slim AS builder -# Install Poetry — pinned so CI builds are reproducible. -RUN curl -sSL https://install.python-poetry.org | python3 - && \ - ln -s /root/.local/bin/poetry /usr/local/bin/poetry +ENV PIP_NO_CACHE_DIR=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + # Matches the version that wrote poetry.lock (lock-version 2.1). + POETRY_VERSION=2.5.1 \ + POETRY_VIRTUALENVS_IN_PROJECT=1 \ + POETRY_NO_INTERACTION=1 + +# build-essential covers any dependency that has no prebuilt wheel. +RUN apt-get update && apt-get install -y --no-install-recommends build-essential \ + && rm -rf /var/lib/apt/lists/* \ + && pip install "poetry==${POETRY_VERSION}" WORKDIR /app -# Copy dependency manifests first so Docker can cache the install layer. -# Re-installing only happens when pyproject.toml or poetry.lock changes. +# Manifests first so the dependency layer is cached until they change. COPY pyproject.toml poetry.lock ./ -# --no-root skips installing the package itself (we COPY the source below). -# --no-interaction / --no-ansi keep output clean in CI. -RUN poetry install --no-root --no-interaction --no-ansi +# --only main: no pytest/httpx/aiosqlite in the image. --no-root: the source is +# copied below and run from /app. +RUN poetry install --only main --no-root --no-ansi -# Copy the rest of the source after deps so source changes don't bust the cache. -COPY . . +# ---- runtime: no Poetry, no compilers, non-root --------------------------- +FROM python:3.11-slim AS runtime -COPY entrypoint.sh /entrypoint.sh -RUN chmod +x /entrypoint.sh +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PYTHONPATH=/app \ + PATH="/app/.venv/bin:$PATH" \ + # Hosted default: the image never migrates on start. Migrations run as a + # separate one-off job (see docs/deploy.md). docker-compose sets this to true. + RUN_MIGRATIONS=false +RUN useradd --system --uid 10001 --no-create-home --shell /usr/sbin/nologin app + +WORKDIR /app +COPY --from=builder /app/.venv /app/.venv +COPY . . +RUN chmod 0755 /app/entrypoint.sh + +USER 10001 EXPOSE 8000 -ENTRYPOINT ["/entrypoint.sh"] +# Standard-library probe so no curl is needed in the image. +HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \ + CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=4).status == 200 else 1)" + +ENTRYPOINT ["/app/entrypoint.sh"] diff --git a/backend/entrypoint.sh b/backend/entrypoint.sh index 29585a4..381eaa2 100644 --- a/backend/entrypoint.sh +++ b/backend/entrypoint.sh @@ -1,13 +1,15 @@ #!/bin/sh set -e -# Run migrations before starting the server so the schema is always up-to-date -# without requiring a separate migration step in CI or on first deploy. -# `alembic upgrade head` is idempotent — safe to run on every container start. -export PYTHONPATH=/app - -echo "Running Alembic migrations..." -poetry run alembic upgrade head +# Migrations are opt-in. The hosted image leaves RUN_MIGRATIONS=false and runs +# `alembic upgrade head` as a separate one-off job, so a rolling restart or a +# second replica can never race a schema change. Local compose sets it to true. +if [ "${RUN_MIGRATIONS:-false}" = "true" ]; then + echo "Running Alembic migrations..." + alembic upgrade head +fi echo "Starting uvicorn..." -exec poetry run uvicorn app.main:app --host 0.0.0.0 --port 8000 +# --proxy-headers is deliberately NOT used: client IP handling is done in the +# app from TRUSTED_PROXY_HOPS, which only trusts the right-most entries. +exec uvicorn app.main:app --host 0.0.0.0 --port 8000 diff --git a/demo-target/.dockerignore b/demo-target/.dockerignore index 4cde88d..aaa54f2 100644 --- a/demo-target/.dockerignore +++ b/demo-target/.dockerignore @@ -1,6 +1,7 @@ -tests/ __pycache__/ *.pyc .pytest_cache/ -README.md +tests/ pytest.ini +.env +.git/ diff --git a/docker-compose.yml b/docker-compose.yml index d3182aa..f69e13a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -27,6 +27,9 @@ services: - ./backend/.env environment: DATABASE_URL: postgresql+asyncpg://queryscope:queryscope@postgres:5432/queryscope + # Only used when the image is built from ./backend: the hosted image does + # not migrate on start, local compose does. + RUN_MIGRATIONS: "true" frontend: # build: ./frontend diff --git a/frontend/.dockerignore b/frontend/.dockerignore new file mode 100644 index 0000000..ba411f0 --- /dev/null +++ b/frontend/.dockerignore @@ -0,0 +1,6 @@ +node_modules/ +dist/ +.env +.env.* +.git/ +*.log From ab3b89a98aaa26c6bfdd1667b955a684ac3b68e7 Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 14:23:47 -0800 Subject: [PATCH 26/45] build: serve the frontend as static files; add SWA config with CSP and render script Also replaces the last .map calls in RunsTable with explicit loops. --- frontend/Dockerfile | 22 ++++----- frontend/nginx.conf | 21 ++++++++ frontend/package.json | 3 +- frontend/scripts/render-swa-config.mjs | 34 +++++++++++++ frontend/src/components/RunsTable.tsx | 68 ++++++++++++++------------ frontend/staticwebapp.config.json | 20 ++++++++ 6 files changed, 125 insertions(+), 43 deletions(-) create mode 100644 frontend/nginx.conf create mode 100644 frontend/scripts/render-swa-config.mjs create mode 100644 frontend/staticwebapp.config.json diff --git a/frontend/Dockerfile b/frontend/Dockerfile index eb183cb..eb07a94 100644 --- a/frontend/Dockerfile +++ b/frontend/Dockerfile @@ -1,25 +1,23 @@ -FROM node:20-slim +# syntax=docker/dockerfile:1 +# ---- build the static bundle ---------------------------------------------- +FROM node:20-slim AS build WORKDIR /app -# Copy manifests first to cache the npm install layer separately from source. COPY package.json package-lock.json ./ - RUN npm ci --ignore-scripts COPY . . -# Vite bakes VITE_* values into the bundle at build time, so the API URL has to -# be a build argument (docker build --build-arg VITE_API_URL=https://api.example.com). +# Vite bakes VITE_* values into the bundle at build time, so the API URL is a +# build argument (docker build --build-arg VITE_API_URL=https://api.example.com). ARG VITE_API_URL ENV VITE_API_URL=$VITE_API_URL - -# Build the Vite production bundle. RUN npm run build +# ---- serve it as static files (no vite preview) ----------------------------- +FROM nginxinc/nginx-unprivileged:1.27-alpine AS runtime +COPY nginx.conf /etc/nginx/conf.d/default.conf +COPY --from=build /app/dist /usr/share/nginx/html +# Same port the Vite preview server used, so compose and k8s mappings still hold. EXPOSE 4173 - -# --host 0.0.0.0 is required: Vite's preview server binds to localhost by -# default, which is unreachable from outside the container. The host flag -# makes it listen on all interfaces so Docker's port mapping works. -CMD ["npm", "run", "preview", "--", "--host", "0.0.0.0"] diff --git a/frontend/nginx.conf b/frontend/nginx.conf new file mode 100644 index 0000000..a64bed8 --- /dev/null +++ b/frontend/nginx.conf @@ -0,0 +1,21 @@ +# Used by the Docker image only (local compose / k8s). Azure Static Web Apps +# uses staticwebapp.config.json instead. +server { + listen 4173; + root /usr/share/nginx/html; + index index.html; + + add_header X-Content-Type-Options nosniff always; + add_header Referrer-Policy no-referrer always; + add_header X-Frame-Options DENY always; + + location /assets/ { + add_header Cache-Control "public, max-age=31536000, immutable"; + try_files $uri =404; + } + + # Single-page app fallback. + location / { + try_files $uri /index.html; + } +} diff --git a/frontend/package.json b/frontend/package.json index e58cede..b468163 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -8,7 +8,8 @@ "build": "tsc -b && vite build", "lint": "eslint .", "preview": "vite preview", - "test": "vitest run" + "test": "vitest run", + "build:swa": "npm run build && node scripts/render-swa-config.mjs" }, "dependencies": { "axios": "^1.13.6", diff --git a/frontend/scripts/render-swa-config.mjs b/frontend/scripts/render-swa-config.mjs new file mode 100644 index 0000000..bd453bc --- /dev/null +++ b/frontend/scripts/render-swa-config.mjs @@ -0,0 +1,34 @@ +// Writes dist/staticwebapp.config.json with the backend origin filled into the +// CSP connect-src. The origin comes from VITE_API_URL, the same value the +// bundle was built with, so the CSP can never drift from the real API. +import { readFileSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; + +const apiUrl = process.env.VITE_API_URL; +if (!apiUrl) { + console.error("VITE_API_URL is required (for example https://api.example.com)"); + process.exit(1); +} + +let origin; +try { + const parsed = new URL(apiUrl); + const isLocal = parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1"; + if (parsed.protocol !== "https:" && !isLocal) { + throw new Error("must be https"); + } + origin = parsed.origin; +} catch { + console.error("VITE_API_URL must be an https URL"); + process.exit(1); +} + +const template = readFileSync(resolve("staticwebapp.config.json"), "utf8"); +if (!template.includes("__API_ORIGIN__")) { + console.error("staticwebapp.config.json has no __API_ORIGIN__ placeholder"); + process.exit(1); +} +const rendered = template.split("__API_ORIGIN__").join(origin); +JSON.parse(rendered); // fail loudly if the result is not valid JSON +writeFileSync(resolve("dist", "staticwebapp.config.json"), rendered); +console.log("Wrote dist/staticwebapp.config.json for " + origin); diff --git a/frontend/src/components/RunsTable.tsx b/frontend/src/components/RunsTable.tsx index 2afa8b2..f9ea39c 100644 --- a/frontend/src/components/RunsTable.tsx +++ b/frontend/src/components/RunsTable.tsx @@ -252,28 +252,9 @@ function SlaBreakdownRow({ thresholds: SlaThresholdResult[]; colSpan: number; }) { - return ( -
- - - - {["Metric", "Target", "Actual", "Delta", ""].map((h) => ( + const slaHeaders: React.ReactNode[] = []; + for (const h of ["Metric", "Target", "Actual", "Delta", ""]) { + slaHeaders.push( - ))} - - - - {thresholds.map((t) => { + ); + } + + const thresholdRows: React.ReactNode[] = []; + for (const t of thresholds) { const meta = METRIC_META[t.metric] ?? { label: t.metric, unit: "" }; const overBudget = t.delta > 0; const deltaSign = t.delta > 0 ? "+" : ""; const deltaStr = `${deltaSign}${t.delta.toFixed(1)}${meta.unit}`; - return ( + thresholdRows.push( - ); - })} + ); + } + + return ( + + diff --git a/frontend/staticwebapp.config.json b/frontend/staticwebapp.config.json new file mode 100644 index 0000000..b16397c --- /dev/null +++ b/frontend/staticwebapp.config.json @@ -0,0 +1,20 @@ +{ + "navigationFallback": { + "rewrite": "/index.html", + "exclude": ["/assets/*", "/*.{svg,png,jpg,jpeg,gif,ico,json,txt,webmanifest}"] + }, + "globalHeaders": { + "Content-Security-Policy": "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' __API_ORIGIN__; base-uri 'none'; form-action 'none'; frame-ancestors 'none'", + "X-Content-Type-Options": "nosniff", + "Referrer-Policy": "no-referrer", + "X-Frame-Options": "DENY", + "Permissions-Policy": "camera=(), microphone=(), geolocation=()", + "Cache-Control": "no-store" + }, + "routes": [ + { + "route": "/assets/*", + "headers": { "Cache-Control": "public, max-age=31536000, immutable" } + } + ] +} From 0117167042c57cfb0c4890b1a962daf99c3759bd Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 14:24:20 -0800 Subject: [PATCH 27/45] feat: configurable backend URL and access code login for the MCP server and CLI --- cli/bin/queryscope.js | 73 ++++++++++++++++++--- mcp-server/src/index.ts | 141 +++++++++++++++++++++++++++++++++------- 2 files changed, 182 insertions(+), 32 deletions(-) diff --git a/cli/bin/queryscope.js b/cli/bin/queryscope.js index fdd90b4..c2c5180 100755 --- a/cli/bin/queryscope.js +++ b/cli/bin/queryscope.js @@ -31,6 +31,51 @@ const ENV_PATH = resolve(ROOT, "backend", ".env"); // Read version once at startup so banner and help text stay in sync. const pkg = JSON.parse(readFileSync(resolve(__dirname, "../package.json"), "utf8")); +// ── Backend URL and optional hosted-deployment auth ──────────────────────── + +// Defaults keep the local-stack behavior; set QUERYSCOPE_URL to point at a +// hosted deployment, and QUERYSCOPE_ACCESS_CODE if it requires login. +const API_URL = (process.env.QUERYSCOPE_URL || "http://localhost:8000").replace(/\/+$/, ""); +const ACCESS_CODE = process.env.QUERYSCOPE_ACCESS_CODE || ""; +// Needed only for `reset` against an auth-enabled backend (admin-only route). +const ADMIN_KEY = process.env.QUERYSCOPE_ADMIN_KEY || ""; + +let sessionToken = null; + +/** Exchange the access code for a token. Never prints the code or the token. */ +async function loginWithCode() { + const res = await fetch(`${API_URL}/auth/login`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ code: ACCESS_CODE }), + }); + // 404 means the server has auth disabled: carry on without a token. + if (res.status === 404) { sessionToken = null; return; } + if (!res.ok) { + throw new Error(res.status === 401 ? "The access code was not accepted" : `Login failed (${res.status})`); + } + sessionToken = (await res.json()).token; +} + +/** fetch against the backend; logs in when a code is set and re-logs in once on 401. */ +async function apiFetch(path, init = {}, retried = false) { + if (ACCESS_CODE && sessionToken === null) await loginWithCode(); + const headers = { ...(init.headers || {}) }; + if (sessionToken) headers.Authorization = `Bearer ${sessionToken}`; + const res = await fetch(`${API_URL}${path}`, { ...init, headers }); + if (res.status === 401 && ACCESS_CODE && !retried) { + sessionToken = null; + return apiFetch(path, init, true); + } + return res; +} + +// The backend is "up" for readiness purposes on any answer below 500, including +// 401 (running, but this client has no valid login yet). +function isUp(res) { + return res.status < 500; +} + // ── Banner ───────────────────────────────────────────────────────────────── const ASCII_ART = ` @@ -185,8 +230,8 @@ async function cmdInit() { let apiReady = false; while (Date.now() < deadline) { try { - const res = await fetch("http://localhost:8000/benchmark/runs"); - if (res.ok) { apiReady = true; break; } + const res = await apiFetch("/benchmark/runs"); + if (isUp(res)) { apiReady = true; break; } } catch { // still starting up — keep polling } @@ -221,8 +266,8 @@ async function cmdInit() { console.log( chalk.bold.green("\n QueryScope is running!\n") + chalk.dim(" Dashboard ") + chalk.cyan("http://localhost:5173") + "\n" + - chalk.dim(" API ") + chalk.cyan("http://localhost:8000") + "\n" + - chalk.dim(" API docs ") + chalk.cyan("http://localhost:8000/docs") + "\n" + chalk.dim(" API ") + chalk.cyan(API_URL) + "\n" + + chalk.dim(" API docs ") + chalk.cyan(`${API_URL}/docs`) + "\n" ); } @@ -252,8 +297,8 @@ async function cmdStart() { let apiReady = false; while (Date.now() < deadline) { try { - const res = await fetch("http://localhost:8000/benchmark/runs"); - if (res.ok) { apiReady = true; break; } + const res = await apiFetch("/benchmark/runs"); + if (isUp(res)) { apiReady = true; break; } } catch { // still starting up } @@ -268,7 +313,7 @@ async function cmdStart() { console.log( "\n" + chalk.dim(" Dashboard ") + chalk.cyan("http://localhost:5173") + "\n" + - chalk.dim(" API ") + chalk.cyan("http://localhost:8000") + "\n" + chalk.dim(" API ") + chalk.cyan(API_URL) + "\n" ); } @@ -283,7 +328,11 @@ function cmdMcp() { ${chalk.dim('"mcpServers":')} ${chalk.dim("{")} ${chalk.dim('"queryscope":')} ${chalk.dim("{")} ${chalk.dim('"command":')} ${chalk.green('"npx"')}${chalk.dim(",")} - ${chalk.dim('"args":')} ${chalk.green('["queryscope-mcp"]')} + ${chalk.dim('"args":')} ${chalk.green('["queryscope-mcp"]')}${chalk.dim(",")} + ${chalk.dim('"env":')} ${chalk.dim("{")} ${chalk.dim("optional, for a hosted deployment:")} + ${chalk.dim('"QUERYSCOPE_URL":')} ${chalk.green('"https://"')}${chalk.dim(",")} + ${chalk.dim('"QUERYSCOPE_ACCESS_CODE":')} ${chalk.green('""')} + ${chalk.dim("}")} ${chalk.dim("}")} ${chalk.dim("}")} ${chalk.dim("}")} @@ -308,8 +357,9 @@ async function cmdReset() { const spinner = ora("Resetting session…").start(); try { - const res = await fetch("http://localhost:8000/benchmark/runs", { + const res = await apiFetch("/benchmark/runs", { method: "DELETE", + headers: ADMIN_KEY ? { "X-Admin-Key": ADMIN_KEY } : {}, }); if (!res.ok) { const body = await res.text(); @@ -339,6 +389,11 @@ ${chalk.bold("Usage:")} queryscope ${chalk.cyan("start")} Start the stack (requires a previous init) queryscope ${chalk.cyan("reset")} Delete all benchmark runs and metrics queryscope ${chalk.cyan("mcp")} Print Claude Desktop MCP config snippet + +${chalk.bold("Environment:")} + QUERYSCOPE_URL Backend URL (default http://localhost:8000) + QUERYSCOPE_ACCESS_CODE Access code for a hosted deployment + QUERYSCOPE_ADMIN_KEY Admin key, needed by ${chalk.cyan("reset")} on a hosted deployment `; switch (command) { diff --git a/mcp-server/src/index.ts b/mcp-server/src/index.ts index 790056d..7489348 100644 --- a/mcp-server/src/index.ts +++ b/mcp-server/src/index.ts @@ -14,7 +14,92 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js" import axios from "axios"; import { z } from "zod"; -const BACKEND = "http://localhost:8000"; +// Where the backend lives. Defaults to a local stack; set QUERYSCOPE_URL for a +// hosted deployment (no trailing slash needed). +const BACKEND = (process.env.QUERYSCOPE_URL || "http://localhost:8000").replace(/\/+$/, ""); + +// Optional access code for a hosted (auth-enabled) deployment. With no code set +// the server behaves exactly as before and sends no Authorization header. +const ACCESS_CODE = process.env.QUERYSCOPE_ACCESS_CODE || ""; + +// Server-side caps on the hosted demo. Mirrored here so a bad request fails +// with a clear message before it leaves the machine. +const MAX_REQUESTS = 500; +const MAX_CONCURRENCY = 20; +const MAX_TIMEOUT_S = 10; + +let token: string | null = null; +let loginInFlight: Promise | null = null; + +/** Exchange the access code for a token. Never logs the code or the token. */ +async function login(): Promise { + if (!ACCESS_CODE) return; + try { + const res = await axios.post<{ token: string }>(`${BACKEND}/auth/login`, { code: ACCESS_CODE }); + token = res.data.token; + } catch (err) { + // 404 means the server has auth disabled: carry on without a token. + if (axios.isAxiosError(err) && err.response?.status === 404) { + token = null; + return; + } + const status = axios.isAxiosError(err) ? err.response?.status : undefined; + throw new Error( + status === 401 + ? "QueryScope rejected the access code in QUERYSCOPE_ACCESS_CODE" + : "Could not log in to QueryScope" + ); + } +} + +// Concurrent tool calls share one login instead of each starting their own. +function ensureLogin(): Promise { + if (loginInFlight === null) { + loginInFlight = login().finally(() => { + loginInFlight = null; + }); + } + return loginInFlight; +} + +const api = axios.create({ baseURL: BACKEND }); + +api.interceptors.request.use(async (config) => { + if (ACCESS_CODE && token === null) await ensureLogin(); + if (token) config.headers.Authorization = `Bearer ${token}`; + return config; +}); + +// Tokens expire (12 h by default) and revoked codes stop working: on a 401 log +// in again once and retry the request. +api.interceptors.response.use(undefined, async (error) => { + const original = error.config; + if ( + ACCESS_CODE && + axios.isAxiosError(error) && + error.response?.status === 401 && + original && + !original._retried + ) { + original._retried = true; + token = null; + await ensureLogin(); + if (token) original.headers.Authorization = `Bearer ${token}`; + return api.request(original); + } + return Promise.reject(error); +}); + +/** Short, safe text for a failed call (no request bodies, no credentials). */ +function describe(err: unknown): string { + if (axios.isAxiosError(err) && err.response) { + const detail = typeof err.response.data?.detail === "string" ? err.response.data.detail : ""; + const retry = err.response.headers["retry-after"]; + const wait = retry ? ` Retry after ${retry} s.` : ""; + return `QueryScope returned ${err.response.status}${detail ? ": " + detail : ""}.${wait}`; + } + return err instanceof Error ? err.message : "Request failed"; +} const server = new McpServer({ name: "queryscope-mcp", @@ -31,20 +116,26 @@ server.registerTool( description: "Run a load benchmark against an API endpoint", inputSchema: { target_url: z.string().url().describe("The URL to benchmark"), - method: z.string().default("GET").describe("HTTP method (GET, POST, …)"), - num_requests: z.number().int().min(1).default(20).describe("Total requests to send"), - concurrency: z.number().int().min(1).default(5).describe("Concurrent requests in flight"), + method: z.string().default("GET").describe("HTTP method (GET, POST, etc.)"), + num_requests: z.number().int().min(1).max(MAX_REQUESTS).default(20).describe(`Total requests to send (max ${MAX_REQUESTS})`), + concurrency: z.number().int().min(1).max(MAX_CONCURRENCY).default(5).describe(`Concurrent requests in flight (max ${MAX_CONCURRENCY})`), + timeout_s: z.number().positive().max(MAX_TIMEOUT_S).default(MAX_TIMEOUT_S).describe(`Per-request timeout in seconds (max ${MAX_TIMEOUT_S})`), }, }, - async ({ target_url, method, num_requests, concurrency }) => { - const res = await axios.post<{ run_id: string }>(`${BACKEND}/benchmark`, { - target_url, - method, - num_requests, - concurrency, - }); - - const { run_id } = res.data; + async ({ target_url, method, num_requests, concurrency, timeout_s }) => { + let run_id: string; + try { + const res = await api.post<{ run_id: string }>("/benchmark", { + target_url, + method, + num_requests, + concurrency, + timeout_s, + }); + run_id = res.data.run_id; + } catch (err) { + return { isError: true, content: [{ type: "text" as const, text: describe(err) }] }; + } return { content: [ @@ -89,9 +180,12 @@ server.registerTool( }, }, async ({ limit }) => { - const res = await axios.get(`${BACKEND}/benchmark/runs`, { - params: { limit }, - }); + let res; + try { + res = await api.get("/benchmark/runs", { params: { limit } }); + } catch (err) { + return { isError: true, content: [{ type: "text" as const, text: describe(err) }] }; + } const { items, total } = res.data; @@ -102,15 +196,16 @@ server.registerTool( } // Format each run as a compact summary line for easy reading by the LLM. - const lines = items.map((run) => { - const p50 = run.metrics ? `${run.metrics.p50.toFixed(1)}ms` : "—"; - const p95 = run.metrics ? `${run.metrics.p95.toFixed(1)}ms` : "—"; - const p99 = run.metrics ? `${run.metrics.p99.toFixed(1)}ms` : "—"; - return ( + const lines: string[] = []; + for (const run of items) { + const p50 = run.metrics ? `${run.metrics.p50.toFixed(1)}ms` : "-"; + const p95 = run.metrics ? `${run.metrics.p95.toFixed(1)}ms` : "-"; + const p99 = run.metrics ? `${run.metrics.p99.toFixed(1)}ms` : "-"; + lines.push( `[${run.id.slice(0, 8)}] ${run.method} ${run.target_url} ` + - `status=${run.status} p50=${p50} p95=${p95} p99=${p99}` + `status=${run.status} p50=${p50} p95=${p95} p99=${p99}` ); - }); + } const text = `${total} total run(s). Showing ${items.length}:\n\n${lines.join("\n")}`; From 1c6e99f44089df0d875146ac40054eccb7379cd6 Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 14:25:44 -0800 Subject: [PATCH 28/45] feat: add Bicep templates for the hosted demo (Container Apps, Postgres, Key Vault, SWA) --- infra/main.bicep | 591 +++++++++++++++++++++++++++++ infra/main.parameters.example.json | 19 + 2 files changed, 610 insertions(+) create mode 100644 infra/main.bicep create mode 100644 infra/main.parameters.example.json diff --git a/infra/main.bicep b/infra/main.bicep new file mode 100644 index 0000000..5727c1b --- /dev/null +++ b/infra/main.bicep @@ -0,0 +1,591 @@ +// QueryScope hosted demo. Resource group scope. +// +// Two-phase deploy (see docs/deploy.md): +// 1. deployApps=false -> platform only (ACR, Key Vault, Postgres, environment, SWA) +// 2. push images and set Key Vault secrets, then deployApps=true -> apps and job +// +// No secret values live in this file. The Postgres admin password is a @secure +// parameter supplied at deploy time; every other secret is set in Key Vault by +// the operator and referenced by the apps through a managed identity. + +targetScope = 'resourceGroup' + +// ---------------------------------------------------------------- parameters + +@description('Short lowercase prefix used in resource names (3-12 chars).') +@minLength(3) +@maxLength(12) +param namePrefix string + +param location string = resourceGroup().location + +@description('Static Web Apps is only available in some regions.') +@allowed(['westus2', 'centralus', 'eastus2', 'westeurope', 'eastasia']) +param staticWebAppLocation string = 'eastus2' + +@description('Phase 1 = false (platform only). Phase 2 = true (apps and migration job).') +param deployApps bool = false + +@description('Full image references, for example .azurecr.io/queryscope-backend:. Used when deployApps is true.') +param backendImage string = '' +param demoTargetImage string = '' + +param postgresAdminUser string = 'qsadmin' +@secure() +param postgresAdminPassword string +param postgresDatabaseName string = 'queryscope' +@description('Smallest burstable SKU. Verify availability in your region.') +param postgresSkuName string = 'Standard_B1ms' +param postgresStorageGb int = 32 +param postgresVersion string = '16' + +param acrSku string = 'Basic' +param logRetentionDays int = 30 +@description('Daily ingestion cap in GB for Log Analytics (-1 = no cap).') +param logDailyQuotaGb int = 1 + +param backendCpu string = '0.5' +param backendMemory string = '1Gi' +param demoTargetCpu string = '0.25' +param demoTargetMemory string = '0.5Gi' + +@description('Azure AI Search endpoint (not a secret).') +param azureSearchEndpoint string +param azureSearchIndex string = 'benchmark-runs-prod' + +@description('Comma-separated exact hostnames the backend may benchmark, in addition to the demo target (added automatically).') +param extraAllowedHosts string = 'httpbin.org' + +@description('Extra CORS origins (for a custom domain). The Static Web App origin is always included.') +param extraCorsOrigins array = [] + +@description('Trusted reverse-proxy hops in front of the backend. See docs/deploy.md for how to verify.') +param trustedProxyHops int = 1 + +@description('Email for budget and alert notifications.') +param alertEmail string +@description('Monthly budget in your billing currency.') +param monthlyBudget int = 25 +param budgetStartDate string = '${utcNow('yyyy-MM')}-01' + +param tags object = { app: 'queryscope', env: 'demo' } + +// ----------------------------------------------------------------- variables + +var suffix = uniqueString(resourceGroup().id) +var acrName = toLower('${namePrefix}acr${suffix}') +var kvName = toLower('${namePrefix}-kv-${take(suffix, 6)}') +var postgresName = toLower('${namePrefix}-pg-${take(suffix, 6)}') +var logName = '${namePrefix}-logs' +var envName = '${namePrefix}-env' +var identityName = '${namePrefix}-id' +var backendName = '${namePrefix}-api' +var demoTargetName = '${namePrefix}-target' +var migrateJobName = '${namePrefix}-migrate' +var swaName = '${namePrefix}-web' + +var acrPullRole = '7f951dda-4ed3-4680-a7ca-43fe172d538d' +var kvSecretsUserRole = '4633458b-17de-4789-8e26-0ba5ffc0a3a0' + +// Container Apps hostnames are predictable from the environment's default +// domain, so they are known in phase 1, before any app exists. That lets the +// frontend build and the allowlist be set up ahead of the apps. +var backendHost = '${backendName}.${containerEnv.properties.defaultDomain}' +var demoTargetHost = '${demoTargetName}.${containerEnv.properties.defaultDomain}' +var allowedTargetHosts = '${extraAllowedHosts},${demoTargetHost}' +var demoTargetUrl = 'https://${demoTargetHost}/work' + +var corsOrigins = concat(['https://${staticSite.properties.defaultHostname}'], extraCorsOrigins) + +// ------------------------------------------------------------------ platform + +resource logs 'Microsoft.OperationalInsights/workspaces@2023-09-01' = { + name: logName + location: location + tags: tags + properties: { + sku: { name: 'PerGB2018' } + retentionInDays: logRetentionDays + workspaceCapping: { dailyQuotaGb: logDailyQuotaGb } + } +} + +resource identity 'Microsoft.ManagedIdentity/userAssignedIdentities@2023-01-31' = { + name: identityName + location: location + tags: tags +} + +resource acr 'Microsoft.ContainerRegistry/registries@2023-07-01' = { + name: acrName + location: location + tags: tags + sku: { name: acrSku } + properties: { + adminUserEnabled: false // pull via managed identity, push via the deploy identity + anonymousPullEnabled: false + } +} + +resource acrPull 'Microsoft.Authorization/roleAssignments@2022-04-01' = { + scope: acr + name: guid(acr.id, identity.id, acrPullRole) + properties: { + roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', acrPullRole) + principalId: identity.properties.principalId + principalType: 'ServicePrincipal' + } +} + +resource kv 'Microsoft.KeyVault/vaults@2023-07-01' = { + name: kvName + location: location + tags: tags + properties: { + tenantId: subscription().tenantId + sku: { family: 'A', name: 'standard' } + enableRbacAuthorization: true + enableSoftDelete: true + softDeleteRetentionInDays: 7 + enablePurgeProtection: true + publicNetworkAccess: 'Enabled' + } +} + +resource kvSecretsUser 'Microsoft.Authorization/roleAssignments@2022-04-01' = { + scope: kv + name: guid(kv.id, identity.id, kvSecretsUserRole) + properties: { + roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', kvSecretsUserRole) + principalId: identity.properties.principalId + principalType: 'ServicePrincipal' + } +} + +resource postgres 'Microsoft.DBforPostgreSQL/flexibleServers@2023-12-01-preview' = { + name: postgresName + location: location + tags: tags + sku: { + name: postgresSkuName + tier: 'Burstable' + } + properties: { + version: postgresVersion + administratorLogin: postgresAdminUser + administratorLoginPassword: postgresAdminPassword + storage: { storageSizeGB: postgresStorageGb } + backup: { + backupRetentionDays: 7 + geoRedundantBackup: 'Disabled' + } + highAvailability: { mode: 'Disabled' } + network: { publicNetworkAccess: 'Enabled' } + } +} + +resource pgDatabase 'Microsoft.DBforPostgreSQL/flexibleServers/databases@2023-12-01-preview' = { + parent: postgres + name: postgresDatabaseName +} + +// The 0.0.0.0 rule means "any Azure service". It is the simple option without a +// VNet; the database still requires TLS and a strong password. See docs/deploy.md +// for the tighter alternative. +resource pgAllowAzure 'Microsoft.DBforPostgreSQL/flexibleServers/firewallRules@2023-12-01-preview' = { + parent: postgres + name: 'AllowAzureServices' + properties: { + startIpAddress: '0.0.0.0' + endIpAddress: '0.0.0.0' + } +} + +resource containerEnv 'Microsoft.App/managedEnvironments@2024-03-01' = { + name: envName + location: location + tags: tags + properties: { + appLogsConfiguration: { + destination: 'log-analytics' + logAnalyticsConfiguration: { + customerId: logs.properties.customerId + sharedKey: logs.listKeys().primarySharedKey + } + } + } +} + +resource staticSite 'Microsoft.Web/staticSites@2023-12-01' = { + name: swaName + location: staticWebAppLocation + tags: tags + sku: { + name: 'Free' + tier: 'Free' + } + properties: {} +} + +// ---------------------------------------------------------------------- apps + +var kvUri = kv.properties.vaultUri + +// Container Apps secret -> Key Vault reference through the managed identity. +var secretDefs = [ + { name: 'session-secret', kvName: 'session-secret' } + { name: 'code-pepper', kvName: 'code-pepper' } + { name: 'admin-api-key', kvName: 'admin-api-key' } + { name: 'database-url', kvName: 'database-url' } + { name: 'azure-search-key', kvName: 'azure-search-key' } + { name: 'openai-api-key', kvName: 'openai-api-key' } +] + +var appSecrets = [ + for s in secretDefs: { + name: s.name + keyVaultUrl: '${kvUri}secrets/${s.kvName}' + identity: identity.id + } +] + +var backendEnv = [ + { name: 'AUTH_ENABLED', value: 'true' } + { name: 'LLM_BENCHMARK_ENABLED', value: 'false' } + { name: 'RUN_MIGRATIONS', value: 'false' } + { name: 'CORS_ORIGINS', value: string(corsOrigins) } + { name: 'TRUSTED_PROXY_HOPS', value: string(trustedProxyHops) } + { name: 'AZURE_SEARCH_ENDPOINT', value: azureSearchEndpoint } + { name: 'AZURE_SEARCH_INDEX', value: azureSearchIndex } + { name: 'ALLOWED_TARGET_HOSTS', value: allowedTargetHosts } + { name: 'DEMO_TARGET_URL', value: demoTargetUrl } + { name: 'SESSION_SECRET', secretRef: 'session-secret' } + { name: 'CODE_PEPPER', secretRef: 'code-pepper' } + { name: 'ADMIN_API_KEY', secretRef: 'admin-api-key' } + { name: 'DATABASE_URL', secretRef: 'database-url' } + { name: 'AZURE_SEARCH_KEY', secretRef: 'azure-search-key' } + { name: 'OPENAI_API_KEY', secretRef: 'openai-api-key' } +] + +var registries = [ + { + server: acr.properties.loginServer + identity: identity.id + } +] + +resource backend 'Microsoft.App/containerApps@2024-03-01' = if (deployApps) { + name: backendName + location: location + tags: tags + identity: { + type: 'UserAssigned' + userAssignedIdentities: { '${identity.id}': {} } + } + properties: { + managedEnvironmentId: containerEnv.id + configuration: { + activeRevisionsMode: 'Single' + ingress: { + external: true + targetPort: 8000 + transport: 'auto' + allowInsecure: false + } + registries: registries + secrets: appSecrets + } + template: { + containers: [ + { + name: 'backend' + image: backendImage + resources: { + cpu: json(backendCpu) + memory: backendMemory + } + env: backendEnv + probes: [ + { + type: 'Liveness' + httpGet: { path: '/health', port: 8000 } + initialDelaySeconds: 20 + periodSeconds: 30 + } + { + type: 'Readiness' + httpGet: { path: '/health', port: 8000 } + periodSeconds: 10 + } + ] + } + ] + // Exactly one replica: the login throttle and the run admission lock are + // in-process. Do not raise maxReplicas without moving them out of process. + scale: { + minReplicas: 1 + maxReplicas: 1 + } + } + } + dependsOn: [acrPull, kvSecretsUser] +} + +resource demoTarget 'Microsoft.App/containerApps@2024-03-01' = if (deployApps) { + name: demoTargetName + location: location + tags: tags + identity: { + type: 'UserAssigned' + userAssignedIdentities: { '${identity.id}': {} } + } + properties: { + managedEnvironmentId: containerEnv.id + configuration: { + activeRevisionsMode: 'Single' + ingress: { + external: true + targetPort: 8080 + transport: 'auto' + allowInsecure: false + } + registries: registries + } + template: { + containers: [ + { + name: 'demo-target' + image: demoTargetImage + resources: { + cpu: json(demoTargetCpu) + memory: demoTargetMemory + } + probes: [ + { + type: 'Liveness' + httpGet: { path: '/health', port: 8080 } + periodSeconds: 30 + } + ] + } + ] + scale: { + minReplicas: 1 + maxReplicas: 1 + } + } + } + dependsOn: [acrPull] +} + +// One-off migration job: started manually by the deploy workflow (or by hand). +resource migrateJob 'Microsoft.App/jobs@2024-03-01' = if (deployApps) { + name: migrateJobName + location: location + tags: tags + identity: { + type: 'UserAssigned' + userAssignedIdentities: { '${identity.id}': {} } + } + properties: { + environmentId: containerEnv.id + configuration: { + triggerType: 'Manual' + replicaTimeout: 600 + replicaRetryLimit: 0 + manualTriggerConfig: { + parallelism: 1 + replicaCompletionCount: 1 + } + registries: registries + secrets: [ + { + name: 'database-url' + keyVaultUrl: '${kvUri}secrets/database-url' + identity: identity.id + } + ] + } + template: { + containers: [ + { + name: 'migrate' + image: backendImage + command: ['alembic'] + args: ['upgrade', 'head'] + resources: { + cpu: json('0.25') + memory: '0.5Gi' + } + env: [ + { name: 'DATABASE_URL', secretRef: 'database-url' } + ] + } + ] + } + } + dependsOn: [acrPull, kvSecretsUser] +} + +// --------------------------------------------------------- budget and alerts + +resource actionGroup 'Microsoft.Insights/actionGroups@2023-01-01' = { + name: '${namePrefix}-alerts' + location: 'global' + tags: tags + properties: { + groupShortName: take('${namePrefix}al', 12) + enabled: true + emailReceivers: [ + { + name: 'owner' + emailAddress: alertEmail + useCommonAlertSchema: true + } + ] + } +} + +resource budget 'Microsoft.Consumption/budgets@2023-05-01' = { + name: '${namePrefix}-monthly' + properties: { + category: 'Cost' + amount: monthlyBudget + timeGrain: 'Monthly' + timePeriod: { startDate: budgetStartDate } + notifications: { + actual50: { + enabled: true + operator: 'GreaterThan' + threshold: 50 + contactEmails: [alertEmail] + } + actual80: { + enabled: true + operator: 'GreaterThan' + threshold: 80 + contactEmails: [alertEmail] + } + forecast100: { + enabled: true + operator: 'GreaterThan' + threshold: 100 + thresholdType: 'Forecasted' + contactEmails: [alertEmail] + } + } + } +} + +// Repeated restarts usually mean a crash loop or a bad secret. +resource restartAlert 'Microsoft.Insights/metricAlerts@2018-03-01' = if (deployApps) { + name: '${namePrefix}-api-restarts' + location: 'global' + tags: tags + properties: { + description: 'Backend restarted several times in 15 minutes' + severity: 2 + enabled: true + scopes: [backend.id] + evaluationFrequency: 'PT5M' + windowSize: 'PT15M' + criteria: { + 'odata.type': 'Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria' + allOf: [ + { + name: 'restarts' + metricName: 'RestartCount' + metricNamespace: 'Microsoft.App/containerApps' + operator: 'GreaterThan' + threshold: 3 + timeAggregation: 'Total' + criterionType: 'StaticThresholdCriterion' + } + ] + } + actions: [{ actionGroupId: actionGroup.id }] + } +} + +// Sustained server errors from the API. +resource errorAlert 'Microsoft.Insights/metricAlerts@2018-03-01' = if (deployApps) { + name: '${namePrefix}-api-5xx' + location: 'global' + tags: tags + properties: { + description: 'More than 20 5xx responses in 15 minutes' + severity: 2 + enabled: true + scopes: [backend.id] + evaluationFrequency: 'PT5M' + windowSize: 'PT15M' + criteria: { + 'odata.type': 'Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria' + allOf: [ + { + name: 'errors' + metricName: 'Requests' + metricNamespace: 'Microsoft.App/containerApps' + operator: 'GreaterThan' + threshold: 20 + timeAggregation: 'Total' + criterionType: 'StaticThresholdCriterion' + dimensions: [ + { + name: 'statusCodeCategory' + operator: 'Include' + values: ['5xx'] + } + ] + } + ] + } + actions: [{ actionGroupId: actionGroup.id }] + } +} + +resource dbStorageAlert 'Microsoft.Insights/metricAlerts@2018-03-01' = { + name: '${namePrefix}-pg-storage' + location: 'global' + tags: tags + properties: { + description: 'Postgres storage above 80 percent' + severity: 2 + enabled: true + scopes: [postgres.id] + evaluationFrequency: 'PT15M' + windowSize: 'PT1H' + criteria: { + 'odata.type': 'Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria' + allOf: [ + { + name: 'storage' + metricName: 'storage_percent' + metricNamespace: 'Microsoft.DBforPostgreSQL/flexibleServers' + operator: 'GreaterThan' + threshold: 80 + timeAggregation: 'Average' + criterionType: 'StaticThresholdCriterion' + } + ] + } + actions: [{ actionGroupId: actionGroup.id }] + } +} + +// ------------------------------------------------------------------- outputs + +output acrName string = acr.name +output acrLoginServer string = acr.properties.loginServer +output keyVaultName string = kv.name +output identityName string = identity.name +output postgresHost string = postgres.properties.fullyQualifiedDomainName +output postgresDatabase string = postgresDatabaseName +output staticWebAppName string = staticSite.name +output staticWebAppUrl string = 'https://${staticSite.properties.defaultHostname}' +output backendAppName string = backendName +output demoTargetAppName string = demoTargetName +output migrateJobName string = migrateJobName +output backendUrl string = 'https://${backendHost}' +output demoTargetFqdn string = demoTargetHost +output demoTargetPublicUrl string = demoTargetUrl diff --git a/infra/main.parameters.example.json b/infra/main.parameters.example.json new file mode 100644 index 0000000..042d06c --- /dev/null +++ b/infra/main.parameters.example.json @@ -0,0 +1,19 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "namePrefix": { "value": "qscope" }, + "location": { "value": "eastus2" }, + "staticWebAppLocation": { "value": "eastus2" }, + "deployApps": { "value": false }, + "backendImage": { "value": "" }, + "demoTargetImage": { "value": "" }, + "postgresSkuName": { "value": "Standard_B1ms" }, + "azureSearchEndpoint": { "value": "https://REPLACE-ME.search.windows.net" }, + "azureSearchIndex": { "value": "benchmark-runs-prod" }, + "extraAllowedHosts": { "value": "httpbin.org" }, + "trustedProxyHops": { "value": 1 }, + "alertEmail": { "value": "you@example.com" }, + "monthlyBudget": { "value": 25 } + } +} From af76f4ccd9d4fee683068d2207125fcd05127e2b Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 14:25:49 -0800 Subject: [PATCH 29/45] ci: add CI workflow and manual OIDC deploy workflow --- .github/workflows/ci.yml | 87 ++++++++++++++++++++++ .github/workflows/deploy.yml | 138 +++++++++++++++++++++++++++++++++++ 2 files changed, 225 insertions(+) create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/deploy.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..2187dd2 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,87 @@ +name: CI + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + backend: + runs-on: ubuntu-24.04 + defaults: + run: + working-directory: backend + steps: + - uses: actions/checkout@v4.2.2 + - uses: actions/setup-python@v5.3.0 + with: + python-version: "3.11" + - name: Install Poetry + # Same version that wrote poetry.lock. + run: pip install "poetry==2.5.1" + - name: Install dependencies + run: poetry install --no-root --no-ansi + - name: Tests (SQLite, no network) + run: poetry run pytest -q + + demo-target: + runs-on: ubuntu-24.04 + defaults: + run: + working-directory: demo-target + steps: + - uses: actions/checkout@v4.2.2 + - uses: actions/setup-python@v5.3.0 + with: + python-version: "3.11" + - name: Install dependencies + run: pip install -r requirements.txt pytest + - name: Tests + run: python -m pytest -q + + frontend: + runs-on: ubuntu-24.04 + defaults: + run: + working-directory: frontend + steps: + - uses: actions/checkout@v4.2.2 + - uses: actions/setup-node@v4.1.0 + with: + node-version: "20" + cache: npm + cache-dependency-path: frontend/package-lock.json + - run: npm ci --ignore-scripts + - name: Type-check + run: npx tsc -b + - name: Lint + run: npm run lint + - name: Tests + run: npm test + - name: Build and render the SWA config + env: + VITE_API_URL: https://api.example.invalid + run: npm run build:swa + + node-packages: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4.2.2 + - uses: actions/setup-node@v4.1.0 + with: + node-version: "20" + - name: Build the MCP server + working-directory: mcp-server + run: | + npm ci --ignore-scripts + npx tsc --noEmit + - name: Syntax-check the CLI + working-directory: cli + run: node --check bin/queryscope.js diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..56e16b0 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,138 @@ +name: Deploy (manual) + +# Manual only. Needs the repository variables listed in docs/deploy.md and an +# Entra app registration with a federated credential for the "production" +# environment. No cloud passwords are stored in GitHub. +on: + workflow_dispatch: + inputs: + deploy_frontend: + description: Also build and deploy the frontend + type: boolean + default: true + +permissions: + id-token: write # OIDC token for azure/login + contents: read + +concurrency: + group: deploy + cancel-in-progress: false + +jobs: + deploy: + runs-on: ubuntu-24.04 + environment: production + timeout-minutes: 40 + env: + RG: ${{ vars.AZURE_RESOURCE_GROUP }} + ACR: ${{ vars.ACR_NAME }} + BACKEND_APP: ${{ vars.BACKEND_APP }} + TARGET_APP: ${{ vars.DEMO_TARGET_APP }} + MIGRATE_JOB: ${{ vars.MIGRATE_JOB }} + SWA_NAME: ${{ vars.SWA_NAME }} + API_URL: ${{ vars.API_URL }} + TAG: ${{ github.sha }} + steps: + - uses: actions/checkout@v4.2.2 + + - name: Log in to Azure (OIDC) + uses: azure/login@v2.2.0 + with: + client-id: ${{ vars.AZURE_CLIENT_ID }} + tenant-id: ${{ vars.AZURE_TENANT_ID }} + subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }} + + - name: Log in to the registry + run: az acr login --name "$ACR" + + - name: Build and push images + run: | + set -euo pipefail + SERVER="$ACR.azurecr.io" + docker build -t "$SERVER/queryscope-backend:$TAG" backend + docker build -t "$SERVER/queryscope-demo-target:$TAG" demo-target + docker push "$SERVER/queryscope-backend:$TAG" + docker push "$SERVER/queryscope-demo-target:$TAG" + + - name: Run database migrations (one-off job) + run: | + set -euo pipefail + SERVER="$ACR.azurecr.io" + az containerapp job update -g "$RG" -n "$MIGRATE_JOB" \ + --image "$SERVER/queryscope-backend:$TAG" --output none + EXEC=$(az containerapp job start -g "$RG" -n "$MIGRATE_JOB" --query name -o tsv) + echo "Started migration execution $EXEC" + for _ in $(seq 1 60); do + STATUS=$(az containerapp job execution show -g "$RG" -n "$MIGRATE_JOB" \ + --job-execution-name "$EXEC" --query properties.status -o tsv) + echo "Migration status: $STATUS" + if [ "$STATUS" = "Succeeded" ]; then exit 0; fi + if [ "$STATUS" = "Failed" ] || [ "$STATUS" = "Stopped" ]; then + echo "Migration did not succeed; apps were NOT updated." >&2 + exit 1 + fi + sleep 10 + done + echo "Timed out waiting for the migration job." >&2 + exit 1 + + - name: Update the apps + run: | + set -euo pipefail + SERVER="$ACR.azurecr.io" + az containerapp update -g "$RG" -n "$BACKEND_APP" \ + --image "$SERVER/queryscope-backend:$TAG" --output none + az containerapp update -g "$RG" -n "$TARGET_APP" \ + --image "$SERVER/queryscope-demo-target:$TAG" --output none + + - name: Check the backend is healthy + run: | + set -euo pipefail + for _ in $(seq 1 30); do + if curl -fsS "$API_URL/health" >/dev/null; then + echo "Backend healthy" + exit 0 + fi + sleep 10 + done + echo "Backend did not become healthy" >&2 + exit 1 + + - uses: actions/setup-node@v4.1.0 + if: ${{ inputs.deploy_frontend }} + with: + node-version: "20" + cache: npm + cache-dependency-path: frontend/package-lock.json + + - name: Build the frontend + if: ${{ inputs.deploy_frontend }} + working-directory: frontend + env: + VITE_API_URL: ${{ vars.API_URL }} + run: | + set -euo pipefail + npm ci --ignore-scripts + npm run build:swa + + - name: Fetch the Static Web Apps deployment token + if: ${{ inputs.deploy_frontend }} + id: swa + run: | + set -euo pipefail + TOKEN=$(az staticwebapp secrets list -g "$RG" -n "$SWA_NAME" --query properties.apiKey -o tsv) + echo "::add-mask::$TOKEN" + echo "token=$TOKEN" >> "$GITHUB_OUTPUT" + + - name: Deploy the frontend + if: ${{ inputs.deploy_frontend }} + uses: Azure/static-web-apps-deploy@v1 + with: + azure_static_web_apps_api_token: ${{ steps.swa.outputs.token }} + action: upload + # The bundle is already built; dist/ contains the rendered + # staticwebapp.config.json. + skip_app_build: true + skip_api_build: true + app_location: frontend/dist From f6658f10ddf63391a28f41c9cbf5293c5e6a5186 Mon Sep 17 00:00:00 2001 From: Kavish Date: Mon, 2 Nov 2026 14:28:44 -0800 Subject: [PATCH 30/45] docs: add hosted deployment runbook --- .gitignore | 3 + cli/bin/queryscope.js | 19 +- docs/deploy.md | 457 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 470 insertions(+), 9 deletions(-) create mode 100644 docs/deploy.md diff --git a/.gitignore b/.gitignore index 55b9e3e..a0afd73 100644 --- a/.gitignore +++ b/.gitignore @@ -27,3 +27,6 @@ CLAUDE.md # graphify knowledge-graph output (local analysis artifacts) graphify-out/ + +infra/main.parameters.json +qs-outputs.json diff --git a/cli/bin/queryscope.js b/cli/bin/queryscope.js index c2c5180..e85e10c 100755 --- a/cli/bin/queryscope.js +++ b/cli/bin/queryscope.js @@ -3,10 +3,10 @@ * queryscope CLI * * Commands: - * queryscope init — first-time setup: prompts for secrets, writes .env, + * queryscope init , first-time setup: prompts for secrets, writes .env, * builds + starts the Docker stack, creates Azure index - * queryscope start — start the stack (assumes .env already exists) - * queryscope reset — delete all benchmark runs via the API + * queryscope start , start the stack (assumes .env already exists) + * queryscope reset , delete all benchmark runs via the API */ import chalk from "chalk"; @@ -126,7 +126,7 @@ async function cmdInit() { // ── Check Docker ───────────────────────────────────────────────────────── const dockerSpinner = ora("Checking Docker…").start(); - // reject: false tells execa to never throw on a non-zero exit code — warnings + // reject: false tells execa to never throw on a non-zero exit code, warnings // written to stderr were causing false failures even when Docker was healthy. const dockerResult = await execa("docker", ["info"], { cwd: ROOT, @@ -233,7 +233,7 @@ async function cmdInit() { const res = await apiFetch("/benchmark/runs"); if (isUp(res)) { apiReady = true; break; } } catch { - // still starting up — keep polling + // still starting up, keep polling } await new Promise((r) => setTimeout(r, 2000)); } @@ -291,7 +291,7 @@ async function cmdStart() { fatal("See output above for details."); } - // Poll until the backend is ready — migrations run at startup. + // Poll until the backend is ready, migrations run at startup. const apiSpinner = ora("Waiting for backend to be ready…").start(); const deadline = Date.now() + 60_000; let apiReady = false; @@ -319,7 +319,7 @@ async function cmdStart() { function cmdMcp() { // Print the JSON snippet the user needs to paste into claude_desktop_config.json. - // Using npx means the user doesn't need a global install — npx will pull + // Using npx means the user doesn't need a global install, npx will pull // queryscope-mcp from the npm registry on first use and cache it locally. console.log(` Add this to ${chalk.cyan("~/Library/Application Support/Claude/claude_desktop_config.json")}: @@ -329,7 +329,7 @@ function cmdMcp() { ${chalk.dim('"queryscope":')} ${chalk.dim("{")} ${chalk.dim('"command":')} ${chalk.green('"npx"')}${chalk.dim(",")} ${chalk.dim('"args":')} ${chalk.green('["queryscope-mcp"]')}${chalk.dim(",")} - ${chalk.dim('"env":')} ${chalk.dim("{")} ${chalk.dim("optional, for a hosted deployment:")} + ${chalk.dim('"env":')} ${chalk.dim("{")} ${chalk.dim('"QUERYSCOPE_URL":')} ${chalk.green('"https://"')}${chalk.dim(",")} ${chalk.dim('"QUERYSCOPE_ACCESS_CODE":')} ${chalk.green('""')} ${chalk.dim("}")} @@ -337,6 +337,7 @@ function cmdMcp() { ${chalk.dim("}")} ${chalk.dim("}")} + The "env" block is only for a hosted deployment; leave it out for a local stack. Then restart Claude Desktop. `); } @@ -382,7 +383,7 @@ async function cmdReset() { const command = process.argv[2]; const HELP = ` -${chalk.bold("queryscope")} — QueryScope CLI +${chalk.bold("queryscope")}, QueryScope CLI ${chalk.bold("Usage:")} queryscope ${chalk.cyan("init")} First-time setup: configure secrets, build, and start the stack diff --git a/docs/deploy.md b/docs/deploy.md new file mode 100644 index 0000000..dd99f0c --- /dev/null +++ b/docs/deploy.md @@ -0,0 +1,457 @@ +# Hosted demo: deployment runbook + +This is the step-by-step guide for putting QueryScope online as an invite-only +demo on Azure. Everything here is prepared as files; nothing has been deployed. +Commands marked **(changes Azure)** create or modify cloud resources. Read each +one before running it. + +Costs and free-tier statements below are **estimates written from memory of +Azure's public pricing. Verify every number on the Azure pricing calculator and +your own subscription before relying on it.** The Bicep templates and workflows +were also written without being run against Azure; expect to fix small issues on +the first real deployment (see section 16). + +## 0. Architecture + +``` +recruiter browser + | https https (Bearer token, CORS-restricted) + v ^ +Azure Static Web Apps ------------------> Container App: backend (1 replica, fixed) +(Vite bundle, CSP, no-referrer) | | | + | | +--> Azure AI Search (index benchmark-runs-prod) + | +--> Key Vault (secrets, via managed identity) + v + PostgreSQL Flexible Server (B1ms) + +Container App: demo-target (public HTTPS, benchmarked by the backend) +Container Apps Job: migrate (manual, runs "alembic upgrade head") +ACR (images) Log Analytics (logs) Budget + alerts +``` + +**The backend must stay at exactly one replica.** The login throttle and the +run-admission lock live in process memory. `infra/main.bicep` pins +`minReplicas = maxReplicas = 1`. The Horizontal Pod Autoscaler in `k8s/hpa.yaml` +(2 to 6 replicas) is therefore **incompatible with the hosted design**; `k8s/` is +left untouched and is for local Kubernetes experiments only. + +## 1. Prerequisites + +- An Azure subscription where you can create resources and role assignments. +- Azure CLI (`az`) with Bicep (`az bicep install`), signed in with `az login`. +- Docker, `openssl`, `curl`, `jq`. +- A GitHub repository with Actions enabled. +- An OpenAI account and an Azure AI Search service you control. +- A short `namePrefix` (3 to 12 lowercase letters), for example `qscope`. + +Azure for Students notes (verify): the student offer gives a small credit (about +100 USD) and may restrict allowed regions and some SKUs through policy. If a +deployment is rejected with a policy error, choose a region from the allowed list +and re-run. ACR Tasks (`az acr build`) are sometimes blocked on student +subscriptions, which is why the workflow uses a local `docker build` and +`docker push` instead. + +## 2. Before anything else: rotate leaked keys + +The repository history contains a leaked Azure key (see the Week 4 TODO in +`CLAUDE.md`). Treat every key that was ever in `.env` as compromised. + +1. **Azure AI Search**: Portal, your search service, Settings, Keys. Regenerate + the admin keys (secondary first, switch to it, then the primary). +2. **OpenAI**: create a **new key in a new project** dedicated to this demo, then + delete the old key. +3. Never paste keys into chat, tickets, shell history or files in the repo. +4. Before making the repository public, scrub history with `git filter-repo` + and a replace-text file kept outside the repo, then force-push. + +## 3. Spending caps + +- **OpenAI**: in the dedicated project, Settings, Limits, set a monthly budget + (a few dollars is plenty) with a hard stop if your plan offers it, plus a low + email-alert threshold. +- **Azure**: `infra/main.bicep` creates a monthly budget with alerts at 50 + percent, 80 percent and forecast 100 percent. A budget **alerts**; it does not + stop spending. Check it in Cost Management after deploying. +- The application limits itself too: 500 requests per run, 2,000 requests per + code per day and 10,000 overall per day. + +## 4. Create the resource group and deploy the platform (phase 1) + +Phase 1 creates everything except the apps and the migration job, which need +images and secrets that do not exist yet. + +```bash +az login +az account set --subscription "" + +RG=queryscope-rg +LOCATION=eastus2 +az group create --name "$RG" --location "$LOCATION" # (changes Azure) + +cp infra/main.parameters.example.json infra/main.parameters.json # git-ignored +# Edit infra/main.parameters.json: namePrefix, azureSearchEndpoint, alertEmail. + +# Generated without printing. Stored in Key Vault in section 5. +PGPASS=$(openssl rand -hex 24) + +az deployment group create \ + --resource-group "$RG" \ + --template-file infra/main.bicep \ + --parameters @infra/main.parameters.json \ + --parameters postgresAdminPassword="$PGPASS" \ + --query properties.outputs --output json > qs-outputs.json # (changes Azure) +``` + +`postgresAdminPassword="$PGPASS"` is visible in the local process list while `az` +runs; acceptable on a personal machine. `qs-outputs.json` holds names and +hostnames only, no secrets (it is git-ignored; do not commit it). Read values: + +```bash +ACR=$(jq -r .acrName.value qs-outputs.json) +KV=$(jq -r .keyVaultName.value qs-outputs.json) +PGHOST=$(jq -r .postgresHost.value qs-outputs.json) +API_URL=$(jq -r .backendUrl.value qs-outputs.json) +WEB_URL=$(jq -r .staticWebAppUrl.value qs-outputs.json) +DEMO_URL=$(jq -r .demoTargetPublicUrl.value qs-outputs.json) +BACKEND_APP=$(jq -r .backendAppName.value qs-outputs.json) +MIGRATE_JOB=$(jq -r .migrateJobName.value qs-outputs.json) +``` + +The backend and demo-target hostnames are predictable from the environment's +default domain, so `API_URL`, `DEMO_URL` and the allowlist are already correct +even though the apps do not exist yet. `CORS_ORIGINS` is the exact Static Web App +origin, set automatically. + +## 5. Put secrets in Key Vault (never print them) + +Writing secrets needs the **Key Vault Secrets Officer** role: + +```bash +ME=$(az ad signed-in-user show --query id -o tsv) +az role assignment create --assignee "$ME" --role "Key Vault Secrets Officer" \ + --scope "$(az keyvault show -n "$KV" --query id -o tsv)" # (changes Azure) +``` + +Role assignments can take a minute or two. Two rules for every command below: +always `--output none` (otherwise `az` echoes the value back), and pass values +through stdin or a hidden prompt, never as arguments. + +```bash +# Random secrets (generated and stored, never shown): +for NAME in session-secret code-pepper admin-api-key; do + openssl rand -base64 48 | tr -d '\n' | \ + az keyvault secret set --vault-name "$KV" --name "$NAME" \ + --file /dev/stdin --encoding utf-8 --output none +done + +# The Postgres admin password (needed again when the template is re-run): +printf '%s' "$PGPASS" | az keyvault secret set --vault-name "$KV" \ + --name postgres-admin-password --file /dev/stdin --encoding utf-8 --output none + +# DATABASE_URL. ssl=require makes asyncpg use TLS, which Azure Postgres requires. +printf '%s' "postgresql+asyncpg://qsadmin:${PGPASS}@${PGHOST}:5432/queryscope?ssl=require" | \ + az keyvault secret set --vault-name "$KV" --name database-url \ + --file /dev/stdin --encoding utf-8 --output none +unset PGPASS + +# Keys you paste yourself (hidden prompt, then unset): +for NAME in azure-search-key openai-api-key; do + printf 'Value for %s (input hidden): ' "$NAME"; read -rs VALUE; echo + printf '%s' "$VALUE" | az keyvault secret set --vault-name "$KV" --name "$NAME" \ + --file /dev/stdin --encoding utf-8 --output none + unset VALUE +done +``` + +Keep the **admin API key** in a password manager (you need it for admin routes +and `queryscope reset`). Copy it without displaying it: +`az keyvault secret show --vault-name "$KV" --name admin-api-key --query value -o tsv | pbcopy` +(macOS), paste into the manager, then clear the clipboard. + +## 6. Build and push images, then deploy the apps (phase 2) + +Pushing needs AcrPush: +`az role assignment create --assignee "$ME" --role AcrPush --scope "$(az acr show -n "$ACR" --query id -o tsv)"`. + +```bash +az acr login --name "$ACR" +TAG=$(git rev-parse --short HEAD) +docker build -t "$ACR.azurecr.io/queryscope-backend:$TAG" backend +docker build -t "$ACR.azurecr.io/queryscope-demo-target:$TAG" demo-target +docker push "$ACR.azurecr.io/queryscope-backend:$TAG" +docker push "$ACR.azurecr.io/queryscope-demo-target:$TAG" + +PGPASS=$(az keyvault secret show --vault-name "$KV" --name postgres-admin-password --query value -o tsv) +az deployment group create \ + --resource-group "$RG" \ + --template-file infra/main.bicep \ + --parameters @infra/main.parameters.json \ + --parameters deployApps=true \ + backendImage="$ACR.azurecr.io/queryscope-backend:$TAG" \ + demoTargetImage="$ACR.azurecr.io/queryscope-demo-target:$TAG" \ + postgresAdminPassword="$PGPASS" \ + --output none # (changes Azure) +unset PGPASS +``` + +## 7. Run migrations and create the search index + +The backend image does not migrate on start. Run the one-off job before the first +request: + +```bash +EXEC=$(az containerapp job start -g "$RG" -n "$MIGRATE_JOB" --query name -o tsv) # (changes Azure) +az containerapp job execution show -g "$RG" -n "$MIGRATE_JOB" \ + --job-execution-name "$EXEC" --query properties.status -o tsv # repeat until Succeeded +``` + +Create the production index. The running container already has every setting, so +run the script there (no secrets on your laptop): + +```bash +az containerapp exec -g "$RG" -n "$BACKEND_APP" --command "python scripts/create_azure_index.py" +``` + +It uses `AZURE_SEARCH_INDEX=benchmark-runs-prod` from the app environment, so it +never touches the old `benchmark-runs` index. Re-running is safe. + +## 8. Seed demo runs and create the first access code + +```bash +# Demo runs against the demo target, also indexed so diagnose can find them: +az containerapp exec -g "$RG" -n "$BACKEND_APP" --command \ + "python scripts/seed_demo.py --target-url $DEMO_URL --index" + +# First access code. Printed ONCE; only its hash is stored. Do not paste it into +# chat or commit it. Share it with the recruiter privately. +az containerapp exec -g "$RG" -n "$BACKEND_APP" --command \ + "python scripts/manage_codes.py create stripe-rebecca" +``` + +Codes look like `label.aB3dE5gH7k`. A magic link is `/#code=`: the +code sits in the URL fragment, which browsers never send to servers, and the app +removes it from the address bar on load. Use `manage_codes.py list` and +`manage_codes.py revoke
{h}
{meta.label} @@ -347,8 +328,35 @@ function SlaBreakdownRow({
+ + + + {slaHeaders} + + + + {thresholdRows}