Files
RustProxy/docs/POLICY.md
T
2026-11-28 15:54:56 +01:00

28 KiB
Raw Blame History

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 Docker Vhosts → service → HTTP policies for a Docker assignment. The shared editor offers a rule builder, scenario presets, a JSON view, import preview and a draft tester. Global settings use the same editor at settings?tab=policies. 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 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.

Scenario presets and the rule builder

Since 0.42.1, Scenario presets beside Add HTTP rule opens a searchable catalog grouped by headers, cache, security, routing and diagnostics. Select a scenario to read its purpose and application notes; Preview rules shows its policy data. Add scenario appends the complete scenario to the current draft with unique rule IDs. It keeps the existing rules, ACLs and maps. Nothing is activated until the containing Settings, Vhost, Docker assignment or location form is saved. The Documentation button in the editor toolbar opens this guide; Vhosts and global settings use the same control.

The catalog contains 40 scenarios built from 54 rules. Global and Vhost editors offer all 40. Location editors offer 39: the prefix rewrite uses pre_route, which runs before a location has been selected.

General scenarios

The following recipes create enabled draft rules, except the disabled legacy redirect. They still require saving the containing form to become active.

Scenario Effect and review points
Normalize Vary Normalize the final token list, keeping existing dimensions and *.
Exact duplicate Vary Match the two full fields in the original example and replace only that exact combination before cache planning.
Hide origin headers Remove Server, X-Powered-By and X-AspNet-Version from the final response.
Basic security headers Add X-Content-Type-Options: nosniff and Referrer-Policy: strict-origin-when-cross-origin only when missing; application-provided values remain in place.
Private routes Bypass shared lookup/storage and send private/no-store response headers on common account, administration and checkout paths. Adjust the path list.
Authorization bypass Bypass shared caching when an Authorization header is present and send private/no-store response headers.
Cookie bypass Bypass shared caching when a Cookie header is present and send private/no-store response headers. This also excludes anonymous requests with tracking cookies.
Responses with Set-Cookie Prevent storage of matching origin responses without deleting the cookie; send Cache-Control: private, no-store.
Error responses Prevent storage of origin responses with status 400–599; send Cache-Control: no-store on final error responses.
Health endpoints Keep common health/readiness paths out of shared caching and mark their responses no-store. Adjust the paths to match your service.
Server-sent events Bypass shared cache for Accept: text/event-stream; prevent storage and disable RustProxy compression for event-stream responses. This does not remove origin compression.
Block unwanted methods Return 403 for TRACE and CONNECT; review them against protocols used by the service.
Block sensitive files Return 403 for literal .env, .env.*, .git, .svn and .hg path segments. The pattern leaves .well-known available and does not cover all encoded aliases.
Request correlation Add the transaction request ID as X-Correlation-ID at final delivery when absent; preserve application correlation IDs.
Legacy path redirect Add a disabled exact /old-path → /new-path redirect with status 302. Edit the paths and enable the rule; this example drops the original query string.

Application and API scenarios

Off means the scenario is added with every rule disabled. Edit its example domains, paths, networks or values, enable the required rules, then save. Keep the order of a scenario containing several rules.

