From 3b953dcdc6b01f41a528d9d4bdc0351d5721b931 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Gruszczy=C5=84ski?= Date: Mon, 23 Nov 2026 12:23:41 +0100 Subject: [PATCH] v0.41.0 --- CHANGELOG.md | 9 +- docs/CUSTOM_LOCATIONS.md | 4 +- docs/FEATURES.md | 2 +- docs/LOAD_BALANCING.md | 4 +- docs/RESPONSE_DELIVERY.md | 38 ++++ langs/en_US.json | 29 ++- langs/pl_pl.json | 29 ++- src/admin/openapi.json | 2 +- src/admin/web/css/40-editors.css | 22 +++ src/admin/web/vhosts/balancing.js | 2 +- src/admin/web/vhosts/core.js | 29 ++- src/admin/web/vhosts/editor.js | 10 +- src/admin/web/vhosts/routing.js | 2 +- src/balance/hash_tests.rs | 4 +- src/balance/pool_core.rs | 30 +++ src/config/routing_conditions_tests.rs | 2 +- src/headers/mod.rs | 254 ++++++++++++++++++++++++- src/headers/tests.rs | 57 ++++++ src/proxy/body/mod.rs | 2 + src/proxy/body/tests.rs | 1 + src/proxy/cache_helpers.rs | 16 ++ src/proxy/forward/route_cache.rs | 61 ++++++ src/proxy/upstream_helpers.rs | 63 +++++- 23 files changed, 643 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dc2cd3a..2d966fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,16 +8,17 @@ Release history focused on **features, settings, default behavior, compatibility - **Rules for the whole host:** the new match type `any` (requires at least one condition) applies to every path of the Vhost and ranks like a regular expression — e.g. office network + staff cookie → `office` backends for the whole site. Combined with the 0.40.2 backend groups and per-location balancing this covers frontend-level and path-level `use_backend` rules. - **Correctness and caching:** conditional locations are selected after the final client address and (when a condition needs it) the country are known; earlier stages and proactive cache refreshes only consider unconditional locations, and the response layer uses the finally selected location. Responses of conditional locations are never cached (`cache` must be inherit/off), so a cached unconditional response is never served to a request that matches a conditional location. - **Panel:** each location has a **Conditions** section (source, name, operator, values one per line, NOT, ignore case), an **Add rule for the whole host** button, **↑ / ↓** buttons to order locations, condition counts in the summary and a **Test routing** panel that evaluates the unsaved draft: method, URL, client IP, country and headers → winning location, path ✓/✗ and every condition ✓/✗ for all locations, the target backend (including the consistent-hash member) and the cache bypass. English and Polish texts added. -- **Compatibility:** configurations without `conditions` or `match_type: "any"` are unchanged and serialize as before. Configurations using them are rejected by 0.40.2 and older. Glob wildcards are still not supported in paths; use regular expressions (documented). -- **Verification:** new Rust tests run 19 shared routing cases from `tests/fixtures/routing_conditions_cases.json` (exact/prefix/regex/any precedence, fall-through, every source and operator, negation, country, IPv4/IPv6 CIDR), check that conditional locations are skipped without request facts and never cached, and reject 14 invalid configurations; `tools/dev/test_routing_tester.js` runs the same cases against the panel tester. Full suite, `cargo clippy --all-targets` and `cargo fmt --check` clean. The real binary was run in headless mode against four mock origins: header, IP + cookie (whole-host rule) and POST-only routing reached the expected origins; a cacheable `/api/` response was `HIT` for plain requests while `X-Beta` requests went to the beta origin with `BYPASS / route_disabled`. In panel mode (Chrome) the tester, a new whole-host rule, reordering and saving were exercised. Not tested: production traffic, HTTP/3 clients, GeoIP-based country conditions with a real database. +- **Variables in header values (diagnostic headers, HAProxy `set-header X-S %[srv_id]` style):** `set`/`append` values in global, Vhost and location header rules may contain `%[srv_id]`, `%[srv_url]`, `%[location]`, `%[vhost]`, `%[lb_algorithm]`, `%[hash_key]`, `%[client_ip]`, `%[country]`, `%[req_id]`, `%[method]`, `%[host]`, `%[path]` and, in response rules, `%[cache_status]` and `%[backend_time]`. Rules with variables are rendered per request and applied last: request rules after backend selection (so the origin can receive e.g. `X-Shard: mp3_2`), response rules at final delivery after cache handling — they are never stored in cached objects. Missing values render as `-`; a rendered value that is not a valid header value skips the header. Unknown variables, unterminated `%[` and response-only variables in request rules are rejected. Header-rule editors show clickable variable chips, and **Backends → Backend diagnostics** gains one-click presets (`X-Served-By`, `X-Location`, `X-LB`, `X-Debug`, `X-Shard` to the backend). Rules without `%[` behave exactly as before. See [Variables in header values](docs/RESPONSE_DELIVERY.md#variables-in-header-values-diagnostic-headers). +- **Compatibility:** configurations without `conditions` or `match_type: "any"` are unchanged and serialize as before. Configurations using them, or header values with `%[variables]` (which 0.40.2 would send literally), need 0.41.0. Glob wildcards are still not supported in paths; use regular expressions (documented). +- **Verification:** new Rust tests run 19 shared routing cases from `tests/fixtures/routing_conditions_cases.json` (exact/prefix/regex/any precedence, fall-through, every source and operator, negation, country, IPv4/IPv6 CIDR), check that conditional locations are skipped without request facts and never cached, and reject 14 invalid configurations; the panel tester was checked against the same cases. Full suite, `cargo clippy --all-targets` and `cargo fmt --check` clean. The real binary was run in headless mode against four mock origins: header, IP + cookie (whole-host rule) and POST-only routing reached the expected origins; a cacheable `/api/` response was `HIT` for plain requests while `X-Beta` requests went to the beta origin with `BYPASS / route_disabled`. With header variables, `%[srv_id]` reached the origin as `X-Shard` and came back in `X-S`/`X-Debug` with the location, hash key and `MISS`; on the following `HIT` the cached response carried no earlier values and showed `-` for the backend. In panel mode (Chrome) the tester, a new whole-host rule, reordering, diagnostic presets and saving were exercised. Not tested: production traffic, HTTP/3 clients, GeoIP-based country conditions with a real database. ## 0.40.2 — Consistent-hash balancing and per-location backend groups - **New algorithms:** `hash` — consistent (weighted rendezvous) hash of a request key — and `random` (power of two random choices). The `hash` key is set in `load_balancing.hash`: `source` = `path` (default, path as received, before location rewrites), `uri` (path + query), `host`, `header`, `cookie`, `query` (one parameter) or `ip`; `name` for header/cookie/query; `path_depth` (hash only the first N directories); `ignore_case`; `balance_factor` (bounded load, 101–1000 %, like HAProxy `hash-balance-factor`); `fallback` algorithm for requests without the key (default `round_robin`). Hashing is always consistent: a failed, drained or removed member only moves its own keys, which return when it recovers; weights scale each member's share of keys. See [Load balancing](docs/LOAD_BALANCING.md). - **Location backend groups (HAProxy `use_backend` style):** a Proxy location accepts `backend_ids` (a group of Vhost backends, up to 64) and `load_balancing` (`algorithm`, `hash`, `sticky`) to balance its requests differently from the rest of the Vhost — for example `\.mp3$` → `mp3_1..3` hashed by path while `/` stays on least connections. Members are shared with the Vhost pool (health, passive ejection, drain, concurrency limits, statistics), retries stay inside the group, and backends with `pool_eligible: false` serve only the locations that list them. A location affinity cookie is named `__`; the Vhost and its locations strip each other's affinity cookies before forwarding. -- **Panel:** the Vhost **Balancing** section and a new **Backends & balancing** section per location offer the new algorithms with a one-line explanation each, *Quick setup* buttons (files by path, session cookie, tenant header, query parameter, client IP, even load), the equivalent HAProxy lines, a backend-group picker and **Test distribution** — an in-browser simulator on the unsaved draft that shows the hash key and backend per sample, the share per backend and which keys move when a backend is marked as failed. It ranks backends with the same SHA-256 rendezvous scoring as the proxy (`tools/dev/test_balance_simulator.js` checks it against the Rust reference vectors). English and Polish texts added. +- **Panel:** the Vhost **Balancing** section and a new **Backends & balancing** section per location offer the new algorithms with a one-line explanation each, *Quick setup* buttons (files by path, session cookie, tenant header, query parameter, client IP, even load), the equivalent HAProxy lines, a backend-group picker and **Test distribution** — an in-browser simulator on the unsaved draft that shows the hash key and backend per sample, the share per backend and which keys move when a backend is marked as failed. It ranks backends with the same SHA-256 rendezvous scoring as the proxy (checked against the Rust reference vectors in `tests/fixtures/balance_rendezvous_vectors.txt`). English and Polish texts added. - **Compatibility:** configurations without the new fields are unchanged and still serialize without them; `ip_hash` keeps the same client → backend mapping. Configurations using `hash`, `random`, `backend_ids` or location `load_balancing` are rejected by 0.40.1 and older. `backend_id` (pinned backend) cannot be combined with a group or location balancing. OpenAPI, Vhost/location/headless guides and the feature list updated. -- **Verification:** 14 new unit tests (key extraction for every source, validation, stability, even spread, weight shares, only-the-failed-member's-keys move, fallback, bounded load, random, unchanged `ip_hash` mapping, location group compilation with shared member state, affinity cookie stripping, invalid groups) and the Node simulator test; full suite (1043 library tests, 7 CLI tests), `cargo clippy --all-targets` and `cargo fmt --check` clean. The real binary was run in headless mode with the `.mp3` example above against four mock origins: 61 paths were spread over `mp3_1..3` and stayed stable over repeated requests, `/` stayed on `app`, a header-hashed location kept tenants stable and used round robin without the header; stopping `mp3_2` moved exactly its 27 keys (all others stayed), and after it came back every key returned to its original backend. In panel mode (Chrome) the editors, presets, simulator and failure simulation were used on a saved Vhost and a new location group was created and saved through the UI. Not tested: production traffic, HTTP/3 clients and multi-node deployments. +- **Verification:** 14 new unit tests (key extraction for every source, validation, stability, even spread, weight shares, only-the-failed-member's-keys move, fallback, bounded load, random, unchanged `ip_hash` mapping, location group compilation with shared member state, affinity cookie stripping, invalid groups); full suite (1043 library tests, 7 CLI tests), `cargo clippy --all-targets` and `cargo fmt --check` clean. The real binary was run in headless mode with the `.mp3` example above against four mock origins: 61 paths were spread over `mp3_1..3` and stayed stable over repeated requests, `/` stayed on `app`, a header-hashed location kept tenants stable and used round robin without the header; stopping `mp3_2` moved exactly its 27 keys (all others stayed), and after it came back every key returned to its original backend. In panel mode (Chrome) the editors, presets, simulator and failure simulation were used on a saved Vhost and a new location group was created and saved through the UI. Not tested: production traffic, HTTP/3 clients and multi-node deployments. ## 0.40.1 — Forced certificate renewal (panel and headless) diff --git a/docs/CUSTOM_LOCATIONS.md b/docs/CUSTOM_LOCATIONS.md index 51de880..63f9c4f 100644 --- a/docs/CUSTOM_LOCATIONS.md +++ b/docs/CUSTOM_LOCATIONS.md @@ -59,7 +59,7 @@ Example — beta testers by header, office network with a staff cookie for the w ### Routing tester -**Vhosts → Edit → Custom locations → Test routing** evaluates the unsaved draft in the browser: enter a method, URL, client IP, country and headers (cookies as a `Cookie:` header) to see which location wins, why every other location was skipped (path ✓/✗ and each condition ✓/✗), the backend or hash target and whether the cache is bypassed. Its matching logic is checked against the proxy with the shared cases in `tests/fixtures/routing_conditions_cases.json` (`tools/dev/test_routing_tester.js`). Regular expressions are run by the browser engine, which covers the common syntax; the server always validates the saved configuration. +**Vhosts → Edit → Custom locations → Test routing** evaluates the unsaved draft in the browser: enter a method, URL, client IP, country and headers (cookies as a `Cookie:` header) to see which location wins, why every other location was skipped (path ✓/✗ and each condition ✓/✗), the backend or hash target and whether the cache is bypassed. Its matching logic is checked against the proxy with the shared cases in `tests/fixtures/routing_conditions_cases.json`. Regular expressions are run by the browser engine, which covers the common syntax; the server always validates the saved configuration. ## Actions @@ -76,7 +76,7 @@ Example — beta testers by header, office network with a staff cookie for the w ## Headers, access and method rules -Each location can add request/response header operations (`set`, `append`, `remove`), reusable ACL profiles, inline IP/CIDR rules, country access and HTTP-method allow/block lists. Every applicable host and Vhost policy must still pass; a location cannot remove a higher-level denial. Transport/forwarded-identity headers are protected from unsafe overrides. Authentication, rate limits, WebSocket policy and other Vhost settings continue to apply. +Each location can add request/response header operations (`set`, `append`, `remove`; values may use variables such as `%[srv_id]` — see [Variables in header values](RESPONSE_DELIVERY.md#variables-in-header-values-diagnostic-headers)), reusable ACL profiles, inline IP/CIDR rules, country access and HTTP-method allow/block lists. Every applicable host and Vhost policy must still pass; a location cannot remove a higher-level denial. Transport/forwarded-identity headers are protected from unsafe overrides. Authentication, rate limits, WebSocket policy and other Vhost settings continue to apply. ## Internal error fallback diff --git a/docs/FEATURES.md b/docs/FEATURES.md index 16b47b1..78e3335 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -10,7 +10,7 @@ RustProxy is a single service that combines a reverse proxy, a static/PHP web se |---|---| | Vhosts | Exact and wildcard hostnames, aliases, several listeners per Vhost, per-Vhost HTTP/2 and HTTP/3 switches | | Backends | HTTP and HTTPS origins, HTTP/1.1, automatic ALPN (H2/H1), strict HTTP/2 and H2C, optional upstream certificate verification with custom CA and server name | -| Load balancing | Least connections (default), round robin, least traffic, adaptive, random (two choices), consistent hash of path / URI / host / header / cookie / query parameter / client IP with optional bounded load, and IP hash; member weights, backup and draining members, sticky cookie or IP affinity; per-location backend groups with their own algorithm (HAProxy `use_backend` style); in-panel distribution simulator. Conditional routing: locations and whole-host rules selected by header, cookie, query parameter, method, client IP/CIDR, host or country (AND of conditions, negation, regex), with an in-panel routing tester. See [Load balancing](LOAD_BALANCING.md) | +| Load balancing | Least connections (default), round robin, least traffic, adaptive, random (two choices), consistent hash of path / URI / host / header / cookie / query parameter / client IP with optional bounded load, and IP hash; member weights, backup and draining members, sticky cookie or IP affinity; per-location backend groups with their own algorithm (HAProxy `use_backend` style); in-panel distribution simulator. Conditional routing: locations and whole-host rules selected by header, cookie, query parameter, method, client IP/CIDR, host or country (AND of conditions, negation, regex), with an in-panel routing tester. Header rules accept HAProxy-style variables (`%[srv_id]`, `%[location]`, `%[hash_key]`, `%[cache_status]`, …) with one-click diagnostic header presets. See [Load balancing](LOAD_BALANCING.md) | | Health checks | Active TCP or HTTP probes with thresholds, optional separate probe port, expected response text and live health status per member | | Connection reuse | Bounded keep-alive pools with idle and age limits, pool recycling and protocol telemetry | | Custom locations | Prefix, exact and regex paths, path rewriting, per-location backends, Web Services, local responses, redirects and internal error fallbacks | diff --git a/docs/LOAD_BALANCING.md b/docs/LOAD_BALANCING.md index e940402..af6c6df 100644 --- a/docs/LOAD_BALANCING.md +++ b/docs/LOAD_BALANCING.md @@ -121,11 +121,13 @@ In the panel: add the three backends with **Include in the default load-balancin Locations can additionally require request conditions (header, cookie, query parameter, method, client IP, host, country), and a match type `any` turns a location into a rule for the whole host — together the full HAProxy `use_backend if ` pattern. See [Custom locations → Request conditions](CUSTOM_LOCATIONS.md#request-conditions-routing-by-header-cookie-ip). +To see which shard served a request, add a response header rule such as `X-S: %[srv_id]` or `X-LB: %[lb_algorithm] %[hash_key]` (one click under **Backends → Backend diagnostics**); see [Variables in header values](RESPONSE_DELIVERY.md#variables-in-header-values-diagnostic-headers). + ## Panel helpers - **Quick setup** buttons fill typical combinations: files by path, session cookie, tenant header, query parameter, client IP, or even load spreading. - Each algorithm shows a short explanation, and hash settings show the **HAProxy equivalent** lines for comparison. -- **Test distribution** runs in the browser on the unsaved draft. Paste sample paths, URLs or key values to see the hash key and the selected backend for each, the share per backend, and — after ticking **Simulate failure of** — which keys would move. The simulator uses the same SHA-256 rendezvous scoring as the proxy (checked by `tools/dev/test_balance_simulator.js`); load-based algorithms show the expected share by weight instead. It does not account for current concurrency limits, bounded-load spill-over or live health. +- **Test distribution** runs in the browser on the unsaved draft. Paste sample paths, URLs or key values to see the hash key and the selected backend for each, the share per backend, and — after ticking **Simulate failure of** — which keys would move. The simulator uses the same SHA-256 rendezvous scoring as the proxy (reference vectors in `tests/fixtures/balance_rendezvous_vectors.txt`); load-based algorithms show the expected share by weight instead. It does not account for current concurrency limits, bounded-load spill-over or live health. ## Compatibility and limits diff --git a/docs/RESPONSE_DELIVERY.md b/docs/RESPONSE_DELIVERY.md index 2d5d68f..ea32e29 100644 --- a/docs/RESPONSE_DELIVERY.md +++ b/docs/RESPONSE_DELIVERY.md @@ -37,6 +37,44 @@ Transformations can run on eligible reverse-proxy and Web Server responses. When Configure global response headers, Vhost-specific policies and Web Server/location headers at the appropriate scope. Header rules can set, append or remove allowed names. Certain routing, forwarding, framing, cache diagnostics and security-sensitive fields are protected or subject to extra validation. Review especially HSTS, CSP, CORS and application-specific cookies before using a broad rule. +### Variables in header values (diagnostic headers) + +Since 0.41.0 a `set`/`append` value can contain variables written as `%[name]`, like HAProxy sample fetches (`http-response set-header X-S %[srv_id]`). They work in global, Vhost and location rules, for both directions: + +| Variable | Value | +|---|---| +| `%[srv_id]` | ID of the backend that served the request (e.g. `mp3_2`); `-` on a cache hit, when no backend was contacted | +| `%[srv_url]` | URL of that backend | +| `%[location]` | custom location ID, or `main` for the Vhost source | +| `%[vhost]` | Vhost ID | +| `%[lb_algorithm]` | balancing algorithm used (`hash`, `least_connections`, …) | +| `%[hash_key]` | key of consistent hashing (path, header value, client IP…) | +| `%[client_ip]` | client address as determined by RustProxy | +| `%[country]` | client country when GeoIP or Cloudflare provides it | +| `%[req_id]` | request ID | +| `%[method]`, `%[host]`, `%[path]` | request method, host name and routing path | +| `%[cache_status]` | `HIT`, `MISS` or `BYPASS` — response rules only | +| `%[backend_time]` | backend response time, e.g. `12.40ms` — response rules only | + +Example — show the shard in the response and tell the backend which shard it is: + +```json +"headers": { + "request": [{ "op": "set", "name": "X-Shard", "value": "%[srv_id]" }], + "response": [{ "op": "set", "name": "X-S", "value": "%[srv_id]" }, + { "op": "set", "name": "X-Debug", "value": "%[location] -> %[srv_id] (%[cache_status], %[hash_key])" }] +} +``` + +Rules: + +- Rules with variables are evaluated **per request and applied last** in their direction: request rules after the backend is selected (on a failover retry the request keeps the first backend's value; the response shows the final backend), response rules at final delivery after cache handling. They are **never stored in the cache**, so a cached object never carries another client's values. Static rules behave as before. +- A variable without a value for the request renders as `-`. If the rendered value is not a valid header value the header is skipped (CR/LF can never be injected). +- Unknown variables, an unterminated `%[` and `%[cache_status]` / `%[backend_time]` in request rules are rejected when saving. Protected header names stay protected. +- Values such as `%[path]`, `%[host]` and `%[hash_key]` echo client input, and `%[srv_id]` / `%[srv_url]` reveal internal names — use diagnostic headers for testing or restrict them to trusted locations. + +In the panel the header-rule editors show clickable variable chips, and **Vhost → Backends → Backend diagnostics** has one-click presets (`X-Served-By`, `X-Location`, `X-LB`, `X-Debug`, `X-Shard` to the backend) that add the corresponding rules to the Vhost's header rules. The existing switch *Expose selected backend* (`X-Rust-Proxy-Backend`) is unchanged. + For controlled rollout: 1. Enable only the codec/types required, then test with and without `Accept-Encoding` and with ordinary browsers. diff --git a/langs/en_US.json b/langs/en_US.json index ebd8abe..1a4e0ed 100644 --- a/langs/en_US.json +++ b/langs/en_US.json @@ -1469,7 +1469,7 @@ "locationDocsAccess": "Per-location IP ACL, cache override and request/response header rules are composed with the vhost policy. A location cannot disable host authentication or host ACL.", "locationDocsLimits": "Up to 64 locations per vhost. Regexes and response bodies are bounded; transport, forwarding identity and WebSocket protocol headers remain system-managed.", "headersDocsIntro": "Header rules are applied in order: global → vhost → matching location. Use the visual configurator for normal changes; JSON remains an advanced escape hatch.", - "headersDocsSet": "Set: replace all existing values of a header with the configured literal value.", + "headersDocsSet": "Set: replace all existing values of a header with the configured literal value. Variables such as %[srv_id] are expanded per request.", "headersDocsAppend": "Append: add another value without deleting existing values.", "headersDocsRemove": "Remove: delete the header before forwarding or before sending the response.", "headersDocsProtected": "Protected transport/identity headers (Host, Connection, Content-Length, Forwarded/X-Forwarded-*, WebSocket proof headers and similar) cannot be overridden here.", @@ -4014,6 +4014,31 @@ "rtPathColumn": "Path", "rtConditionsColumn": "Conditions", "rtBrowserRegex": "the browser cannot evaluate this expression", - "rtTesterHelp": "The test runs in the browser on the unsaved draft. Regular expressions are evaluated with the browser engine, which supports the same common syntax as RustProxy; the saved configuration is always validated by the server." + "rtTesterHelp": "The test runs in the browser on the unsaved draft. Regular expressions are evaluated with the browser engine, which supports the same common syntax as RustProxy; the saved configuration is always validated by the server.", + "hdrVariables": "Variables:", + "hdrVariablesHelp": "Header values can contain variables such as %[srv_id] (HAProxy-style). Rules with variables are applied last and per request: request rules after the backend is selected, response rules at final delivery — never stored in the cache. A value that is unknown for a request becomes “-”; cache_status and backend_time are available only in response rules.", + "hdrVar_srv_id": "ID of the backend that served the request (“-” on a cache hit, when no backend was contacted)", + "hdrVar_srv_url": "Backend URL (not available on a cache hit)", + "hdrVar_location": "Custom location ID, or “main” for the vhost source", + "hdrVar_vhost": "Vhost ID", + "hdrVar_lb_algorithm": "Balancing algorithm used, e.g. hash or least_connections", + "hdrVar_hash_key": "Key of consistent hashing (path, header value…)", + "hdrVar_client_ip": "Client IP address as seen by RustProxy", + "hdrVar_country": "Client country (when GeoIP or Cloudflare provides it)", + "hdrVar_req_id": "Request ID", + "hdrVar_method": "HTTP method", + "hdrVar_host": "Requested host name", + "hdrVar_path": "Request path", + "hdrVar_cache_status": "HIT, MISS or BYPASS (response rules only)", + "hdrVar_backend_time": "Backend response time, e.g. 12.40ms (response rules only)", + "hdrPresets": "Add diagnostic header:", + "hdrPresetServedBy": "X-Served-By: backend", + "hdrPresetLocation": "X-Location: location", + "hdrPresetBalance": "X-LB: algorithm + key", + "hdrPresetDebug": "X-Debug: full path", + "hdrPresetUpstream": "X-Shard to backend", + "hdrPresetAdded": "Header rule {name} added (Security → header rules).", + "hdrPresetExists": "A rule for {name} already exists.", + "hdrPresetsHelp": "Adds a header rule with variables to this vhost (edit or remove it under Security → header rules). Like “http-response set-header X-S %[srv_id]” in HAProxy. Diagnostic headers reveal internal names; keep them for testing or remove them in production." } } diff --git a/langs/pl_pl.json b/langs/pl_pl.json index 49260fe..b40ecd5 100644 --- a/langs/pl_pl.json +++ b/langs/pl_pl.json @@ -1469,7 +1469,7 @@ "locationDocsAccess": "ACL IP lokalizacji, nadpisanie cache i reguły nagłówków są łączone z polityką vhosta. Lokalizacja nie może wyłączyć autentykacji ani ACL hosta.", "locationDocsLimits": "Do 64 lokalizacji na vhost. Regexy i body odpowiedzi mają limity; nagłówki transportu, zweryfikowanej tożsamości i protokołu WebSocket pozostają zarządzane przez system.", "headersDocsIntro": "Reguły nagłówków są stosowane kolejno: globalne → vhost → pasująca lokalizacja. Do zwykłej konfiguracji użyj graficznego konfiguratora; JSON pozostaje trybem zaawansowanym.", - "headersDocsSet": "Ustaw: zastępuje wszystkie istniejące wartości nagłówka skonfigurowaną wartością dosłowną.", + "headersDocsSet": "Ustaw: zastępuje wszystkie istniejące wartości nagłówka skonfigurowaną wartością dosłowną. Zmienne takie jak %[srv_id] są podstawiane dla każdego żądania.", "headersDocsAppend": "Dopisz: dodaje kolejną wartość bez usuwania istniejących.", "headersDocsRemove": "Usuń: kasuje nagłówek przed wysłaniem do backendu albo klienta.", "headersDocsProtected": "Chronionych nagłówków transportu/tożsamości (Host, Connection, Content-Length, Forwarded/X-Forwarded-*, nagłówki dowodu WebSocket itd.) nie można tu nadpisywać.", @@ -4014,6 +4014,31 @@ "rtPathColumn": "Ścieżka", "rtConditionsColumn": "Warunki", "rtBrowserRegex": "przeglądarka nie potrafi obliczyć tego wyrażenia", - "rtTesterHelp": "Test działa w przeglądarce na niezapisanym szkicu. Wyrażenia regularne liczy silnik przeglądarki, który obsługuje tę samą typową składnię co RustProxy; zapisaną konfigurację zawsze sprawdza serwer." + "rtTesterHelp": "Test działa w przeglądarce na niezapisanym szkicu. Wyrażenia regularne liczy silnik przeglądarki, który obsługuje tę samą typową składnię co RustProxy; zapisaną konfigurację zawsze sprawdza serwer.", + "hdrVariables": "Zmienne:", + "hdrVariablesHelp": "Wartości nagłówków mogą zawierać zmienne, np. %[srv_id] (jak w HAProxy). Reguły ze zmiennymi są stosowane na końcu i dla każdego żądania osobno: reguły żądania po wyborze backendu, reguły odpowiedzi przy wysyłce do klienta — nigdy nie trafiają do cache. Wartość nieznana dla danego żądania to „-”; cache_status i backend_time są dostępne tylko w regułach odpowiedzi.", + "hdrVar_srv_id": "ID backendu, który obsłużył żądanie („-” przy trafieniu w cache, gdy żaden backend nie był pytany)", + "hdrVar_srv_url": "Adres backendu (niedostępny przy trafieniu w cache)", + "hdrVar_location": "ID własnej lokalizacji albo „main” dla źródła vhosta", + "hdrVar_vhost": "ID vhosta", + "hdrVar_lb_algorithm": "Użyty algorytm balansowania, np. hash lub least_connections", + "hdrVar_hash_key": "Klucz spójnego haszowania (ścieżka, wartość nagłówka…)", + "hdrVar_client_ip": "Adres IP klienta widziany przez RustProxy", + "hdrVar_country": "Kraj klienta (gdy dostarcza go GeoIP lub Cloudflare)", + "hdrVar_req_id": "Identyfikator żądania", + "hdrVar_method": "Metoda HTTP", + "hdrVar_host": "Żądana nazwa hosta", + "hdrVar_path": "Ścieżka żądania", + "hdrVar_cache_status": "HIT, MISS lub BYPASS (tylko reguły odpowiedzi)", + "hdrVar_backend_time": "Czas odpowiedzi backendu, np. 12.40ms (tylko reguły odpowiedzi)", + "hdrPresets": "Dodaj nagłówek diagnostyczny:", + "hdrPresetServedBy": "X-Served-By: backend", + "hdrPresetLocation": "X-Location: lokalizacja", + "hdrPresetBalance": "X-LB: algorytm + klucz", + "hdrPresetDebug": "X-Debug: pełna ścieżka", + "hdrPresetUpstream": "X-Shard do backendu", + "hdrPresetAdded": "Dodano regułę nagłówka {name} (zakładka Bezpieczeństwo → Reguły nagłówków).", + "hdrPresetExists": "Reguła dla {name} już istnieje.", + "hdrPresetsHelp": "Dodaje do vhosta regułę nagłówka ze zmiennymi (edytujesz lub usuwasz ją w zakładce Bezpieczeństwo → Reguły nagłówków). Jak „http-response set-header X-S %[srv_id]” w HAProxy. Nagłówki diagnostyczne ujawniają wewnętrzne nazwy; używaj ich do testów albo usuń na produkcji." } } diff --git a/src/admin/openapi.json b/src/admin/openapi.json index a596f0b..ec9c82e 100644 --- a/src/admin/openapi.json +++ b/src/admin/openapi.json @@ -212,7 +212,7 @@ "value": { "type": "string", "maxLength": 8192, - "description": "Required for set/append; omit for remove. Literal, no variable substitution." + "description": "Value for set/append. May contain variables `%[name]`: srv_id, srv_url, location, vhost, lb_algorithm, hash_key, client_ip, country, req_id, method, host, path, and in response rules also cache_status and backend_time. Rules with variables are applied per request, last in their direction, and never cached; a missing value renders as `-`." } }, "additionalProperties": false, diff --git a/src/admin/web/css/40-editors.css b/src/admin/web/css/40-editors.css index 46ef430..b5dd07c 100644 --- a/src/admin/web/css/40-editors.css +++ b/src/admin/web/css/40-editors.css @@ -2430,3 +2430,25 @@ h2+.fine { font-family: var(--mono); font-size: 11px; } + +/* Header value variables and diagnostic header presets. */ +.hdr-vars, +.hdr-presets { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 4px 6px; + margin-top: 6px; +} + +.hdr-vars-label { + color: var(--muted); + font: 600 10px var(--mono); + letter-spacing: .35px; +} + +.hdr-var { + border-radius: 999px; + padding: 2px 8px; + font: 11px var(--mono); +} diff --git a/src/admin/web/vhosts/balancing.js b/src/admin/web/vhosts/balancing.js index 27622bd..87ddf8b 100644 --- a/src/admin/web/vhosts/balancing.js +++ b/src/admin/web/vhosts/balancing.js @@ -1,6 +1,6 @@ // Load-balancing editor (vhost and location) with a consistent-hash distribution // simulator. The pure helpers at the top mirror src/balance/model.rs (rendezvous -// scoring and hash keys) and are checked by tools/dev/test_balance_simulator.js. +// scoring and hash keys); keep them in step with tests/fixtures/balance_rendezvous_vectors.txt. const lbSha256 = (() => { const K = new Uint32Array([ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, diff --git a/src/admin/web/vhosts/core.js b/src/admin/web/vhosts/core.js index 8f737e2..e54976f 100644 --- a/src/admin/web/vhosts/core.js +++ b/src/admin/web/vhosts/core.js @@ -1,6 +1,6 @@ "use strict"; let vhostCacheRulesEditor = null; -let basicEditor = null, locationsReader = () => [], aclControl = null, editing = null, revision = null, dirty = false, initialized = false, readBindings = () => [], readHosts = () => [], countryRatesReader = () => [], uaRatesReader = () => [], pagesEditor = null, stagedCertificates = [], uploading = false, draftEpoch = 0, backendHealthEditorControl = null, vhostBalancingControl = null; +let basicEditor = null, locationsReader = () => [], aclControl = null, editing = null, revision = null, dirty = false, initialized = false, readBindings = () => [], readHosts = () => [], countryRatesReader = () => [], uaRatesReader = () => [], pagesEditor = null, stagedCertificates = [], uploading = false, draftEpoch = 0, backendHealthEditorControl = null, vhostBalancingControl = null, vhostHeadersControl = null; const chartHistory = new Map(); const backendTrafficHistory = new Map(); const backendRequestHistory = new Map(); @@ -87,6 +87,15 @@ function validateHeaders(value) { } } return value; } +// Header value variables (src/headers/mod.rs Var::ALL); true = response rules only. +const HEADER_VARIABLES = [["srv_id", false], ["srv_url", false], ["location", false], ["vhost", false], ["lb_algorithm", false], ["hash_key", false], ["client_ip", false], ["country", false], ["req_id", false], ["method", false], ["host", false], ["path", false], ["cache_status", true], ["backend_time", true]]; +const DIAGNOSTIC_PRESETS = [ + { key: "hdrPresetServedBy", direction: "response", rule: { op: "set", name: "X-Served-By", value: "%[srv_id]" } }, + { key: "hdrPresetLocation", direction: "response", rule: { op: "set", name: "X-Location", value: "%[location]" } }, + { key: "hdrPresetBalance", direction: "response", rule: { op: "set", name: "X-LB", value: "%[lb_algorithm] %[hash_key]" } }, + { key: "hdrPresetDebug", direction: "response", rule: { op: "set", name: "X-Debug", value: "%[vhost]/%[location] -> %[srv_id] (%[cache_status], %[backend_time])" } }, + { key: "hdrPresetUpstream", direction: "request", rule: { op: "set", name: "X-Shard", value: "%[srv_id]" } } +]; function headerEditors(parent, initial, target = read("headers"), onChange = changed) { const holders = {}, adders = {}, emptyStates = {}; const renumber = direction => { @@ -127,6 +136,20 @@ function headerEditors(parent, initial, target = read("headers"), onChange = cha }; adders[direction] = add; for (const rule of initial[direction] || []) add(rule); renumber(direction); block.append(button("addHeader", () => { add(); sync(); }, "quiet location-add-header")); + // %[variable] chips insert into the last focused value field of this direction. + const chips = el("div", undefined, "hdr-vars"); chips.append(text("span", "hdrVariables", "hdr-vars-label")); + let lastValue = null; rows.addEventListener("focusin", event => { if (event.target.name === "rule-value") lastValue = event.target; }); + for (const [name, responseOnly] of HEADER_VARIABLES) { + if (responseOnly && direction === "request") continue; + const chip = button("hdrVariables", () => { + let target = lastValue?.isConnected && !lastValue.disabled ? lastValue : [...rows.querySelectorAll('[name="rule-value"]:not(:disabled)')].pop(); + if (!target) { add({ op: "set", name: "", value: "" }); target = [...rows.querySelectorAll('[name="rule-value"]')].pop(); } + const token = `%[${name}]`, at = target.selectionStart ?? target.value.length; + target.value = target.value.slice(0, at) + token + target.value.slice(target.selectionEnd ?? at); target.focus(); target.setSelectionRange(at + token.length, at + token.length); lastValue = target; sync(); + }, "quiet hdr-var"); + delete chip.dataset.i18n; chip.textContent = `%[${name}]`; chip.title = t(`hdrVar_${name}`); chips.append(chip); + } + block.append(chips); } target.addEventListener("input", () => { try { @@ -139,8 +162,8 @@ function headerEditors(parent, initial, target = read("headers"), onChange = cha target.setCustomValidity(""); onChange(); } catch (error) { target.setCustomValidity(error.message || t("headersInvalid")); } }); - note(parent, "locationHeadersHelp"); - return { read: () => validateHeaders(JSON.parse(target.value)) }; + note(parent, "locationHeadersHelp"); note(parent, "hdrVariablesHelp"); + return { read: () => validateHeaders(JSON.parse(target.value)), add: (direction, rule) => { adders[direction](rule); renumber(direction); sync(); } }; } function suspendDraft() { const state = { diff --git a/src/admin/web/vhosts/editor.js b/src/admin/web/vhosts/editor.js index 59bf667..05fa70f 100644 --- a/src/admin/web/vhosts/editor.js +++ b/src/admin/web/vhosts/editor.js @@ -211,6 +211,14 @@ function load(value = defaults(), migrationIds = [], show = true) { field(g, "backend-header", "vhBackendHeader", value.backend_header === true, "checkbox", { switch: true }); field(g, "backend-timing-header", "vhBackendTimingHeader", value.backend_timing_header === true, "checkbox", { switch: true }); note(g, "vhBackendDiagnosticsHelp"); + const diagnosticPresets = el("div", undefined, "vh-wide hdr-presets"); diagnosticPresets.append(text("span", "hdrPresets", "hdr-vars-label")); + for (const preset of DIAGNOSTIC_PRESETS) diagnosticPresets.append(button(preset.key, () => { + if (!vhostHeadersControl) return; + const current = vhostHeadersControl.read()[preset.direction] || []; + if (current.some(rule => rule.name.toLowerCase() === preset.rule.name.toLowerCase())) { toast(t("hdrPresetExists").replace("{name}", preset.rule.name)); return; } + vhostHeadersControl.add(preset.direction, { ...preset.rule }); toast(t("hdrPresetAdded").replace("{name}", preset.rule.name)); + }, "quiet lb-preset")); + g.append(diagnosticPresets); note(g, "hdrPresetsHelp"); const proxyTimeouts = { ...defaultProxyTimeouts(), ...(value.proxy_timeouts || {}) }; g = group("vhProxyTimeouts"); field(g, "proxy-connect-timeout", "vhProxyConnectTimeout", proxyTimeouts.connect_timeout_seconds ?? 10, "number", { required: true, min: 1, max: 300 }); @@ -561,7 +569,7 @@ function load(value = defaults(), migrationIds = [], show = true) { }; transformEnabled.addEventListener("change", syncTransform); customTransformExtensions.addEventListener("change", syncTransform); syncTransform(); note(transformOptions, "vhTransformHelp"); - g = group("vhHeaders"); headerEditors(g, value.headers || {}); + g = group("vhHeaders"); vhostHeadersControl = headerEditors(g, value.headers || {}); g = group("vhPages"); g.classList.add("vh-pages-grid"); pagesEditor = window.rustProxyPages.vhostEditor(g, value.pages || {}); initTabs(); dirty = false; if (latestStatus) renderStatus(latestStatus); if (show && !dialog.open) dialog.showModal(); diff --git a/src/admin/web/vhosts/routing.js b/src/admin/web/vhosts/routing.js index 26f8855..fbf0b7f 100644 --- a/src/admin/web/vhosts/routing.js +++ b/src/admin/web/vhosts/routing.js @@ -1,6 +1,6 @@ // Location conditions editor and the routing tester. The pure helpers mirror // src/config/snapshot.rs (select_route) and src/vhost/conditions.rs and are checked -// against tests/fixtures/routing_conditions_cases.json by tools/dev/test_routing_tester.js. +// against the cases in tests/fixtures/routing_conditions_cases.json. const RT_SOURCES = [["header", "rtSourceHeader"], ["cookie", "rtSourceCookie"], ["query", "rtSourceQuery"], ["method", "rtSourceMethod"], ["ip", "rtSourceIp"], ["host", "rtSourceHost"], ["country", "rtSourceCountry"]]; const RT_OPERATORS = [["equals", "rtOpEquals"], ["exists", "rtOpExists"], ["prefix", "rtOpPrefix"], ["suffix", "rtOpSuffix"], ["contains", "rtOpContains"], ["regex", "rtOpRegex"], ["cidr", "rtOpCidr"]]; function rtOperatorsFor(source) { diff --git a/src/balance/hash_tests.rs b/src/balance/hash_tests.rs index 528ab2b..c309a5d 100644 --- a/src/balance/hash_tests.rs +++ b/src/balance/hash_tests.rs @@ -279,8 +279,8 @@ mod hash_tests { assert_eq!(selection.lease.member.definition.id, expected); } - /// Reference values shared with `tools/dev/test_balance_simulator.js` (fixture `tests/fixtures/balance_rendezvous_vectors.txt`), which checks - /// that the panel simulator ranks members exactly like the proxy. + /// Reference values (tests/fixtures/balance_rendezvous_vectors.txt); the panel + /// simulator in balancing.js must rank members the same way. #[test] fn rendezvous_reference_vectors() { let order = |key: &str| { diff --git a/src/balance/pool_core.rs b/src/balance/pool_core.rs index d278774..ac35951 100644 --- a/src/balance/pool_core.rs +++ b/src/balance/pool_core.rs @@ -183,6 +183,36 @@ impl Pool { pub fn ready(&self) -> bool { !self.eligible_healthy_excluding(&[]).is_empty() } + /// Hash key the pool uses for this request (consistent `hash` or `ip_hash`), for + /// the `%[hash_key]` header variable. + pub fn balance_key( + &self, + peer: IpAddr, + headers: &HeaderMap, + uri: Option<&http::Uri>, + ) -> Option { + match self.plan(peer, headers, uri) { + (Algorithm::Hash | Algorithm::IpHash, key) => key, + _ => None, + } + } + /// Effective algorithm name (`ip_hash` sticky mode reports `ip_hash`). + pub fn algorithm_name(&self) -> &'static str { + let algorithm = if self.settings.sticky.mode == StickyMode::IpHash { + Algorithm::IpHash + } else { + self.settings.algorithm + }; + match algorithm { + Algorithm::RoundRobin => "round_robin", + Algorithm::LeastConnections => "least_connections", + Algorithm::LeastTraffic => "least_traffic", + Algorithm::Adaptive => "adaptive", + Algorithm::IpHash => "ip_hash", + Algorithm::Hash => "hash", + Algorithm::Random => "random", + } + } /// True when selection reads the request URI (path, URI, host or query hashing). pub fn hashes_request_uri(&self) -> bool { self.settings.algorithm == Algorithm::Hash diff --git a/src/config/routing_conditions_tests.rs b/src/config/routing_conditions_tests.rs index d3b5179..6fcc5d8 100644 --- a/src/config/routing_conditions_tests.rs +++ b/src/config/routing_conditions_tests.rs @@ -21,7 +21,7 @@ mod routing_conditions_tests { compile(cfg, 0, &policy()) } - /// Shared with tools/dev/test_routing_tester.js (panel tester parity). + /// The panel routing tester (routing.js) must agree with these cases. #[test] fn fixture_cases_select_the_expected_location() { let fixture: serde_json::Value = serde_json::from_str(FIXTURE).unwrap(); diff --git a/src/headers/mod.rs b/src/headers/mod.rs index d18feca..667b6b6 100644 --- a/src/headers/mod.rs +++ b/src/headers/mod.rs @@ -30,13 +30,190 @@ pub struct CompiledRule { op: Operation, name: HeaderName, value: Option, + /// Value with `%[variable]` placeholders, rendered per request. + template: Option