This commit is contained in:
Mateusz Gruszczyński committed 2026-11-23 12:23:41 +01:00
1 parent 54b2ac0838
commit 3b953dcdc6
23 files changed
+643 -29

No files matched your search

+5 -4
View File
@@ -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. - **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. - **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. - **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). - **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).
- **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. - **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 ## 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). - **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 `<vhost cookie>__<location>`; the Vhost and its locations strip each other's affinity cookies before forwarding. - **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 `<vhost cookie>__<location>`; 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. - **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) ## 0.40.1 — Forced certificate renewal (panel and headless)
+2 -2
View File
@@ -59,7 +59,7 @@ Example — beta testers by header, office network with a staff cookie for the w
### Routing tester ### 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 ## Actions
@@ -76,7 +76,7 @@ Example — beta testers by header, office network with a staff cookie for the w
## Headers, access and method rules ## 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 ## Internal error fallback
+1 -1
View File
@@ -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 | | 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 | | 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 | | 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 | | 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 | | Custom locations | Prefix, exact and regex paths, path rewriting, per-location backends, Web Services, local responses, redirects and internal error fallbacks |
+3 -1
View File
@@ -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 <group> if <acls>` pattern. See [Custom locations → Request conditions](CUSTOM_LOCATIONS.md#request-conditions-routing-by-header-cookie-ip). 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 <group> if <acls>` 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 ## Panel helpers
- **Quick setup** buttons fill typical combinations: files by path, session cookie, tenant header, query parameter, client IP, or even load spreading. - **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. - 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 ## Compatibility and limits
+38
View File
@@ -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. 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: For controlled rollout:
1. Enable only the codec/types required, then test with and without `Accept-Encoding` and with ordinary browsers. 1. Enable only the codec/types required, then test with and without `Accept-Encoding` and with ordinary browsers.
+27 -2
View File
@@ -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.", "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.", "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.", "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.", "headersDocsAppend": "Append: add another value without deleting existing values.",
"headersDocsRemove": "Remove: delete the header before forwarding or before sending the response.", "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.", "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", "rtPathColumn": "Path",
"rtConditionsColumn": "Conditions", "rtConditionsColumn": "Conditions",
"rtBrowserRegex": "the browser cannot evaluate this expression", "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."
} }
} }
+27 -2
View File
@@ -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.", "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.", "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.", "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.", "headersDocsAppend": "Dopisz: dodaje kolejną wartość bez usuwania istniejących.",
"headersDocsRemove": "Usuń: kasuje nagłówek przed wysłaniem do backendu albo klienta.", "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ć.", "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", "rtPathColumn": "Ścieżka",
"rtConditionsColumn": "Warunki", "rtConditionsColumn": "Warunki",
"rtBrowserRegex": "przeglądarka nie potrafi obliczyć tego wyrażenia", "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."
} }
} }
+1 -1
View File
@@ -212,7 +212,7 @@
"value": { "value": {
"type": "string", "type": "string",
"maxLength": 8192, "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, "additionalProperties": false,
+22
View File
@@ -2430,3 +2430,25 @@ h2+.fine {
font-family: var(--mono); font-family: var(--mono);
font-size: 11px; 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);
}
+1 -1
View File
@@ -1,6 +1,6 @@
// Load-balancing editor (vhost and location) with a consistent-hash distribution // Load-balancing editor (vhost and location) with a consistent-hash distribution
// simulator. The pure helpers at the top mirror src/balance/model.rs (rendezvous // 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 lbSha256 = (() => {
const K = new Uint32Array([ const K = new Uint32Array([
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
+26 -3
View File
@@ -1,6 +1,6 @@
"use strict"; "use strict";
let vhostCacheRulesEditor = null; 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 chartHistory = new Map();
const backendTrafficHistory = new Map(); const backendTrafficHistory = new Map();
const backendRequestHistory = new Map(); const backendRequestHistory = new Map();
@@ -87,6 +87,15 @@ function validateHeaders(value) {
} }
} return 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) { function headerEditors(parent, initial, target = read("headers"), onChange = changed) {
const holders = {}, adders = {}, emptyStates = {}; const holders = {}, adders = {}, emptyStates = {};
const renumber = direction => { 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); adders[direction] = add; for (const rule of initial[direction] || []) add(rule); renumber(direction);
block.append(button("addHeader", () => { add(); sync(); }, "quiet location-add-header")); 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", () => { target.addEventListener("input", () => {
try { try {
@@ -139,8 +162,8 @@ function headerEditors(parent, initial, target = read("headers"), onChange = cha
target.setCustomValidity(""); onChange(); target.setCustomValidity(""); onChange();
} catch (error) { target.setCustomValidity(error.message || t("headersInvalid")); } } catch (error) { target.setCustomValidity(error.message || t("headersInvalid")); }
}); });
note(parent, "locationHeadersHelp"); note(parent, "locationHeadersHelp"); note(parent, "hdrVariablesHelp");
return { read: () => validateHeaders(JSON.parse(target.value)) }; return { read: () => validateHeaders(JSON.parse(target.value)), add: (direction, rule) => { adders[direction](rule); renumber(direction); sync(); } };
} }
function suspendDraft() { function suspendDraft() {
const state = { const state = {
+9 -1
View File
@@ -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-header", "vhBackendHeader", value.backend_header === true, "checkbox", { switch: true });
field(g, "backend-timing-header", "vhBackendTimingHeader", value.backend_timing_header === true, "checkbox", { switch: true }); field(g, "backend-timing-header", "vhBackendTimingHeader", value.backend_timing_header === true, "checkbox", { switch: true });
note(g, "vhBackendDiagnosticsHelp"); 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 || {}) }; const proxyTimeouts = { ...defaultProxyTimeouts(), ...(value.proxy_timeouts || {}) };
g = group("vhProxyTimeouts"); g = group("vhProxyTimeouts");
field(g, "proxy-connect-timeout", "vhProxyConnectTimeout", proxyTimeouts.connect_timeout_seconds ?? 10, "number", { required: true, min: 1, max: 300 }); 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(); transformEnabled.addEventListener("change", syncTransform); customTransformExtensions.addEventListener("change", syncTransform); syncTransform();
note(transformOptions, "vhTransformHelp"); 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 || {}); 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(); initTabs(); dirty = false; if (latestStatus) renderStatus(latestStatus); if (show && !dialog.open) dialog.showModal();
+1 -1
View File
@@ -1,6 +1,6 @@
// Location conditions editor and the routing tester. The pure helpers mirror // 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 // 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_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"]]; const RT_OPERATORS = [["equals", "rtOpEquals"], ["exists", "rtOpExists"], ["prefix", "rtOpPrefix"], ["suffix", "rtOpSuffix"], ["contains", "rtOpContains"], ["regex", "rtOpRegex"], ["cidr", "rtOpCidr"]];
function rtOperatorsFor(source) { function rtOperatorsFor(source) {
+2 -2
View File
@@ -279,8 +279,8 @@ mod hash_tests {
assert_eq!(selection.lease.member.definition.id, expected); 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 /// Reference values (tests/fixtures/balance_rendezvous_vectors.txt); the panel
/// that the panel simulator ranks members exactly like the proxy. /// simulator in balancing.js must rank members the same way.
#[test] #[test]
fn rendezvous_reference_vectors() { fn rendezvous_reference_vectors() {
let order = |key: &str| { let order = |key: &str| {
+30
View File
@@ -183,6 +183,36 @@ impl Pool {
pub fn ready(&self) -> bool { pub fn ready(&self) -> bool {
!self.eligible_healthy_excluding(&[]).is_empty() !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<String> {
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). /// True when selection reads the request URI (path, URI, host or query hashing).
pub fn hashes_request_uri(&self) -> bool { pub fn hashes_request_uri(&self) -> bool {
self.settings.algorithm == Algorithm::Hash self.settings.algorithm == Algorithm::Hash
+1 -1
View File
@@ -21,7 +21,7 @@ mod routing_conditions_tests {
compile(cfg, 0, &policy()) 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] #[test]
fn fixture_cases_select_the_expected_location() { fn fixture_cases_select_the_expected_location() {
let fixture: serde_json::Value = serde_json::from_str(FIXTURE).unwrap(); let fixture: serde_json::Value = serde_json::from_str(FIXTURE).unwrap();
+248 -6
View File
@@ -30,13 +30,190 @@ pub struct CompiledRule {
op: Operation, op: Operation,
name: HeaderName, name: HeaderName,
value: Option<HeaderValue>, value: Option<HeaderValue>,
/// Value with `%[variable]` placeholders, rendered per request.
template: Option<Template>,
/// Applied only on the wire (final delivery): `Age` and every response rule with
/// variables, so per-request values are never stored in the cache.
wire_only: bool, wire_only: bool,
} }
/// Variables available in header values as `%[name]` (HAProxy-style sample fetches).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Var {
SrvId,
SrvUrl,
Location,
Vhost,
LbAlgorithm,
HashKey,
ClientIp,
Country,
ReqId,
Method,
Host,
Path,
CacheStatus,
BackendTime,
}
impl Var {
pub const ALL: [(&'static str, Var); 14] = [
("srv_id", Var::SrvId),
("srv_url", Var::SrvUrl),
("location", Var::Location),
("vhost", Var::Vhost),
("lb_algorithm", Var::LbAlgorithm),
("hash_key", Var::HashKey),
("client_ip", Var::ClientIp),
("country", Var::Country),
("req_id", Var::ReqId),
("method", Var::Method),
("host", Var::Host),
("path", Var::Path),
("cache_status", Var::CacheStatus),
("backend_time", Var::BackendTime),
];
fn parse(name: &str) -> Option<Self> {
Self::ALL
.iter()
.find(|(candidate, _)| *candidate == name)
.map(|(_, var)| *var)
}
/// Known only once the response exists.
fn response_only(self) -> bool {
matches!(self, Var::CacheStatus | Var::BackendTime)
}
}
#[derive(Debug, Clone)]
enum Segment {
Text(String),
Var(Var),
}
#[derive(Debug, Clone)]
pub struct Template(Vec<Segment>);
impl Template {
fn parse(value: &str) -> Result<Option<Self>> {
if !value.contains("%[") {
return Ok(None);
}
let mut segments = Vec::new();
let mut rest = value;
while let Some(start) = rest.find("%[") {
if start > 0 {
segments.push(Segment::Text(rest[..start].to_owned()));
}
let after = &rest[start + 2..];
let end = after
.find(']')
.context("unterminated %[variable] in header value")?;
let name = &after[..end];
let var = Var::parse(name).with_context(|| {
format!(
"unknown header variable %[{name}]; available: {}",
Var::ALL
.iter()
.map(|(n, _)| format!("%[{n}]"))
.collect::<Vec<_>>()
.join(", ")
)
})?;
segments.push(Segment::Var(var));
rest = &after[end + 1..];
}
if !rest.is_empty() {
segments.push(Segment::Text(rest.to_owned()));
}
Ok(Some(Self(segments)))
}
pub fn uses(&self, var: Var) -> bool {
self.0
.iter()
.any(|segment| matches!(segment, Segment::Var(v) if *v == var))
}
fn render(&self, vars: &Vars<'_>) -> Option<HeaderValue> {
let mut out = String::new();
for segment in &self.0 {
match segment {
Segment::Text(text) => out.push_str(text),
Segment::Var(var) => out.push_str(vars.get(*var).unwrap_or("-")),
}
}
// Values reflected from the request are visible ASCII; anything that is not a
// valid header value (e.g. control characters) drops the header.
HeaderValue::from_str(&out).ok()
}
}
/// Values for header variables; `None` renders as `-`.
#[derive(Debug, Default, Clone)]
pub struct Vars<'a> {
pub srv_id: Option<&'a str>,
pub srv_url: Option<&'a str>,
pub location: Option<&'a str>,
pub vhost: Option<&'a str>,
pub lb_algorithm: Option<&'a str>,
pub hash_key: Option<&'a str>,
pub client_ip: Option<&'a str>,
pub country: Option<&'a str>,
pub req_id: Option<&'a str>,
pub method: Option<&'a str>,
pub host: Option<&'a str>,
pub path: Option<&'a str>,
pub cache_status: Option<&'a str>,
pub backend_time: Option<&'a str>,
}
impl Vars<'_> {
fn get(&self, var: Var) -> Option<&str> {
match var {
Var::SrvId => self.srv_id,
Var::SrvUrl => self.srv_url,
Var::Location => self.location,
Var::Vhost => self.vhost,
Var::LbAlgorithm => self.lb_algorithm,
Var::HashKey => self.hash_key,
Var::ClientIp => self.client_ip,
Var::Country => self.country,
Var::ReqId => self.req_id,
Var::Method => self.method,
Var::Host => self.host,
Var::Path => self.path,
Var::CacheStatus => self.cache_status,
Var::BackendTime => self.backend_time,
}
.filter(|value| !value.is_empty())
}
}
/// Request facts captured when the request is routed, for response-side variables.
#[derive(Debug, Default, Clone)]
pub struct RequestVars {
pub location: Option<String>,
pub vhost: Option<String>,
pub lb_algorithm: Option<String>,
pub hash_key: Option<String>,
pub client_ip: Option<String>,
pub country: Option<String>,
pub method: Option<String>,
pub host: Option<String>,
pub path: Option<String>,
}
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default)]
pub struct CompiledHeaders { pub struct CompiledHeaders {
pub request: Vec<CompiledRule>, pub request: Vec<CompiledRule>,
pub response: Vec<CompiledRule>, pub response: Vec<CompiledRule>,
} }
impl CompiledHeaders {
/// True when a rule value uses `var`.
pub fn uses(&self, var: Var) -> bool {
self.request
.iter()
.chain(&self.response)
.any(|rule| rule.template.as_ref().is_some_and(|t| t.uses(var)))
}
pub fn has_templates(&self) -> bool {
self.request
.iter()
.chain(&self.response)
.any(|rule| rule.template.is_some())
}
}
impl HeaderRules { impl HeaderRules {
pub fn is_empty(&self) -> bool { pub fn is_empty(&self) -> bool {
self.request.is_empty() && self.response.is_empty() self.request.is_empty() && self.response.is_empty()
@@ -94,26 +271,60 @@ fn compile_rules(rules: &[Rule], direction: Direction) -> Result<Vec<CompiledRul
"transport/identity header cannot be changed: {}", "transport/identity header cannot be changed: {}",
name name
); );
let value = match (&rule.op, &rule.value) { let (value, template) = match (&rule.op, &rule.value) {
(Operation::Remove, None) => None, (Operation::Remove, None) => (None, None),
(Operation::Remove, Some(_)) => bail!("remove header rule cannot include a value"), (Operation::Remove, Some(_)) => bail!("remove header rule cannot include a value"),
(_, Some(value)) => { (_, Some(value)) => {
ensure!(value.len() <= 8192, "header value too long"); ensure!(value.len() <= 8192, "header value too long");
Some(value.parse().context("invalid header value")?) match Template::parse(value)? {
Some(template) => {
// The literal parts must form a valid header value too.
let _: HeaderValue = value
.replace("%[", "")
.replace(']', "")
.parse()
.context("invalid header value")?;
if direction == Direction::Request {
if let Some(var) =
template.0.iter().find_map(|segment| match segment {
Segment::Var(var) if var.response_only() => Some(*var),
_ => None,
})
{
bail!(
"%[{}] is only available in response header rules",
Var::ALL
.iter()
.find(|(_, v)| *v == var)
.map(|(n, _)| *n)
.unwrap_or("?")
);
}
}
(None, Some(template))
}
None => (Some(value.parse().context("invalid header value")?), None),
}
} }
(_, None) => bail!("set/append header rule requires a value"), (_, None) => bail!("set/append header rule requires a value"),
}; };
let dynamic = template.is_some();
Ok(CompiledRule { Ok(CompiledRule {
op: rule.op, op: rule.op,
name, name,
value, value,
template,
wire_only: direction == Direction::Response wire_only: direction == Direction::Response
&& rule.name.eq_ignore_ascii_case("age"), && (dynamic || rule.name.eq_ignore_ascii_case("age")),
}) })
}) })
.collect() .collect()
} }
fn apply_rule(headers: &mut HeaderMap, rule: &CompiledRule) { fn apply_rule(headers: &mut HeaderMap, rule: &CompiledRule) {
if rule.template.is_some() {
// Templates need request values; see apply_with_vars / apply_wire.
return;
}
match (&rule.op, &rule.value) { match (&rule.op, &rule.value) {
(Operation::Remove, _) => { (Operation::Remove, _) => {
headers.remove(&rule.name); headers.remove(&rule.name);
@@ -134,12 +345,43 @@ pub fn apply(headers: &mut HeaderMap, rules: &[CompiledRule]) {
} }
} }
} }
pub fn apply_wire_age(headers: &mut HeaderMap, rules: &[CompiledRule]) { fn apply_template(headers: &mut HeaderMap, rule: &CompiledRule, vars: &Vars<'_>) {
let Some(template) = &rule.template else {
return;
};
let Some(value) = template.render(vars) else {
return;
};
match rule.op {
Operation::Set => {
headers.insert(rule.name.clone(), value);
}
Operation::Append => {
headers.append(rule.name.clone(), value);
}
Operation::Remove => {}
}
}
/// Request rules with variables (static request rules use [`apply`]).
pub fn apply_with_vars(headers: &mut HeaderMap, rules: &[CompiledRule], vars: &Vars<'_>) {
for rule in rules {
apply_template(headers, rule, vars);
}
}
/// Final-delivery stage for response rules: `Age` rules and rules with variables.
pub fn apply_wire(headers: &mut HeaderMap, rules: &[CompiledRule], vars: &Vars<'_>) {
for rule in rules { for rule in rules {
if rule.wire_only { if rule.wire_only {
apply_rule(headers, rule); if rule.template.is_some() {
apply_template(headers, rule, vars);
} else {
apply_rule(headers, rule);
}
} }
} }
} }
pub fn apply_wire_age(headers: &mut HeaderMap, rules: &[CompiledRule]) {
apply_wire(headers, rules, &Vars::default());
}
#[cfg(test)] #[cfg(test)]
include!("tests.rs"); include!("tests.rs");
+57
View File
@@ -109,4 +109,61 @@ mod tests {
apply_wire_age(&mut headers, &compiled.response); apply_wire_age(&mut headers, &compiled.response);
assert_eq!(headers.get_all("age").iter().count(), 2); assert_eq!(headers.get_all("age").iter().count(), 2);
} }
#[test]
fn variables_render_per_request_and_only_on_the_wire() {
let rules: HeaderRules = serde_json::from_value(serde_json::json!({
"request": [{"op":"set","name":"x-shard","value":"%[srv_id]"},
{"op":"set","name":"x-static","value":"100%"}],
"response": [{"op":"set","name":"x-s","value":"%[srv_id]@%[location] (%[cache_status], %[backend_time])"},
{"op":"append","name":"x-lb","value":"%[lb_algorithm]:%[hash_key]"},
{"op":"set","name":"x-plain","value":"yes"}]
}))
.unwrap();
let compiled = rules.compile().unwrap();
assert!(compiled.has_templates());
assert!(compiled.uses(Var::HashKey) && !compiled.uses(Var::Country));
let vars = Vars {
srv_id: Some("mp3_2"),
location: Some("mp3"),
lb_algorithm: Some("hash"),
hash_key: Some("/a.mp3"),
cache_status: Some("HIT"),
..Default::default()
};
// Static stage: templates are skipped, so cached objects never carry them.
let mut headers = HeaderMap::new();
apply(&mut headers, &compiled.response);
assert_eq!(headers["x-plain"], "yes");
assert!(!headers.contains_key("x-s") && !headers.contains_key("x-lb"));
apply_wire(&mut headers, &compiled.response, &vars);
assert_eq!(headers["x-s"], "mp3_2@mp3 (HIT, -)");
assert_eq!(headers["x-lb"], "hash:/a.mp3");
assert_eq!(headers.get_all("x-plain").iter().count(), 1);
let mut request = HeaderMap::new();
apply(&mut request, &compiled.request);
assert_eq!(request["x-static"], "100%");
assert!(!request.contains_key("x-shard"));
apply_with_vars(&mut request, &compiled.request, &vars);
assert_eq!(request["x-shard"], "mp3_2");
// Values that are not valid header values drop the header instead of failing.
let mut bad = HeaderMap::new();
apply_wire(&mut bad, &compiled.response, &Vars { srv_id: Some("a b"), ..vars.clone() });
assert_eq!(bad["x-s"], "a b@mp3 (HIT, -)");
let mut dropped = HeaderMap::new();
apply_wire(&mut dropped, &compiled.response, &Vars { srv_id: Some("a\r\nX-Evil: 1"), ..vars });
assert!(!dropped.contains_key("x-s"), "CR/LF never reaches a header");
assert!(!dropped.contains_key("x-evil"));
}
#[test]
fn invalid_variables_are_rejected() {
for rules in [
serde_json::json!({"response":[{"op":"set","name":"x","value":"%[nope]"}]}),
serde_json::json!({"response":[{"op":"set","name":"x","value":"%[srv_id"}]}),
serde_json::json!({"request":[{"op":"set","name":"x","value":"%[cache_status]"}]}),
serde_json::json!({"request":[{"op":"set","name":"x","value":"%[backend_time]"}]}),
] {
let parsed: HeaderRules = serde_json::from_value(rules.clone()).unwrap();
assert!(parsed.compile().is_err(), "{rules} should be rejected");
}
}
} }
+2
View File
@@ -56,6 +56,8 @@ pub struct Exchange {
/// Location chosen by conditional routing when it differs from the route the /// Location chosen by conditional routing when it differs from the route the
/// response layer saw before the request was forwarded. /// response layer saw before the request was forwarded.
pub routed: Mutex<Option<Arc<crate::config::CompiledRoute>>>, pub routed: Mutex<Option<Arc<crate::config::CompiledRoute>>>,
/// Request values for response header rules with `%[variables]`.
pub header_vars: Mutex<Option<Arc<crate::headers::RequestVars>>>,
pub source: AtomicU8, pub source: AtomicU8,
pub cache_effective_enabled: AtomicU8, pub cache_effective_enabled: AtomicU8,
pub transform_effective_enabled: AtomicU8, pub transform_effective_enabled: AtomicU8,
+1
View File
@@ -12,6 +12,7 @@ mod tests {
vhost: None, vhost: None,
route: Mutex::new(None), route: Mutex::new(None),
routed: Mutex::new(None), routed: Mutex::new(None),
header_vars: Mutex::new(None),
source: AtomicU8::new(ExchangeSource::Unresolved as u8), source: AtomicU8::new(ExchangeSource::Unresolved as u8),
cache_effective_enabled: AtomicU8::new(0), cache_effective_enabled: AtomicU8::new(0),
transform_effective_enabled: AtomicU8::new(0), transform_effective_enabled: AtomicU8::new(0),
+16
View File
@@ -255,6 +255,22 @@ fn apply_response_age_rules(
crate::headers::apply_wire_age(headers, &route.headers.response); crate::headers::apply_wire_age(headers, &route.headers.response);
} }
} }
/// Final-delivery response rules: `Age` and rules with `%[variables]`.
fn apply_response_wire_rules(
headers: &mut http::HeaderMap,
snapshot: &crate::config::Snapshot,
frontend: Option<&crate::config::CompiledFrontend>,
route: Option<&crate::config::CompiledRoute>,
vars: &crate::headers::Vars<'_>,
) {
crate::headers::apply_wire(headers, &snapshot.headers.response, vars);
if let Some(frontend) = frontend {
crate::headers::apply_wire(headers, &frontend.headers.response, vars);
}
if let Some(route) = route {
crate::headers::apply_wire(headers, &route.headers.response, vars);
}
}
fn finish_headers( fn finish_headers(
response: &mut Response, response: &mut Response,
snapshot: &crate::config::Snapshot, snapshot: &crate::config::Snapshot,
+61
View File
@@ -45,6 +45,21 @@ if route.unavailable {
if let crate::config::CompiledSource::WebServer(service) = &route.source { if let crate::config::CompiledSource::WebServer(service) = &route.source {
return include!("web_source.rs"); return include!("web_source.rs");
} }
// Header rules with %[variables] need request facts; computed only when used.
let header_templates = snapshot.headers.has_templates()
|| route.frontend.as_ref().is_some_and(|f| f.headers.has_templates())
|| route.headers.has_templates();
let template_hash_key = (header_templates
&& [&snapshot.headers, &route.headers]
.into_iter()
.chain(route.frontend.as_ref().map(|f| &f.headers))
.any(|h| h.uses(crate::headers::Var::HashKey)))
.then(|| {
route.pool.as_ref().and_then(|pool| {
pool.balance_key(context.client_ip, request.headers(), Some(request.uri()))
})
})
.flatten();
let (backend, backend_lease, affinity_cookie) = if let Some(pool) = &route.pool { let (backend, backend_lease, affinity_cookie) = if let Some(pool) = &route.pool {
let selection = match &route.backend_id { let selection = match &route.backend_id {
Some(id) => pool.select_member_wait(id).await, Some(id) => pool.select_member_wait(id).await,
@@ -299,6 +314,52 @@ if let Some(frontend) = &route.frontend {
crate::headers::apply(request.headers_mut(), &frontend.headers.request); crate::headers::apply(request.headers_mut(), &frontend.headers.request);
} }
crate::headers::apply(request.headers_mut(), &route.headers.request); crate::headers::apply(request.headers_mut(), &route.headers.request);
if header_templates {
let request_vars = crate::headers::RequestVars {
location: Some(route.name.clone()),
vhost: route.frontend.as_ref().map(|f| f.id.clone()),
lb_algorithm: route.pool.as_ref().map(|p| p.algorithm_name().to_owned()),
hash_key: template_hash_key.clone(),
client_ip: Some(context.client_ip.to_string()),
country: country.clone(),
method: Some(request.method().as_str().to_owned()),
host: Some(host.clone()),
path: Some(path.to_string()),
};
let srv_id = backend_lease
.as_ref()
.map(|lease| lease.member.definition.id.clone())
.unwrap_or_else(|| backend.id.rsplit('/').next().unwrap_or("").to_owned());
let srv_url = backend_lease
.as_ref()
.map(|lease| lease.member.definition.url.clone())
.unwrap_or_else(|| backend.origin.clone());
let request_id = exchange.as_ref().map(|e| e.request_id.clone());
let vars = crate::headers::Vars {
srv_id: Some(&srv_id),
srv_url: Some(&srv_url),
location: request_vars.location.as_deref(),
vhost: request_vars.vhost.as_deref(),
lb_algorithm: request_vars.lb_algorithm.as_deref(),
hash_key: request_vars.hash_key.as_deref(),
client_ip: request_vars.client_ip.as_deref(),
country: request_vars.country.as_deref(),
req_id: request_id.as_deref(),
method: request_vars.method.as_deref(),
host: request_vars.host.as_deref(),
path: request_vars.path.as_deref(),
cache_status: None,
backend_time: None,
};
crate::headers::apply_with_vars(request.headers_mut(), &snapshot.headers.request, &vars);
if let Some(frontend) = &route.frontend {
crate::headers::apply_with_vars(request.headers_mut(), &frontend.headers.request, &vars);
}
crate::headers::apply_with_vars(request.headers_mut(), &route.headers.request, &vars);
if let Some(exchange) = &exchange {
*exchange.header_vars.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(request_vars));
}
}
context.apply_upstream( context.apply_upstream(
request.headers_mut(), request.headers_mut(),
route route
+62 -1
View File
@@ -216,6 +216,7 @@ async fn observe(state: Arc<App>, mut request: Request) -> Response {
vhost: frontend_context.as_ref().map(|f| f.id.clone()), vhost: frontend_context.as_ref().map(|f| f.id.clone()),
route: Mutex::new(None), route: Mutex::new(None),
routed: Mutex::new(None), routed: Mutex::new(None),
header_vars: Mutex::new(None),
source: AtomicU8::new(ExchangeSource::Unresolved as u8), source: AtomicU8::new(ExchangeSource::Unresolved as u8),
cache_effective_enabled: AtomicU8::new(0), cache_effective_enabled: AtomicU8::new(0),
transform_effective_enabled: AtomicU8::new(0), transform_effective_enabled: AtomicU8::new(0),
@@ -463,11 +464,71 @@ async fn observe(state: Arc<App>, mut request: Request) -> Response {
} }
} }
if !minimal_welcome { if !minimal_welcome {
apply_response_age_rules( let request_vars = exchange
.header_vars
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
let lease = exchange
.backend
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
// Stale-if-error copies name the backend that failed; a plain cache hit has none.
let origin = response.extensions().get::<OriginBackend>().map(|o| o.0.clone());
let srv_id = lease
.as_ref()
.map(|lease| lease.member.definition.id.clone())
.or_else(|| {
origin
.as_deref()
.map(|id| id.rsplit('/').next().unwrap_or(id).to_owned())
});
let srv_url = lease.as_ref().map(|lease| lease.member.definition.url.clone());
let backend_time = response
.extensions()
.get::<OriginTiming>()
.map(|t| format!("{:.2}ms", t.0.as_secs_f64() * 1000.0));
let cache_status = match exchange.cache_status.load(Ordering::Relaxed) {
1 => "HIT",
2 => "MISS",
_ => "BYPASS",
};
let fallback_location = effective_route_context.map(|route| route.name.clone());
let vars = crate::headers::Vars {
srv_id: srv_id.as_deref(),
srv_url: srv_url.as_deref(),
location: request_vars
.as_ref()
.and_then(|v| v.location.as_deref())
.or(fallback_location.as_deref()),
vhost: request_vars
.as_ref()
.and_then(|v| v.vhost.as_deref())
.or(frontend_context.as_ref().map(|f| f.id.as_str())),
lb_algorithm: request_vars.as_ref().and_then(|v| v.lb_algorithm.as_deref()),
hash_key: request_vars.as_ref().and_then(|v| v.hash_key.as_deref()),
client_ip: request_vars.as_ref().and_then(|v| v.client_ip.as_deref()),
country: request_vars.as_ref().and_then(|v| v.country.as_deref()),
req_id: Some(exchange.request_id.as_str()),
method: Some(exchange.method.as_str()),
host: request_vars
.as_ref()
.and_then(|v| v.host.as_deref())
.or(Some(exchange.host.as_str())),
path: request_vars
.as_ref()
.and_then(|v| v.path.as_deref())
.or(Some(exchange.path.as_str())),
cache_status: Some(cache_status),
backend_time: backend_time.as_deref(),
};
apply_response_wire_rules(
response.headers_mut(), response.headers_mut(),
&snapshot, &snapshot,
frontend_context.as_deref(), frontend_context.as_deref(),
effective_route_context, effective_route_context,
&vars,
); );
} }
if response if response