Scenario Added state Effect and review points
Language variants Off Merge Accept-Language into Vary before cache planning for /localized/; use only when the origin actually varies its response by that header.
CORS for one frontend Off On /api/, remove previous allowed-origin/credentials headers, allow the fixed https://app.example.test origin, and merge Origin into Vary for all matching responses.
CORS exposed headers On Merge ETag and X-Correlation-ID into Access-Control-Expose-Headers only when an allowed-origin response header already exists. Does not grant CORS access or create those diagnostic headers.
Internal redirect locations Off Replace the configured internal HTTP host in 3xx Location fields with a fixed public HTTPS host, preserving the captured path/query. Does not rewrite page content.
Download attachments Off Set Content-Disposition: attachment on successful responses under /downloads/; edit the path. No filename or access permission is generated.
Same-origin framing Off Add X-Frame-Options: SAMEORIGIN when missing. Review embedded applications and any existing CSP frame-ancestors directive.
Trial HSTS Off Add missing Strict-Transport-Security: max-age=300 only on the actual TLS listener; no includeSubDomains or preload. Verify HTTPS first.
Browser device permissions Off Add missing Permissions-Policy denying camera, microphone and geolocation; remove restrictions required by the application.
CSP report-only audit Off Add a missing report-only CSP for self-hosted resources, no objects and a self-only base URI. Review browser-console violations; no report endpoint is configured.
Staging noindex Off Send X-Robots-Tag: noindex, nofollow throughout the selected scope. This is crawler advice, not authentication.
Cross-site write requests Off Deny POST, PUT, PATCH and DELETE carrying Sec-Fetch-Site: cross-site. Keep application CSRF protection; clients without that header are unaffected.
JSON API writes Off Require exactly one Content-Type field declaring application/json or application/*+json for POST, PUT and PATCH below /api/, otherwise return 415. Missing or duplicate fields are rejected. This checks headers, not body validity.
Internal path by client network Off Deny /internal outside the configured trusted client-IP CIDR. Replace the example 203.0.113.0/24 and path before enabling.
Preview/draft query parameters Off Bypass lookup/storage and send private/no-store when literal preview or draft query names exist, even with empty or false values. Does not authorize draft access.
Signed/token URLs Off Bypass lookup/storage for configured literal signing/token query names. The application still validates the signature and expiry.
HTML revalidation On Add Cache-Control: no-cache only to HTML responses lacking Cache-Control. Existing privacy directives remain; the shared object's TTL is unchanged.
Public API TTL/grace Off Set 60-second TTL and 30-second grace defaults for explicitly public /api/public responses without Set-Cookie, private, no-cache or no-store. Requires enabled cache.
Canonical host Off Redirect a configured alias to a fixed HTTPS hostname with 308, preserving path, query and method. Edit both domains and verify the certificate.
HTTP to HTTPS for one host Off Redirect the configured host with 308 when received without TLS. Uses listener TLS, not forwarding headers; review external TLS termination to avoid loops.
Remove a path prefix Off Rewrite /legacy/… to /… in pre_route, retaining query parameters. Review routing/access for the resulting path; available globally and on Vhosts only.
Move a URL subtree Off Redirect /docs-old/… to /docs/… with 308, preserving the rest of the path, query and method. Edit the condition and replacement together.
Maintenance response Off Return a local 503 after access/authentication checks and add Retry-After: 300 using a transaction marker. Enable both rules together; the initial condition covers the whole scope.
Selected API backend Off Send /api-v2/ to an existing backend member ID. Set the real ID before enabling; backend selection bypasses shared cache. Global use requires that member in each affected Vhost.
Cache outcome header On Add missing X-Cache from cache_status at final delivery. Preserves an application header and does not change cache decisions.
API/web classification Off Set txn.ui_request_class to web or api, then expose it as X-Request-Class at delivery. Edit /api/ and retain all three rules in order; the label is not a trusted identity.

The CORS recipe configures response headers only. The application must handle OPTIONS preflight and authentication. The recipe does not allow credentialed browser requests or reflect an arbitrary request origin. Enable both rules together so every applicable response retains Vary: Origin.

The public-API TTL/grace recipe does not force cache lookup or weaken credential and storage privacy checks. Existing VCL TTL/grace assignments take precedence. Its backend-response stage retains the background-refresh restrictions below. no-cache in the HTML recipe means revalidation, not a prohibition on storage.

Presets are editable starting points; they do not install authentication or replace existing access rules. For global policies, review the effects across every affected Vhost. Response storage rules do not purge existing cache entries or run the backend-response stage on a HIT. Backend-response rules also retain the background-refresh restrictions described under cache boundaries. For the event-stream preset, clients must send Accept: text/event-stream to bypass any existing cache entry before the origin's response type is known.

Add and inspect conditions

Open a rule's conditions, enter a sample expression, choose an operator and enter one comparison value per line. Add condition commits those fields to the rule and updates its visible condition list/count. The initial sample is path with a prefix comparison; enter the intended path before adding it. Choose AND to require both the existing condition and the new comparison, or OR to allow either. Existing nested expressions remain grouped.

The builder checks for missing samples/values, invalid numeric values and condition/value limits before adding a comparison. exists takes no values; case-insensitive matching applies to text comparisons, not numeric, CIDR or existence tests. Advanced condition JSON remains available for nested AND/OR/NOT expressions and named ACL references. Invalid JSON must be corrected before switching views or applying changes that would rebuild the editor. The server still validates sample syntax, stage compatibility and the complete policy before activation.

Action choices follow the selected stage. Stop this scope's stage after matching has its own row below the stage settings; it ends only the matching scope's chain at that stage. Policy on/off controls follow Show on/off settings as switches in Appearance, including dynamically added rules and conditions. The same behavior applies in global settings, Vhosts, Docker assignments and locations.

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:

  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 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.