This commit is contained in:
Mateusz Gruszczyński committed 2026-11-25 15:47:34 +01:00
1 parent 6df256cdbb
commit 0d6249e383
159 files changed
+16737 -1971

No files matched your search

+4 -1
View File
@@ -16,12 +16,14 @@ The current bundled `src/admin/openapi.json` declares these operations (among ot
| `POST /api/config/reload` | Revalidate and hot-reload manually changed `--config` JSON; revision-aware. |
| `GET/POST /api/api-tokens` · `DELETE /api/api-tokens/{id}` | List/generate/revoke general RO/RW API tokens (browser-admin-only). |
| `GET/POST/DELETE /api/prometheus-token` | Inspect/generate/rotate/revoke a standalone Prometheus scrape token (browser-admin-only). |
| `GET /api/config/{section}` · `PUT /api/config/{section}` | Read or atomically replace one of 23 supported configuration sections. |
| `GET /api/config/{section}` · `PUT /api/config/{section}` | Read or atomically replace a supported configuration section, including `policy` since 0.42.0. |
| `POST /api/config/geoip/update` | Run a GeoIP download/check/reload immediately using already-saved GeoIP settings; does not change revision. |
| `GET /api/config/history` · `POST /api/config/history/restore` | Review/restore retained configuration snapshots. |
| `GET /api/status` · `GET /api/backends` | Operational status and backend observations. |
| `GET /api/cache` · `POST /api/cache/purge` · `POST /api/cache/invalidate` | Cache observations and authenticated invalidation. `GET` supports the lightweight `view=live` polling view. |
| `GET /api/cache/rules/stats` · `GET /api/cache/rules/targets` · `POST /api/cache/rules/test` · `POST /api/cache/rules/import-vcl` | Cache rule match counters, the vhosts a rule can target (ordinary and generated Docker vhosts), simulation of saved or draft rules for a test request/response (also for Docker vhosts), and conversion of a VCL subset into rules (nothing is saved). See [Cache rules](CACHE.md#cache-rules-vcl-style) and the [supported VCL import matrix](VCL.md). |
| `POST /api/policy/import-haproxy` · `POST /api/policy/test` | Convert a strictly supported HAProxy snippet into a policy draft, or evaluate policy rules against a supplied fixture with a trace. Neither endpoint saves configuration. See [HTTP policy rules](POLICY.md). |
| `GET /api/policy/stats` | Match/action-error counters for active policy rules by scope; reset on configuration recompilation. Draft tests do not affect the counters. |
| `GET /api/transform` | Transform observations and resource usage. Supports the lightweight `view=live` polling view. |
| `GET /api/logs` · `GET /api/live-logs` | Recent and streaming request logs. |
| `GET /api/file-logs` · `GET /api/file-logs/query` | Stored-log exploration. Source metadata includes `domains` (current configured hostnames/aliases, empty when not applicable); source and group IDs remain stable. |
@@ -94,6 +96,7 @@ The section name in the URL and its corresponding JSON member in a full configur
| `transform` | `transform` |
| `forwarding` | `forwarding` |
| `headers` | `headers` |
| `policy` | `policy` |
| `prometheus` | `prometheus` |
| `geoip` | `geoip_updates` |
| `administration` | `administration` |
+19
View File
@@ -119,6 +119,25 @@ With the policy enabled, the middle request stays `HIT` if the entry is fresh. C
In **Vhosts → Cache**, overrides for static extensions, bypass path prefixes and unsafe force targets each place the enable/override checkbox immediately above the associated multiline list. The fields are disabled while their individual override is off; their saved values and cache policy are unchanged. Never enable unsafe forced caching for personalized responses.
In corrected 0.42.0, forced-cache keys always partition by both `Cookie` and
`Authorization` **before lookup**. Missing, empty and nonempty fields remain
distinct, including when one credential appears only after another variant was
cached. Explicit VCL/HTTP-policy lookup partitions Cookie in the same way;
Authorization still bypasses unless the separate force option admits it.
The forwarded values after the existing credential filter and supported request
edits are used. An entirely empty input Cookie field is still removed by the
admin-cookie filter; a valid empty cookie such as `session=` remains distinct
from no Cookie. Responses add the corresponding `Vary` dimensions even when the
request lacks those fields. Explicit later delivery-header overrides retain
their documented behavior and must preserve dimensions needed downstream.
These keys use a new internal namespace, so older forced/VCL-lookup HOT/COLD
entries cannot satisfy the corrected lookups; they may remain on disk until
normal eviction or cleanup. Other cache keys and the COLD file format remain
compatible. Credential-partitioned fills do not schedule proactive background
refresh; ordinary foreground validation retains the matching request context.
Response privacy exclusions and explicit VCL `return(pass)` still apply.
## Cache decision precedence, explicit `pass` and public static assets
**Applies to RustProxy 0.39.2.** Every reason that keeps a request away from the HOT/COLD cache is classified by one central decision (`src/cache/policy/decision.rs`), used by live traffic and by **Test a request**. Reasons are evaluated strongest first:
+8
View File
@@ -109,6 +109,14 @@ Appearance settings, Dashboard Presets and Overview cards belong to the administ
## Sample files and safe changes
Since 0.42.0, the optional `policy` member configures [HTTP policy rules](POLICY.md)
globally; Vhosts, Docker assignments and locations can carry their own policy.
Each object contains `acls`, `maps` and `rules`. Omitting it is a no-op. Policies
are compiled with the configuration and apply live after successful validation;
an invalid rule rejects the update. Existing `headers` and `cache.rules` remain
valid and preserve their previous ordering. The global section endpoint is
`GET/PUT /api/config/policy`.
Example JSON is in `examples/`. Treat it as a starting point: addresses, certificates, paths, backend health endpoints and service IDs must match your installation. The API uses full validated settings and rejects unknown fields; it is **not** a generic patch store. Use the current authenticated `/docs → API` OpenAPI reference to inspect field schemas.
For planned changes, export configuration, create an encrypted backup, make one logical change, save, verify real traffic and confirm metrics/logs. Revert via configuration history only when rollback of the config (not filesystem/secrets) is sufficient.
+7
View File
@@ -18,6 +18,13 @@ Encoded `/` separators (`%2F` / `%2f`) are normalized to real `/` only for locat
## Request conditions (routing by header, cookie, IP…)
Since 0.42.0, a location can also carry a `policy` object for
[HTTP policy actions](POLICY.md) after it has been selected. These policies do
not replace the path/condition selector below. Location `pre_route` rules are
rejected; use a global or Vhost `pre_route` policy when the request must change
before selection. Location policies run after global and Vhost policy at the
same stage, without changing existing VCL precedence.
A location can require extra **conditions** besides its path — the RustProxy equivalent of HAProxy ACLs in `use_backend <backend> if <acl> <acl>`. Each condition tests one request attribute:
| `source` | `name` | Operators | Notes |
+6
View File
@@ -2,6 +2,12 @@
RustProxy discovers published Docker services through a **separate read-only Docker agent** on each Docker host. The RustProxy core does not need Docker-socket access. The agent observes Docker containers; RustProxy turns enabled assignments into dynamic, ordinary HTTP Vhosts.
Since 0.42.0, a configured Docker assignment can persist an optional
[HTTP policy](POLICY.md) alongside its other Vhost settings. The generated Vhost
inherits that policy, including its location policies. Edit the assignment
through the Docker Vhost configuration; changing a transient discovered Vhost
does not replace the assignment as the source of configuration.
## Set up a Docker host
Install the **optional Docker agent on each Linux Docker host**, not on the RustProxy server. It is distributed as a separate `rustproxy-docker-agent` DEB/RPM package and is **not built as FreeBSD `pkg`**. Docker Engine **or Podman**, systemd and access to the container API socket (`/var/run/docker.sock`, `/run/podman/podman.sock` or a rootless `$XDG_RUNTIME_DIR/podman/podman.sock`) are required at runtime. The agent detects the socket automatically (`RUSTPROXY_DOCKER_SOCKET=auto`); see [docker-agent/README.md](../docker-agent/README.md#podman) for Podman socket permissions.
+3 -1
View File
@@ -16,6 +16,7 @@ RustProxy is a single service that combines a reverse proxy, a static/PHP web se
| Custom locations | Prefix, exact and regex paths, path rewriting, per-location backends, Web Services, local responses, redirects and internal error fallbacks |
| WebSockets | HTTP/1.1 Upgrade, RFC 8441 (HTTP/2) and RFC 9220 (HTTP/3) Extended CONNECT |
| Forwarding headers | `X-Forwarded-*`, `Forwarded`, `X-Real-IP`, trusted proxy ranges, Cloudflare client IP and country |
| HTTP policies | Optional global, Vhost, Docker-assignment and location policies: named ACLs, nested AND/OR/NOT, typed samples, maps, transaction variables, header/list operations and explicit request/response stages. Strict HAProxy subset importer, draft tester and [VCL cooperation](POLICY.md) with legacy precedence preserved. |
| Redirects and pages | Redirect hosts, canonical host and HTTPS redirects, 404 hosts, custom error pages and direct-IP pages |
| TCP/UDP Streams | Layer-4 forwarding with backend pools, health checks, session limits and idle timeouts |
@@ -65,7 +66,8 @@ RustProxy is a single service that combines a reverse proxy, a static/PHP web se
- Shared HTTP cache with a memory tier (HOT) and an optional disk tier (COLD).
- RFC 9111 freshness, validators and `Vary` with conservative header-aware normalization (known comma-list fields, language/encoding/charset qualities and media types), while preserving opaque values and quoted strings; stale-while-revalidate, stale-if-error and request coalescing. Configurable static-extension exception for cookie-independent assets: omit `Vary: Cookie` only for explicitly public cacheable responses, preserving all other Vary dimensions. A central [cache decision](CACHE.md#cache-decision-precedence-explicit-pass-and-public-static-assets) separates security bypasses, explicit VCL `pass`, Cookie/session guards (`cookie_pass`) and backend properties, so public static assets can be HIT for logged-in users without weakening explicit pass rules; Cookie-bearing static fills are stored only when the backend reply is explicitly public.
- Varnish-compatible policy option, forced caching rules and per-location cache switches.
- Varnish-compatible policy option, forced caching rules and per-location cache switches. Forced caching partitions Cookie/Authorization before HOT/COLD lookup, including absent and empty effective values; explicit VCL lookup partitions Cookie while retaining the Authorization bypass.
- Structured VCL imports retain `if`/`elsif`/`else` selection through header mutations and nested actions. The editor preserves whole control-flow groups; older flat conversions can be replaced by re-importing their original VCL source.
- Graphical [cache rules](CACHE.md#cache-rules-vcl-style) with global and per-Vhost precedence, terminal VCL pass/hash behavior, ordered safe request-header/cookie/query rewrites, vcl_hash variants, reversible rule-only no-store decisions, backend-response header edits before cache policy, and delivery header overrides; includes a shared, responsive two-section tester in global, ordinary vhost and Docker vhost editors, a scope-aware in-panel VCL guide, and a warning-reporting VCL subset importer. The exact VCL syntax, backend vs deliver `Vary`/header mutations and safety restrictions are listed in [VCL compatibility](VCL.md); the [traffic cookbook](VCL_TRAFFIC_COOKBOOK.md) includes ready-to-import examples and expected live request outcomes.
- RFC 9211 `Cache-Status` and optional `X-Cache` diagnostics.
- Purge and ban from the panel, the API or HTTP PURGE/BAN from allowlisted addresses.
+8
View File
@@ -53,6 +53,14 @@ The file can contain secrets: Docker agent tokens, client secrets of login provi
## Minimal configuration
The optional [HTTP policy](POLICY.md) format also works in headless mode. See
[`examples/policy-vary.json`](../examples/policy-vary.json) for the duplicate
`Vary` ACL case and
[`examples/policy-vcl-cooperation.json`](../examples/policy-vcl-cooperation.json)
for policy classification consumed by existing VCL-style cache rules. JSON is
the saved format; use the panel importer/API to convert supported HAProxy text
before placing the resulting `policy` object in a headless configuration.
The smallest useful file is a single vhost ([`examples/headless-minimal.json`](../examples/headless-minimal.json)). `"*"` as the host makes it answer every hostname and IP address that no other vhost claims, so no domain is needed:
```json
+2
View File
@@ -17,6 +17,8 @@ A managed install uses `update.sh`; an unmanaged source-tree install must follow
| Change area | What to review |
|---|---|
| **Cache** | Operational Vhost saves aim to retain compatible HOT/COLD cache. Content-affecting changes invalidate a scope; older disk cache objects can require refilling. Validate actual behavior before rollout. |
| **0.42.0 VCL imports** | Fresh imports preserve branch selection with validated `vcl_flow` metadata. Existing flat conversions keep their old behavior; re-import the original source and replace the old rules to fix branches that mutate their own conditions. Keep a pre-upgrade configuration for rollback; do not strip the new metadata. See [VCL upgrade guidance](VCL.md#recognized-conditions-and-expressions). |
| **0.42.0 credential variants** | Corrected force-cache/VCL-lookup keys use a new internal namespace, so older entries in those modes require a refill. Unaffected cache keys and the COLD file format stay compatible. Normal credential bypass and explicit pass remain in force. |
| **Web Server** | `sendfile=auto` is an optional Linux cleartext HTTP/1.1 path; default is `off`. No existing service needs to enable it. |
| **0.32.x origin protocols** | Legacy backend `http2` remains compatible on TLS (H2/H1) and H2C for plain HTTP. New strict `h2` must be set explicitly. |
| **0.33.x Overview** | Dashboard presets/layouts are per administrator, independent from Vhost configuration; existing preferences should be retained and new widgets may remain hidden. |
+313
View File
@@ -0,0 +1,313 @@
# HTTP policy rules and VCL cooperation
Since 0.42.0, an optional `policy` object provides named ACLs, nested conditions,
sample expressions, transaction variables, maps and ordered HTTP actions. It is
available globally, on a Vhost (including a configured Docker assignment), and on
a custom location. Existing configurations need no conversion: omitting `policy`
keeps the previous behavior.
The JSON model is authoritative. The HAProxy importer converts a **supported
subset** into that model; it does not run HAProxy or load a complete HAProxy
configuration. The existing VCL importer and cache rules retain their semantics.
Policy hooks share the request and response with VCL at the explicit boundaries
below. VCL remains the owner of its existing cache-rule precedence and terminal
`return(pass)` / `return(hash)` behavior.
## Configure and activate
- In the panel, open **Settings → Rules & headers → HTTP policies** globally,
**Vhost → Headers → HTTP policies**, the location's **HTTP policies** section,
or the Docker assignment's policy section. The shared editor offers a rule
builder, a JSON view, import preview and a draft tester. Reordering uses the
visible rule order; switching views preserves the same policy object.
- Set `policy` in the complete configuration, `vhosts[].policy`, or
`vhosts[].routes[].policy`. A Docker assignment stores its policy with that
assignment so discovery does not discard the customization.
- A policy contains `acls` and `maps` objects and an ordered `rules` array. Each
rule has a unique `id`, a `stage`, optional `when`, and an `actions` array.
`name` is descriptive, `enabled` defaults to `true`, and `stop` defaults to
`false`. An omitted condition matches every request reaching that stage.
- Validate and save through the normal configuration path. Compilation checks
field names, expressions, available stages, action arguments and bounds before
activation. Existing connections retain their configuration snapshot.
- Headless mode uses the same fields. Validate with
`rust-proxy --headless config validate config.json`, then reload using
the normal headless reload or watch mechanism.
The complete [Vary example](../examples/policy-vary.json) is suitable for a local
headless test after adjusting its backend address. The
[cooperation example](../examples/policy-vcl-cooperation.json) demonstrates a
request classification consumed by VCL-style cache rules.
## Stages and existing rules
| Stage | Runs when | Relationship to VCL and existing headers |
|---|---|---|
| `pre_route` | After global and host access checks, before final location selection | Global and Vhost policies only. URL rewrites are restricted to this stage; the resulting target goes through normal routing and access validation. |
| `request` | After route access/authentication, before source handling and cache request rules | Header changes are visible to existing `vcl_recv` and `vcl_hash` rules. |
| `backend_request` | When sending a request to a selected reverse-proxy backend | After existing custom request headers; trusted identity and transport headers remain protected. Configuring this stage conservatively bypasses shared cache. |
| `backend_response` | On a reverse-proxy origin response, before the cache plan | After existing `beresp` header edits. New rules can inspect those edits. Explicit VCL TTL/grace retain precedence over policy TTL/grace. |
| `deliver` | On the response leaving source handling | After existing `vcl_deliver`, before outer compression and final diagnostic/custom headers. Applies to cache HIT, MISS and BYPASS when a policy context exists. |
| `after_response` | At final delivery | After compression and existing dynamic custom headers. Suitable for final `Vary` normalization and per-request diagnostic headers. Local-response no-cache enforcement still applies afterward. |
Administrative/control-plane traffic, the minimal welcome response and protected
authentication-provider responses are excluded. Backend stages do not run on a
cache HIT. A location cannot declare a `pre_route` rule: location selection has
not occurred at that point, so validation rejects it.
Within each stage, new policies run **Global → Vhost → Location**; each scope
retains array order. Later rules see earlier header/variable changes. `stop` or
the `stop` action ends the current scope's chain, not the other scopes or later
stages. A terminal response ends request processing.
This does **not** reorder legacy VCL: its local rules still run before global
rules, with local ownership of conflicting headers/settings. Existing Custom
Headers keep their Global → Vhost → Location order and their static/dynamic
separation. Use the stage table when both mechanisms edit the same header.
## Exact duplicate `Vary` rule
This policy matches two complete `Vary` fields, one containing exactly
`Accept-Encoding` and another containing either spelling of the combined value:
```json
{
"acls": {
"vary_duplicate": {"fetch": "res.fhdr_cnt(Vary)", "operator": "eq", "values": ["2"]},
"vary_encoding": {"fetch": "res.fhdr(Vary)", "operator": "equals", "ignore_case": true, "values": ["Accept-Encoding"]},
"vary_combined": {"fetch": "res.fhdr(Vary)", "operator": "equals", "ignore_case": true, "values": ["Accept,Accept-Encoding", "Accept, Accept-Encoding"]}
},
"rules": [
{
"id": "combine-duplicate-vary",
"stage": "backend_response",
"when": {"all": [{"acl": "vary_duplicate"}, {"acl": "vary_encoding"}, {"acl": "vary_combined"}]},
"actions": [{"type": "set_header", "name": "Vary", "value": "Accept, Accept-Encoding"}]
}
]
}
```
Put that object under the desired `policy` member. The equivalent import source
is [policy-vary.haproxy](../examples/policy-vary.haproxy). A single field
`Vary: Accept, Accept-Encoding` has a full-field count of **one**, not two.
Adding a third `Vary` field makes the exact rule fail instead of erasing an
unrelated dimension.
For general cleanup, prefer a semantic operation:
```json
{
"id": "normalize-final-vary",
"stage": "after_response",
"actions": [{"type": "normalize_header", "name": "Vary"}]
}
```
It combines valid field lists and removes duplicate tokens while preserving
first occurrence order and required dimensions. When `*` occurs, canonical
`Vary: *` covers all dimensions and remains uncacheable. Malformed values are left
unchanged; normalization does not make them cacheable. It does not collapse
`Set-Cookie` into a comma list. List actions support `Vary`, `Allow`,
`Accept-Encoding`, `Content-Language`, `Access-Control-Allow-Methods`,
`Access-Control-Allow-Headers` and `Access-Control-Expose-Headers`. Parameterized
or quoted values outside the token-list grammar are left unchanged.
## Conditions, samples and maps
Conditions use `all`, `any`, `not`, `acl`, or a comparison with `fetch`,
`operator`, `values` and optional `ignore_case`. A comparison matches when any
returned sample matches any configured value. Numeric operands are strings in
the JSON `values` array. `exists` takes no values. ACLs are named expressions in
the same policy; unknown references and cycles are rejected.
| Sample family | Examples |
|---|---|
| Request identity | `method`, `path`, `url`, `query`, `host`; aliases `req.method`, `req.path`, `req.url`, `req.host` |
| Request and response fields | `req.fhdr(Name)`, `res.fhdr(Name)` for complete field values; `req.hdr(Name)`, `res.hdr(Name)` for list members |
| Counts and occurrences | `res.fhdr_cnt(Vary)` counts complete fields; `res.hdr_cnt(Vary)` counts list members; `res.fhdr(Vary,1)` selects the first field, `-1` the last |
| Cookies and query | `req.cook(name)`, `res.cook(name)`, `url_param(name)` / `req.query(name)` |
| Client/context | `src` / `client_ip`, `country`, `ssl_fc` / `tls`, `vhost`, `location`, `req_id` |
| Response/backend | `status` / `res.status`, `cache_status`, `srv_id`, `srv_url`, `backend_time`, `lb_algorithm`, `hash_key` |
| Variables/literals | `var(txn.name)`, `str(value)`, `int(42)` |
Response fields require a response stage. `cache_status` and `backend_time` are
available at delivery; selected-backend fields are unavailable before backend
selection. Location is unavailable in `pre_route`. Invalid stage/sample
combinations are rejected when saving, not deferred to live traffic.
Text operators are `equals`, `contains`, `prefix`, `suffix`, `regex`, and
`exists`; IP/CIDR tests use `cidr`. Integer comparisons are `eq`, `ne`, `gt`,
`ge`, `lt`, `le`. Negate an expression using `not`.
Header/action values support `%[sample]`, including converter chains such as
`%[req.fhdr(User-Agent),lower]`. Supported converters are `lower`, `upper`,
`trim`, `length`, `map(name[,fallback])` and `regsub(pattern,replacement)`.
Conditions inspect all returned samples; a value template selects the last
sample unless an occurrence is explicit. A missing sample renders as `-`.
The replacement converter uses the Rust regex syntax and performs replacement
globally; do not assume every HAProxy regex/converter form is interchangeable.
Maps are declared inline, without filesystem reads during requests:
```json
{
"maps": {
"plans": {
"kind": "exact",
"ignore_case": true,
"entries": [{"key": "premium", "value": "priority"}],
"default": "standard"
}
},
"rules": [
{
"id": "classify-plan",
"stage": "request",
"actions": [{"type": "set_var", "name": "txn.plan", "value": "%[req.fhdr(X-Plan),map(plans)]"}]
},
{
"id": "show-plan",
"stage": "after_response",
"actions": [{"type": "set_header", "name": "X-Plan-Class", "value": "%[var(txn.plan)]"}]
}
]
}
```
Maps support `exact`, `prefix`, `regex` and `ip`. Prefix/IP maps prefer the most
specific prefix; regex maps retain entry order. Variables are restricted to
`txn.*`, belong to one request and are never stored in cached objects. Classifying
a client header does not make it a trusted authentication claim.
## Actions and cache boundaries
| Area | JSON action types |
|---|---|
| Headers | `set_header`, `append_header`, `remove_header`, `set_if_missing`, `replace_header`, `replace_value` |
| Token lists | `normalize_header`, `merge_header`, `remove_value` |
| Variables | `set_var`, `unset_var` |
| Request target | `set_path`, `set_query` in `pre_route` |
| Configured backend | `use_backend` selects an existing backend member; it is not an arbitrary URL fetch |
| Local response | `deny` in `pre_route`/`request`; `return` and `redirect` only in `request`, after route access/authentication |
| Cache | `pass`, `lookup`, `no_store`, `set_ttl`, `set_grace`, `hash_header` |
| Delivery/control | `disable_compression`, `stop` |
The compiler checks each action against its stage. Transport, framing and trusted
identity headers remain protected. A rendered header must be valid HTTP; CR/LF
injection and oversized values are rejected or skipped with a trace warning.
Successful/redirect local responses cannot terminate `pre_route` processing
before the selected location's access and authentication checks.
Cache behavior is deliberately explicit:
1. A policy `pass` and a VCL `return(pass)` both win over any lookup request.
Existing authorization, method, route and disabled-cache checks remain in
force. A lookup does not grant permission to store a private response.
2. Existing VCL `return(hash)` still ends `vcl_recv` and still runs `vcl_hash`.
Policy request-header changes are visible to that hash phase. Adding an
internal hash dimension does not automatically add downstream `Vary`. That
field must name the real client attributes that select a representation: the
cooperation example merges `User-Agent` into `Vary`, since its `X-Device`
header is created inside the proxy and is absent from browser requests.
3. Backend-response edits run before storage policy. A VCL TTL/grace assignment
wins over a conflicting policy assignment; no-store decisions accumulate.
These decisions also apply to foreground `304` validation. A no-store
decision can serve the validated body for that request while discarding the
object instead of publishing a refreshed cache entry.
4. Backend-request customization, policy backend selection, and backend-response
policies dependent on per-client state conservatively bypass shared storage.
This includes request headers/cookies, client identity, transaction variables,
method, TLS and balancing hash samples. Put purely diagnostic, per-client
response headers in a delivery stage.
5. Delivery changes do not rewrite the stored object, its key, TTL or variants.
Every new policy edit to `Vary` in `deliver` or `after_response`, including
generic set/remove/replace, must retain the existing dimensions and `*`.
An edit that removes one or creates malformed `Vary` is skipped atomically
and counted as an action error; the tester includes a warning. Manual
`backend_response` edits can replace the field before cache planning, so the
operator must preserve every dimension on which the origin actually varies.
These new guards do not silently change legacy VCL/Custom Header semantics.
When any `backend_response` policy is configured in the applicable scopes, or a
request adds an explicit policy `hash_header` dimension, expired
stale-while-revalidate entries are validated synchronously and proactive
background refresh is disabled. This ensures the rules run in the current
request's policy context and preserves the original hash inputs. Fresh cache
HITs and existing explicit `max-stale` /
`only-if-cached` behavior remain available. This release does not run these rules
in an independent background policy context.
## HAProxy import and API
`POST /api/policy/import-haproxy` converts supported ACL/action text into a
policy draft. Unsupported or invalid syntax rejects the import with its line
number; no partially understood policy is activated. In the panel, **Validate
and preview import** shows the converted JSON and warnings; **Add imported rules
to draft** updates the unsaved editor. Save that scope separately to activate
it. Full HAProxy `global`, `defaults`, `frontend`, `backend`, stick tables,
Lua and external files are not a supported configuration format.
The `http-request`, `http-response` and `http-after-response` prefixes map to
request-side, backend-response and final-response policy stages. Their exact
supported commands are checked by the importer. RustProxy-specific actions such
as `normalize-header` are extensions, not a promise of HAProxy compatibility.
Use JSON for the full native model, including inline maps and explicit stages.
| Imported form | Supported subset / difference |
|---|---|
| `acl name fetch ...` | `-i`, `-m str/sub/beg/end/reg/int/bool/ip/found`, numeric comparisons and multiple patterns; repeated definitions of one ACL are ORed |
| Conditions | `if`, `unless`, adjacent AND, `&&`, `or`/`\|\|`, `!`, inline `{ ... }`, and separated parenthesis tokens |
| Header commands | `set-header`, `add-header`, `del-header`, `replace-header`, `replace-value`; HAProxy replacement references `\1` are converted to the native regex replacement form |
| Target rewrite | `set-path`, `set-query`; imported request rewrites move to `pre_route` with an ordering warning |
| Backend target | `use_backend`, `use-server`, or extension `use-backend`; a target is a configured RustProxy member ID, and selection bypasses shared cache |
| Local response | `deny [deny_status N]`, `return status N [string BODY]`, `redirect location URL [code N]` |
| Variables/control | `set-var(txn.name) SAMPLE`, `set-var-fmt(txn.name) FORMAT`, `unset-var(txn.name)`, `allow` (ends the current scope's chain) |
| RustProxy extensions | `http-pre-route`, `http-backend-request`, `http-deliver`; `set-header-if-missing`, `normalize-header`, `merge-header`, `remove-value`, `cache-pass`, `cache-lookup`, `cache-no-store`, `cache-ttl`, `cache-grace`, `cache-hash-header`, `disable-compression`, `stop` |
Comments, quoted strings and continued lines are supported. Extension and
rewrite warnings must be reviewed before applying the returned draft.
`POST /api/policy/test` evaluates a supplied draft and request/response fixture
with the same compiled engine, returning matched/skipped rules and actions.
It does not contact a backend or store responses. Supply repeated headers as
separate fixture entries when testing full-field counts. A policy-only trace is
not a complete simulation of authentication, VCL, cache, routing or compression;
verify those interactions with real traffic.
The global policy is available at `GET/PUT /api/config/policy`, with the normal
configuration revision guard and administrator/API-token permissions. Import and
test endpoints use the normal administration authentication; they are not public
proxy routes. See [API](API.md) and the bundled OpenAPI for exact payloads.
`GET /api/policy/stats` returns active rules by scope with match and action-error
counts. The tester does not increment live counters. Counts reset when the
configuration recompiles; they are not a persistent traffic history.
Bounds per scope include 128 rules, 128 named ACLs, 16 maps, 1,024 total map
entries, 128 regex patterns and 256 KiB of serialized policy. A rule has 1–16
actions; condition groups have at most 32 children and nesting is bounded at 16.
Expression/regex expansion and transaction storage have additional limits.
The complete configuration still has its existing 2 MiB bound.
## Verification and upgrade
Configurations without `policy` preserve the existing VCL and header behavior.
An older binary rejects the new key: remove policy objects before downgrading,
or restore a pre-upgrade configuration snapshot. No cache format change is
required by the policy model. Changing a global policy invalidates applicable
cached representations; changing a Vhost/location policy changes that scope's
cache identity. An invalid reload leaves the previous complete configuration
active.
Run the Rust checks and regression tests from the source root:
```bash
./dev.sh check
./dev.sh test
cargo clippy --locked --all-targets -- -D warnings
```
Passing a policy fixture or a mock-origin unit test alone does not establish
production readiness. Test the built binary with your authentication provider,
protocols, existing VCL and actual origin responses before deployment.
+1
View File
@@ -16,6 +16,7 @@ Guides for operating RustProxy: installation, publishing services, security, cer
- [Installation and updates](INSTALL.md) — packages, source build, Docker image, first administrator, systemd and updates.
- [Configuration](CONFIGURATION.md) — SQLite or JSON configuration source, configuration map and changes that need a restart.
- [HTTP policy rules](POLICY.md) — named ACLs, maps, variables, HAProxy subset import, header/list operations, stage order and cooperation with existing VCL.
- [Headless mode](HEADLESS.md) — proxy and load balancer configured only from a JSON file, without the panel.
- [Troubleshooting](TROUBLESHOOTING.md) — symptom-based checks and a rollout checklist.
+15
View File
@@ -35,6 +35,21 @@ Transformations can run on eligible reverse-proxy and Web Server responses. When
## Custom and security headers
For conditional operations, named ACLs, full-field counts, regex replacement or
safe `Vary` list normalization, use [HTTP policy rules](POLICY.md) (0.42.0).
`backend_response` changes origin headers before cache planning; `deliver` runs
after VCL delivery and before compression; `after_response` runs after
compression and the existing dynamic header rules. Existing Custom Headers keep
their behavior. A normalization rule preserves all variant dimensions instead
of replacing them with a fixed list.
Configuring a `backend_response` policy, or adding a policy `hash_header`
dimension to a request, makes expired stale-while-revalidate objects use
foreground validation and disables proactive background refresh for that
request. Fresh HITs remain available. Foreground `304` validation uses
the same policy no-store/TTL decisions and existing VCL TTL/grace precedence.
See the policy guide for request-dependent cache bypass and explicit stale rules.
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)
+1 -1
View File
@@ -25,6 +25,6 @@ The backend editor groups connection/capacity settings separately from active he
Stream views/Overview include sessions, connections, traffic, rejected/errors and backend health/capacity when enabled. Counter reset or no-data state after service restart is normal.
The source package includes `scripts/start_stream_backends.sh`, `scripts/test_stream_tcp.py` and `scripts/test_stream_udp.py` for isolated test networks. Their mock selftests alone do **not** establish that RustProxy forwarding works; run end-to-end client traffic through the configured Stream listener.
Run end-to-end client traffic through the configured Stream listener in an isolated test network. Verify data transfer, idle timeouts and backend failover for the selected protocol.
If clients cannot connect, inspect listen IP/port, host firewall, TCP vs UDP selection, routing to the chosen backend, backend health and stream logs. See [Security](SECURITY.md) and [Monitoring](MONITORING.md).
+58 -3
View File
@@ -1,6 +1,6 @@
# VCL import: supported instructions and exact effects
This guide describes the VCL **subset implemented by RustProxy 0.39.2**, not the full Varnish Configuration Language. It is based on the VCL importer and cache-rule engine. Importing VCL **converts statements into graphical cache rules (which must then be saved)**; RustProxy does not execute arbitrary VCL text at request time. Unsupported instructions may be skipped with warnings or cause a parse error; they are not executed as Varnish code. **In the graphical importer, warnings pause conversion:** no rules are added until you explicitly choose **Add partial import (reviewed)**. Even after adding, you must separately save the configuration. The read-only VCL export is a human-oriented preview, **not** a lossless backup or a guaranteed re-importable VCL program.
This guide describes the VCL **subset implemented by RustProxy 0.42.0**, not the full Varnish Configuration Language. It is based on the VCL importer and cache-rule engine. Importing VCL **converts statements into graphical cache rules (which must then be saved)**; RustProxy does not execute arbitrary VCL text at request time. Unsupported instructions may be skipped with warnings or cause a parse error; they are not executed as Varnish code. **In the graphical importer, warnings pause conversion:** no rules are added until you explicitly choose **Add partial import (reviewed)**. Even after adding, you must separately save the configuration. The read-only VCL export for ordinary flat rules is a human-oriented preview, **not** a lossless backup or a guaranteed re-importable VCL program. Structured VCL imports use a JSON preview/export that preserves their control flow.
For a short operational reference inside the panel, open **Cache & VCL guide** from **Settings → Cache**, the ordinary **Vhost → Cache** editor or **Docker vhosts → Cache**. The same modal works in all three places; example VCL is pasted into the importer of the editor that opened the guide, and the modal labels that scope. The modal shows the current compatibility-mode, fallback-TTL and grace settings, explains `Vary` and header mutations with examples, and identifies unsupported Varnish hooks. It complements this exact syntax reference; it does not execute VCL or save settings.
@@ -8,6 +8,16 @@ For the **complete reference to all 42 quick-rule templates** (conditions, stage
## Where to import, rule order and activation
Since 0.42.0, optional [HTTP policy rules](POLICY.md) can cooperate with these
rules. Policy request edits run before `vcl_recv`/`vcl_hash`, policy backend
response edits run after existing `beresp` edits but before cache planning,
policy delivery runs after `vcl_deliver`, and `after_response` runs after
compression and legacy dynamic headers. Existing VCL order, local-over-global
priority and terminal return semantics are unchanged. Either engine's explicit
pass wins over lookup; existing VCL TTL/grace assignments take precedence over
policy assignments. New policy Global → Vhost → Location ordering does not
replace the VCL ordering described below.
- **Settings -> Cache -> Rules**: global cache rules, optionally targeted to particular vhosts.
- **Vhosts -> Cache -> Cache rules for this vhost**: rules for one vhost (ordinary or Docker-generated). **Ignore global cache rules** disables the global rules for that vhost.
- Imported rules and graphical rules use the same engine. Within each stage, **vhost rules run first**, followed by applicable global rules. A vhost edit to the same header or supported scalar setting wins over a conflicting global edit. In one scope, later matching edits win unless `stop`/`return(...)` terminates the stage.
@@ -63,17 +73,62 @@ The query-removal conversion accepts only the supported captured-separator `regs
## Recognized conditions and expressions
The corrected 0.42.0 importer records explicit branch selection. Each
`if`/`elsif`/`else` chain chooses its branch once when execution reaches it.
Changing or unsetting a condition's header inside that branch does not enter
its `else` or skip the remaining nested/tail statements. A later, independent
condition still reads the current, possibly modified headers. The same rule
applies in request, hash, backend-response and delivery hooks.
**Upgrade existing imports:** saved flat rules from an older importer retain
their existing behavior. Their JSON no longer contains enough information to
recover the original branch boundaries. Re-import the original VCL with 0.42.0,
review the draft tester, replace the old converted rules and save. Do not append
the new import while leaving the old actions enabled. Native graphical rules
do not require conversion.
| Form | Example | Notes |
|---|---|---|
| URL, method, request headers | `req.url ~ "^/assets/"`, `req.method == "GET"`, `req.http.Cookie` | `req.url` includes path and query; an unqualified request header tests presence. `bereq.url` and `bereq.http.X` are accepted as rule-request aliases. |
| Backend/delivery status and headers | `beresp.status == 200`, `beresp.http.Content-Type ~ "^text/"`, `resp.http.X-Flag` | Evaluated against the response at the relevant stage; earlier supported header mutations are visible to subsequent conditions. |
| Comparisons | `==`, `!=`, `~`, `!~` | Equality and regex matching for supported request/response variables. |
| Status comparisons | `beresp.status >= 500`, `resp.status < 400` | Also accepts `>`, `<=`, `==`, `!=`. |
| Branching | `if`, `elsif`, `else`, nested blocks, `&&`, `||`, `!`, parentheses | Branch guards are preserved in the generated rules, subject to the rule/condition limits. |
| Branching | `if`, `elsif`, `else`, nested blocks, `&&`, `||`, `!`, parentheses | The selected branch is retained in the generated control-flow group; independent later conditions observe earlier edits. Subject to rule/condition limits. |
`client.ip` with a Varnish ACL is **not imported**; the graphical rules have a client IP/CIDR condition instead. `include`, external modules, backend/ACL/probe definitions and custom subroutines are not loaded as executable configuration. Arbitrary functions, variables, string concatenation, dynamic header expressions, `pipe`, `restart`, `purge`, `synth` and hit-for-miss/hit-for-pass behavior are **not** implemented. Import is a conversion, not a promise of runtime Varnish equivalence.
Limits include a maximum VCL source of 256 KiB; the compiled cache-rule lists are limited to 128 rules, 16 conditions and 16 actions per rule. A complex boolean expression may expand to too many rules and be skipped with a warning. Use the graphical tester to verify the imported behavior.
Limits include 256 KiB of VCL source, 128 canonical rules per list (including
branch-entry markers), and 16 actions per rule. A branch has up to 128 OR
alternatives with 16 conditions each; an `if` chain has at most 16 branches.
A group permits 16 enclosing branch guards and 2,048 condition nodes in total.
The parser also limits nested blocks and unary/grouped expressions to depth 64.
Unsupported or excessive branches are skipped with warnings or rejected at
parsing/validation; review partial imports and use the graphical tester before
saving.
### Saved control flow and editor operations
Fresh imports carry optional `vcl_flow` metadata on their canonical cache rules.
The importer generates a versioned group ID, a zero-based `index`, the total
`count`, and references to earlier branch selections in `guards`. A branch-entry
rule has no actions; its `branches[].any` contains OR alternatives, each an AND
list of ordinary rule conditions. A final `[[]]` predicate represents `else`.
Action rules use the selected branch without re-evaluating its original guard.
Selection is private to the request, hook and configured scope, including when
the same import is used locally and globally.
Keep the complete import together. The panel moves, copies, enables, disables,
removes and assigns Vhosts to the whole group. Copies receive fresh group IDs.
Branch structure is read-only in the graphical editor; edit the original VCL
and replace its import to change that structure. The JSON preview/export keeps
the metadata, whereas the ordinary flat-rule VCL preview cannot represent it.
Configuration validation rejects incomplete or reordered groups, cross-hook
references, mixed enable/scope states and invalid branch ancestry before
activation. Rules without `vcl_flow` retain independent sequential evaluation.
New control-flow configurations require 0.42.0 or newer. For rollback, restore
the pre-upgrade configuration; deleting metadata would make guarded actions
unconditional. Keep the original VCL source alongside a full JSON backup.
## `Vary`: before or after the cache?
+11
View File
@@ -4,6 +4,11 @@
## Practical examples and traffic scenarios
The VCL subset below is preserved in 0.42.0. Optional [HTTP policy rules](POLICY.md)
add named ACLs, header counts, maps, variables and staged operations alongside
VCL, with explicit integration points. Those native capabilities are not new
VCL syntax and do not imply full Varnish compatibility.
The companion [VCL traffic cookbook](VCL_TRAFFIC_COOKBOOK.md) contains **12 VCL recipes and an additional Drupal 6 parent-domain example** (including an intentionally restricted importer example and a high-risk advanced example), an HTTP request/response behavior matrix, `curl` checks, expected `PASS`/`MISS`/`HIT` behavior and troubleshooting. The standalone source files are in [`examples/vcl/`](../examples/vcl/). They cover public catalogs, JSON APIs, private routes, CDN cookies, public static files, multilingual responses, A/B variants, SSE/webhooks/errors, safe header changes, query normalization and highly restricted Set-Cookie removal. Each example states its origin/privacy contract and importer limitations.
| Goal | Available through imported VCL | Native GUI/API required or not supported |
@@ -152,6 +157,12 @@ The shared cache stores **HTTP status 200** responses only in this release. A po
## 7. Graphical actions without a faithful imported VCL equivalent
The corrected 0.42.0 importer preserves selected branches when their headers
are changed or removed; forced cache also separates missing, empty and present
Cookie/Authorization values before lookup. Older flat VCL
conversions need re-import from their original source to gain branch selection;
native graphical rules keep their existing evaluation order.
These capabilities exist in RustProxy's JSON/graphical cache rules but should **not** be inferred to work by pasting arbitrary VCL syntax:
| Graphical rule/setting | VCL import limitation |
+5
View File
@@ -1,5 +1,10 @@
# Vhosts, domains and backends
Since 0.42.0, Vhosts and their custom locations can define optional
[HTTP policy rules](POLICY.md) for conditional headers, named ACLs, maps,
transaction variables and staged actions. These cooperate with existing VCL
and Custom Headers; their stage and scope order are documented separately.
A **Vhost** publishes one or more hostnames on named HTTP/HTTPS listeners. Its source can be an HTTP reverse-proxy backend pool or a reusable local Web Service. Use **Vhosts → Add** in the panel.
## Publish a site