18 KiB
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
policyin the complete configuration,vhosts[].policy, orvhosts[].routes[].policy. A Docker assignment stores its policy with that assignment so discovery does not discard the customization. - A policy contains
aclsandmapsobjects and an orderedrulesarray. Each rule has a uniqueid, astage, optionalwhen, and anactionsarray.nameis descriptive,enableddefaults totrue, andstopdefaults tofalse. 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 is suitable for a local headless test after adjusting its backend address. The cooperation example 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:
{
"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. 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:
{
"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:
{
"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:
- A policy
passand a VCLreturn(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. - Existing VCL
return(hash)still endsvcl_recvand still runsvcl_hash. Policy request-header changes are visible to that hash phase. Adding an internal hash dimension does not automatically add downstreamVary. That field must name the real client attributes that select a representation: the cooperation example mergesUser-AgentintoVary, since itsX-Deviceheader is created inside the proxy and is absent from browser requests. - 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
304validation. A no-store decision can serve the validated body for that request while discarding the object instead of publishing a refreshed cache entry. - 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.
- Delivery changes do not rewrite the stored object, its key, TTL or variants.
Every new policy edit to
Varyindeliverorafter_response, including generic set/remove/replace, must retain the existing dimensions and*. An edit that removes one or creates malformedVaryis skipped atomically and counted as an action error; the tester includes a warning. Manualbackend_responseedits 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 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:
./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.