Policy reference¶
ReferenceFacts to look up.
Generated from the policy catalogue in the binary, so it cannot drift from what the gateway runs. The console's Policy catalogue shows the same information.
Apinx — Policy Reference¶
Generated from the policy catalogue (go test ./src/internal/policy -run Reference -args -update). Do not edit by hand.
Policies attach to routes through policies: bindings at four levels: global, environment, API and route (FR-4.13), plus the product level the control plane adds for APIs in a product, and through named shared flows attached to an API or a route, which merge before that level's own bindings (ADR-0012, ADR-0015; see GATEWAY-CONFIG.md). A binding at a narrower level combines with the same policy inherited from a wider one according to its strategy: override (default) replaces the inherited settings, merge changes only the settings given, append runs both. enabled: false switches an inherited policy off at that level. Whatever order bindings are written in, policies run in phase order: the table below is that order. The exception is the environment flow hooks (ADR-0017): shared flows hooked on the client side run first on the request and last on the response, those hooked on the backend side run last before the backend and first on its answer, and no API or route can change or switch them off.
Durations are strings with a unit (30s, 5m, 1h); sizes accept a unit too (64KB, 1MB).
| Phase | Type | Name | Category | Summary |
|---|---|---|---|---|
| 50 | lifecycle |
Lifecycle | lifecycle | Deprecation and retirement of an API version. |
| 100 | ip-filter |
IP filter | protection | Allow or deny callers by IP address or CIDR range. |
| 110 | cors |
CORS | protection | Answer browser cross-origin requests. |
| 120 | allow-methods |
Allowed methods | protection | Restrict the HTTP methods a route accepts. |
| 150 | forward |
Forward only | protection | Forward only the listed client headers and query parameters to the backend. |
| 200 | request-size-limit |
Request size limit | protection | Reject request bodies larger than a limit. |
| 205 | require-headers |
Required headers | protection | Refuse requests that lack a header or send a value outside an allowed set. |
| 205 | threat-protection |
Threat protection | protection | Refuse hostile payloads: oversized or deeply nested JSON and XML, XXE, and injection patterns. |
| 210 | deny |
Deny | protection | Reject every request with a fixed status. |
| 210 | validate |
Request validation | protection | Refuse requests that do not match a JSON Schema. |
| 300 | api-key |
API key | authentication | Require an API key issued to an application. |
| 300 | basic |
Basic authentication | authentication | Require HTTP Basic credentials from a fixed list of users. |
| 300 | jwt |
JWT | authentication | Validate JWT access tokens from an identity provider. |
| 300 | oauth2 |
Apinx access token | authentication | Accept access tokens issued by this gateway to its applications. |
| 400 | subscription |
Product subscription | authorization | Only applications subscribed to a product that includes this operation, within their plan's limits. |
| 500 | rate-limit |
Rate limit | traffic | Limit how many requests a caller may make per time window. |
| 510 | concurrency-limit |
Concurrency limit | traffic | Bound the number of requests in flight at once. |
| 590 | mock-response |
Mock response | composition | Answer the request from the gateway with a fixed response; no backend needed. |
| 600 | cache |
Response cache | caching | Serve repeated responses from memory. |
| 650 | normalize-errors |
Normalize errors | errors | Replace backend error bodies with the uniform Apinx error format. |
| 690 | service-callout |
Service callout | composition | Call other backends during a request and stitch their answers in. |
| 700 | transform |
Transform | transformation | Rewrite headers, path, query, JSON bodies and the response status. |
| 705 | upstream-auth |
Backend authentication | authentication | Authenticate the gateway to the backend with an OAuth 2 token it obtains and caches. |
| 710 | set-header |
Set header | transformation | Set fixed headers on the request and the response. |
| 720 | compress |
Response compression | transformation | Compress responses the caller accepts compressed. |
| 720 | soap |
SOAP backend | composition | Publish one operation of a SOAP backend as a JSON operation. |
Accepted values¶
Settings that take one of a fixed set of values, across all policies. Every other setting is a free string, a number, a boolean (true, false), a duration (30s, 5m, 1h), a size (64KB, 1MB) or a list of those.
| Policy | Setting | Accepted values | Default |
|---|---|---|---|
lifecycle |
state |
deprecated, retired |
|
api-key |
in |
header, query, cookie |
header |
jwt |
from |
header, query, cookie |
header |
oauth2 |
from |
header, query, cookie |
header |
rate-limit |
algorithm |
sliding_window, token_bucket, fixed_window |
sliding_window |
rate-limit |
key |
consumer, ip, route, header |
consumer |
concurrency-limit |
key |
route, consumer, ip |
route |
service-callout |
callouts.method |
GET, HEAD, POST, PUT, PATCH, DELETE |
GET |
service-callout |
callouts.when |
before, after |
after |
service-callout |
run_after_on |
success, always |
success |
transform |
request.method |
GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS |
|
transform |
request.body.if_not_json |
pass, reject |
pass |
transform |
response.body.if_not_json |
pass, reject |
pass |
upstream-auth |
request |
form, json |
form |
upstream-auth |
grant |
client_credentials, password |
client_credentials |
upstream-auth |
client_auth |
basic, body |
basic |
compress |
level |
fast, default, best |
default |
soap |
version |
1.1, 1.2 |
1.1 |
soap |
security |
none, username_token |
none |
soap |
password_type |
text, digest |
text |
soap |
response.attributes |
drop, keep |
drop |
soap |
response.types |
string, infer |
string |
lifecycle¶
Lifecycle — Deprecation and retirement of an API version. · phase 50 · lifecycle · acts on responses
Bound automatically on the routes of a deprecated or retired API version. Deprecated: answers carry Deprecation, Sunset (when a date is set) and Link to the successor version. Retired: every call gets 410 APX-PL-0024 with the same headers, before any other policy runs.
| Setting | Type | Default | Description |
|---|---|---|---|
state |
deprecated | retired | Set by the control plane from the API's lifecycle. | |
since |
string | When the version was deprecated (RFC 3339). | |
sunset |
string | When it is or was retired (RFC 3339). | |
successor |
string | The successor version's API name. | |
successor_path |
string | The successor's base path, for the Link header. | |
successor_header |
string | The header that selects the successor on the same base path (Api-Version: v2). | |
note |
string | A message for callers. |
ip-filter¶
IP filter — Allow or deny callers by IP address or CIDR range. · phase 100 · protection
Deny entries win over allow entries. When an allow list is present, only listed addresses pass. Addresses are taken from the connection unless the gateway is told to trust X-Forwarded-For from known proxies.
| Setting | Type | Default | Description |
|---|---|---|---|
allow |
list | Addresses or CIDR ranges allowed; empty means everyone not denied. | |
deny |
list | Addresses or CIDR ranges rejected. | |
trust_x_forwarded_for |
boolean | false |
Use the client address from X-Forwarded-For. Enable only when a trusted proxy in front of the gateway sets it. |
trusted_proxies |
list | Addresses or CIDR ranges of the proxies in front of the gateway. Their X-Forwarded-For entries are skipped when finding the client; the rightmost other entry is the caller. Empty takes the last entry, the one your proxy added. |
cors¶
CORS — Answer browser cross-origin requests. · phase 110 · protection · acts on responses
Handles preflight OPTIONS requests at the gateway and adds Access-Control headers to responses for allowed origins. Runs before authentication so preflights, which carry no credentials, are answered.
| Setting | Type | Default | Description |
|---|---|---|---|
origins |
list | * |
Allowed origins, e.g. https://app.example.com. * allows any origin (without credentials). |
methods |
list | GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS |
Methods a browser may use. |
headers |
list | Request headers a browser may send. Empty echoes whatever the preflight asks for. | |
exposed_headers |
list | Response headers scripts may read. | |
credentials |
boolean | false |
Allow cookies and Authorization headers. Requires explicit origins. |
max_age |
duration | 10m |
How long browsers may cache the preflight answer. |
reject_unknown_origin |
boolean | false |
Reject requests from origins not in the list with 403 instead of leaving enforcement to the browser. |
allow-methods¶
Allowed methods — Restrict the HTTP methods a route accepts. · phase 120 · protection
Requests with any other method are answered 405 with an Allow header. Useful when a catch-all route should be read-only.
| Setting | Type | Default | Description |
|---|---|---|---|
methods (required) |
list | Permitted methods, e.g. GET, HEAD. |
forward¶
Forward only — Forward only the listed client headers and query parameters to the backend. · phase 150 · protection
Zero-trust forwarding: the backend receives only the headers and query parameters named here, plus what the gateway sets itself (its identity headers, Via, X-Forwarded-) and what a transform or set-header policy adds. Everything else the client sent is dropped before the backend is called, after authentication has read it: an api-key or jwt policy still sees Authorization even when it is not listed. Content-Type, Content-Length, Content-Encoding and Transfer-Encoding always pass, the body would be unreadable without them. Without a headers list no client header passes; without a query list every query parameter passes, since the query is usually part of the API's contract. Use "" to pass everything on one side.
| Setting | Type | Default | Description |
|---|---|---|---|
headers |
list | Client headers the backend may receive, by name (case does not matter). Empty: none. "*": all. | |
query |
list | * |
Query parameters the backend may receive, by name. "*" (default): all. Empty list: none. |
policies:
- config:
headers:
- Accept
- Accept-Language
- If-None-Match
- X-Request-Id
query:
- page
- size
- sort
type: forward
request-size-limit¶
Request size limit — Reject request bodies larger than a limit. · phase 200 · protection
A declared Content-Length above the limit is rejected before anything is read. Bodies without a declared length are cut off when they exceed the limit and the request fails with 413 instead of reaching the backend in full.
| Setting | Type | Default | Description |
|---|---|---|---|
max_bytes (required) |
size | Largest accepted body, e.g. 1MB, 64KB or 1048576. |
require-headers¶
Required headers — Refuse requests that lack a header or send a value outside an allowed set. · phase 205 · protection
A contract check at the edge, before any backend sees the request: every listed header must be present, and when values are listed, must carry one of them. Typical uses are a language header a mobile app must send (Accept-Language: ar or en), a client version, or a tenant header. A request that fails is answered 400 APX-PL-0027 naming the header and the allowed values.
| Setting | Type | Default | Description |
|---|---|---|---|
required (required) |
map | Header name to the list of allowed values. An empty list requires the header to be present with any value. | |
case_insensitive |
boolean | true |
Compare values ignoring case (AR and ar are the same). |
threat-protection¶
Threat protection — Refuse hostile payloads: oversized or deeply nested JSON and XML, XXE, and injection patterns. · phase 205 · protection
Checks each request before any backend sees it. JSON and XML bodies are inspected as they are read, against structural limits (depth, sizes, lengths); XML DTDs and entity declarations are refused, closing XXE and billion-laughs attacks. The path, the query, header values and, if you choose, the body are checked against injection patterns: a bundled set for SQL injection, script injection, path traversal and command injection, plus your own. Bodies can have a size limit per content type. Every rule has a safe default, so the policy works without settings. Compressed bodies (gzip, deflate) are inspected decompressed and forwarded as they came; other encodings are refused. A body that is JSON or XML gets the structural limits whatever its declared type. Pattern matching reads JSON strings decoded and form fields unescaped, and scans the headers as one text, one header per line.
| Setting | Type | Default | Description |
|---|---|---|---|
max_body_bytes |
size | 1MB |
Largest body inspected and accepted for any content type without its own limit. |
content_types |
map | Body size limits per media type, e.g. application/json: 256KB, multipart/form-data: 10MB. A type/* entry covers a family. | |
json.max_depth |
integer | 20 |
Deepest nesting of objects and arrays. |
json.max_object_entries |
integer | 1000 |
Most keys in one object. |
json.max_array_length |
integer | 10000 |
Most items in one array. |
json.max_string_length |
integer | 65536 |
Longest string value, in bytes. |
json.max_key_length |
integer | 256 |
Longest object key, in bytes. |
xml.max_depth |
integer | 20 |
Deepest element nesting. |
xml.max_elements |
integer | 10000 |
Most elements in the document. |
xml.max_attributes |
integer | 50 |
Most attributes on one element. |
xml.max_name_length |
integer | 256 |
Longest element or attribute name. |
xml.max_text_length |
integer | 65536 |
Longest text or attribute value, in bytes. |
xml.allow_dtd |
boolean | false |
Accept documents with a DTD. Entities are never expanded; keep this off unless a client cannot avoid a DOCTYPE. |
patterns.defaults |
boolean | true |
Use the bundled patterns: sql-injection, script-injection, path-traversal, command-injection. |
patterns.disable |
list | Bundled patterns to leave out, by name. | |
patterns.custom |
map | Your own patterns: a name and a regular expression (RE2), e.g. internal-host: (?i)corp.internal. A pattern costs time for every character it reads, more for wide counted repeats such as {1,200}: a value too long for your patterns to read in about 200 ms is refused 413 APX-PL-0039, never let through unchecked. | |
patterns.in |
list | path, query, headers |
Where to look: path, query, headers, body. |
patterns.skip_headers |
list | Authorization, Cookie, User-Agent |
Header values not checked (credentials and free text). |
policies:
- config:
json:
max_depth: 10
max_body_bytes: 1MB
patterns:
in:
- path
- query
- headers
- body
type: threat-protection
deny¶
Deny — Reject every request with a fixed status. · phase 210 · protection
Takes a route offline deliberately, for maintenance or while a backend is being replaced. Nothing reaches the upstream.
| Setting | Type | Default | Description |
|---|---|---|---|
status |
integer | 403 |
HTTP status to answer with, 400 to 599. |
message |
string | Forbidden |
Plain-text body. |
validate¶
Request validation — Refuse requests that do not match a JSON Schema. · phase 210 · protection
Checks the request against JSON Schema (draft 2020-12): the JSON body, and the query, headers and path parameters as objects whose values are converted to the types the schema declares (integer, number, boolean, arrays of them). A request that fails is answered 400 with the violations (where and why), and never reaches the backend. Schemas may be written here or come from an imported OpenAPI document, which fills this policy in per operation. Compiled once when published.
| Setting | Type | Default | Description |
|---|---|---|---|
body |
code | JSON Schema the request body must match, for the listed content types. A request without a body passes unless require_body is set. | |
query |
code | JSON Schema of an object whose properties are the query parameters (a repeated or comma-separated parameter is an array when the property says so). | |
headers |
code | JSON Schema of an object whose properties are request headers, by name. | |
path |
code | JSON Schema of an object whose properties are the operation's path parameters. | |
content_types |
list | application/json |
Media types the body schema applies to, by prefix; a body of another type passes untouched. |
require_body |
boolean | false |
Refuse a request without a body when a body schema is set. |
max_body_bytes |
size | 1MB |
Largest body read for validation; a larger one is refused with 413. |
policies:
- config:
body:
properties:
quantity:
minimum: 1
type: integer
sku:
minLength: 1
type: string
required:
- sku
- quantity
type: object
query:
properties:
limit:
maximum: 100
type: integer
type: object
type: validate
api-key¶
API key — Require an API key issued to an application. · phase 300 · authentication
The key is looked up in the Consumers directory; revoked or expired keys are refused on the next request. The application becomes the caller's identity for rate limiting and for the backend. Keys are created and rotated under Consumers.
| Setting | Type | Default | Description |
|---|---|---|---|
in |
header | query | cookie | header |
Where the key is sent. |
name |
string | X-API-Key |
Header, query parameter or cookie name. |
allow_applications |
list | Only these applications (by name) may call the route. Empty allows any application with a valid key. | |
strip |
boolean | true |
Remove the key before forwarding to the backend. |
forward_identity |
boolean | true |
Send X-Apinx-Application and X-Apinx-Application-Id to the backend. |
trust_x_forwarded_for |
boolean | false |
For applications limited to source addresses (Consumers): take the client address from X-Forwarded-For. Enable only behind a trusted proxy. |
trusted_proxies |
list | Addresses or CIDR ranges of the proxies in front of the gateway. Their X-Forwarded-For entries are skipped when finding the client; the rightmost other entry is the caller. Empty takes the last entry, the one your proxy added. |
basic¶
Basic authentication — Require HTTP Basic credentials from a fixed list of users. · phase 300 · authentication
For internal tools and legacy clients. Passwords are stored as argon2id hashes; a plain password given in the configuration is hashed when the configuration compiles and never stored in clear. Verified credentials are cached briefly so the hash is not recomputed on every request.
| Setting | Type | Default | Description |
|---|---|---|---|
users (required) |
list | Entries of the form {username, password} or {username, password_hash}. | |
realm |
string | apinx |
Realm shown in the browser's credential prompt. |
strip |
boolean | true |
Remove the Authorization header before forwarding. |
forward_identity |
boolean | true |
Send X-Apinx-Subject with the username to the backend. |
jwt¶
JWT — Validate JWT access tokens from an identity provider. · phase 300 · authentication
Verifies signature, issuer, audience, expiry and not-before locally against the provider's published keys (JWKS), fetched and cached by the gateway, or against keys given inline. By default the key set is found from the issuer through OpenID Connect discovery. Scopes and claims can be required for authorization. Works with any OpenID Connect or OAuth 2 provider. For tokens this gateway issues to its own applications, use the oauth2 policy (Apinx access token) instead; bound together, either token is accepted.
| Setting | Type | Default | Description |
|---|---|---|---|
issuer (required) |
string | Expected iss claim, e.g. https://login.example.com/. Without jwks_url, jwks or hmac_secret it must be the provider's https:// address: the keys are found from |
|
audiences |
list | Accepted aud values; the token must carry at least one. Empty skips the audience check. | |
jwks_url |
string | URL of the provider's JSON Web Key Set. Leave empty to discover it from the issuer. | |
allow_http |
boolean | false |
Accept a plain http:// URL beyond this machine. What is fetched or sent then travels in clear; only for an isolated network. |
jwks |
string | Inline JSON Web Key Set, for providers without a reachable URL. | |
hmac_secret (secret) |
string | Shared secret for HS256/384/512 tokens. Prefer asymmetric keys. | |
algorithms |
list | RS256, ES256 |
Allowed signing algorithms. Tokens using any other are rejected. |
from |
header | query | cookie | header |
Where the token is sent. header expects Authorization: Bearer |
name |
string | Header, query parameter or cookie name. Default Authorization for header, access_token otherwise. | |
required_scopes |
list | Every listed scope must be present in the scope (or scp) claim. | |
required_claims |
map | Claim name to required value, or to a list of acceptable values. An empty list requires the claim to be present with any value. | |
leeway |
duration | 30s |
Clock skew tolerated on exp and nbf; at most 5m. |
cache_ttl |
duration | 10m |
How long fetched keys, and the key set address discovered from the issuer, are used before refreshing. |
strip |
boolean | true |
Remove the token before forwarding to the backend. |
forward_identity |
boolean | true |
Send X-Apinx-Subject with the token subject to the backend. |
policies:
- config:
audiences:
- orders-api
issuer: https://login.example.com/
required_scopes:
- orders:read
type: jwt
oauth2¶
Apinx access token — Accept access tokens issued by this gateway to its applications. · phase 300 · authentication
Applications obtain a token at this environment's /oauth2/token with their client ID and secret (Consumers → Client credentials), and keep it fresh with refresh tokens. The gateway verifies the RS256 signature with its own keys, without a network call, and refuses a token whose application, secret or session was revoked. The application becomes the caller's identity for limits, products, plans and the backend, as with an API key. Bind it together with api-key or jwt to accept either credential.
| Setting | Type | Default | Description |
|---|---|---|---|
required_scopes |
list | Every listed scope must be in the token. Scopes are granted per application under Consumers. | |
allow_applications |
list | Only these applications (by name) may call the route. Empty allows every application of the environment. | |
from |
header | query | cookie | header |
Where the token is sent. header expects Authorization: Bearer |
name |
string | Header, query parameter or cookie name. Default Authorization for header, access_token otherwise. | |
leeway |
duration | 30s |
Clock skew tolerated on exp and nbf; at most 5m. |
strip |
boolean | true |
Remove the token before forwarding to the backend. |
forward_identity |
boolean | true |
Send X-Apinx-Application, X-Apinx-Application-Id and X-Apinx-Subject to the backend. |
trust_x_forwarded_for |
boolean | false |
For applications limited to source addresses: take the client address from X-Forwarded-For. Enable only behind a trusted proxy. |
trusted_proxies |
list | Addresses or CIDR ranges of the proxies in front of the gateway, as on the api-key policy. |
subscription¶
Product subscription — Only applications subscribed to a product that includes this operation, within their plan's limits. · phase 400 · authorization · acts on responses
Bound automatically on every route of an API that belongs to a product; switch it off on a route to make that route public. The calling application must hold an active subscription to one of the products that offer the operation (403 APX-PL-0015 otherwise, also when products offer some operations of the API and none offers this one; APX-PL-0016 while pending or suspended). The plan's rate limit (429 APX-PL-0007) and daily or monthly quota (429 APX-PL-0017) count per subscription across everything the product offers. Responses carry RateLimit-* and X-Quota-Limit, X-Quota-Remaining and X-Quota-Reset.
| Setting | Type | Default | Description |
|---|---|---|---|
api |
string | The API this binding protects (set by the control plane). | |
plans |
map | Plans of the products that offer the operation, keyed product/plan, with their rate_limit and quota (set by the control plane). Empty: no product offers it, so every call is refused. | |
operation |
string | Set by the control plane when no product offers this operation of an offered API; named in the refusal. | |
closed_since |
string | Set by the control plane on a deprecated API version: subscriptions made after this time (RFC 3339) do not reach it (403 APX-PL-0025). | |
successor |
string | The version such subscribers should call instead. |
rate-limit¶
Rate limit — Limit how many requests a caller may make per time window. · phase 500 · traffic · acts on responses
Counts requests per key and answers 429 with Retry-After once the limit is reached. Every response carries RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset. Counters are exact on one instance; with redis.address configured they are shared by every instance (see shared). Runs after authentication so limits can be per application. Bound on an API or wider, the counter is shared by every operation it covers; bound on one operation, it counts that operation alone.
| Setting | Type | Default | Description |
|---|---|---|---|
limit (required) |
integer | Requests allowed per window. | |
window |
duration | 1m |
Length of the window, e.g. 1s, 1m, 1h. |
algorithm |
sliding_window | token_bucket | fixed_window | sliding_window |
sliding_window smooths bursts across window edges; token_bucket allows a burst then a steady rate; fixed_window resets on the clock. |
burst |
integer | token_bucket only: bucket capacity. Default: limit. | |
key |
consumer | ip | route | header | consumer |
What the counter is per: the authenticated application or subject (falling back to IP), the client IP, the whole route, or a header value. At most 262,144 distinct keys are tracked per instance; beyond that the least recently seen are forgotten. |
header_name |
string | key: header only: the header whose value identifies the caller. | |
trust_x_forwarded_for |
boolean | false |
Use the client address from X-Forwarded-For for ip keys. Enable only behind a trusted proxy. |
trusted_proxies |
list | Addresses or CIDR ranges of the proxies in front of the gateway. Their X-Forwarded-For entries are skipped when finding the client; the rightmost other entry is the caller. Empty takes the last entry, the one your proxy added. | |
status |
integer | 429 |
Status returned when the limit is reached. |
shared |
boolean | Count across every instance through Redis (redis.address). Default: on when Redis is configured, off otherwise. false keeps this limit on each instance alone, without the Redis round trip. Without Redis the limit counts per instance either way; when Redis cannot be reached, the instance counts alone until it is back. |
concurrency-limit¶
Concurrency limit — Bound the number of requests in flight at once. · phase 510 · traffic
Protects a backend from spikes: when the limit is reached, further requests wait for a slot up to queue_timeout, then are answered 503 with Retry-After. A slot is released when the response completes, whatever happened. The bound is per instance; with redis.address configured it is shared by every instance (see shared). Bound on an API or wider, the slots are shared by every operation it covers; bound on one operation, it bounds that operation alone.
| Setting | Type | Default | Description |
|---|---|---|---|
max (required) |
integer | Maximum concurrent requests per key. | |
key |
route | consumer | ip | route |
Whether the bound applies to the whole route, per authenticated caller, or per client IP. |
queue_timeout |
duration | 0s |
How long a request may wait for a slot. 0 rejects immediately. |
trust_x_forwarded_for |
boolean | false |
Use the client address from X-Forwarded-For for ip keys. Enable only behind a trusted proxy. |
trusted_proxies |
list | Addresses or CIDR ranges of the proxies in front of the gateway. Their X-Forwarded-For entries are skipped when finding the client; the rightmost other entry is the caller. Empty takes the last entry, the one your proxy added. | |
shared |
boolean | Bound the requests in flight across every instance through Redis (redis.address). Default: on when Redis is configured, off otherwise. false keeps the bound per instance, without the Redis round trip. A slot held longer than two minutes frees itself; when Redis cannot be reached, the instance bounds its own requests until it is back. |
mock-response¶
Mock response — Answer the request from the gateway with a fixed response; no backend needed. · phase 590 · composition
The gateway answers with the status, headers and body given here and never calls a backend. A route whose operations all carry a mock-response policy may have no upstream at all. The body may use the references transformations know (${path.id}, ${query.page}, ${header.X-Request-Id}, ${claim.sub}), so a mock can echo what was asked. Policies before it still run: a mocked operation keeps its API key, its rate limit and its CORS headers, and the request inspector shows the answer as the policy's. An optional delay imitates a slow backend for demos and client timeouts; it is capped at 5 seconds.
| Setting | Type | Default | Description |
|---|---|---|---|
status |
integer | 200 |
HTTP status of the answer, 100 to 599. |
body |
code | Body text; references are expanded. Empty answers with no body. | |
content_type |
string | Content-Type of the body. Default: application/json when the body is JSON, text/plain otherwise. | |
headers |
map | Extra response headers, name to value; values may use references. | |
delay |
duration | 0s |
Wait this long before answering, at most 5s. |
policies:
- config:
body: '{"id": "${path.id}", "name": "Sample order", "status": "shipped"}'
status: 200
type: mock-response
cache¶
Response cache — Serve repeated responses from memory. · phase 600 · caching · acts on responses
Stores cacheable responses in the gateway's memory for a time to live and answers repeats without calling the backend. The key is method, host, path, query and any listed headers, and the request headers the backend names in Vary. Unless vary_by_consumer is false, each caller has entries of its own: by the identity the gateway authenticated and by every credential the request still carries to the backend (Authorization, Cookie and other key or token headers), and a caller the gateway cannot name is not cached at all. Cache-Control: no-store and private responses, responses that set cookies or say Vary: *, and answers from a route's canary are never stored. Purge a route or an API from the Admin API or the console when the backend data changes.
| Setting | Type | Default | Description |
|---|---|---|---|
ttl |
duration | 60s |
How long an entry is served. |
methods |
list | GET, HEAD |
Methods eligible for caching. |
statuses |
list | 200, 203, 204, 300, 301, 404, 410 |
Response statuses stored. |
include_query |
boolean | true |
Include the query string in the key. |
key_headers |
list | Request headers whose values become part of the key, e.g. Accept-Language. | |
vary_by_consumer |
boolean | true |
Keep separate entries per caller, so one user's answer is never served to another: per authenticated identity, and per credential the request carries on to the backend (a browser's cookies included). Set false only for responses that are the same for everyone; one entry then serves every caller. |
max_object_bytes |
size | 1MB |
Largest response body stored. |
respect_cache_control |
boolean | true |
Honour no-store, private and max-age=0 from the backend. |
coalesce |
duration | 2s |
When many callers ask for an entry that is not stored, one of them calls the backend and the others wait for that answer, at most this long, before calling the backend themselves. 0s turns it off: every caller of a missing entry calls the backend. At most 30s. |
normalize-errors¶
Normalize errors — Replace backend error bodies with the uniform Apinx error format. · phase 650 · errors · acts on responses
Backends leak stack traces, HTML error pages and inconsistent JSON. This policy keeps the backend's status but replaces the body with application/problem+json carrying a stable code, the correlation id and optional remediation, the same shape the gateway uses for its own errors.
| Setting | Type | Default | Description |
|---|---|---|---|
statuses |
list | 5xx |
Which responses to normalise: exact codes (502) or classes (4xx, 5xx). |
message |
string | Override the message shown to clients. | |
keep_upstream_body |
boolean | false |
Include the first 512 bytes of the backend body in details.upstream_body. Only for development. |
verbose |
boolean | false |
Include remediation text in the body. |
service-callout¶
Service callout — Call other backends during a request and stitch their answers in. · phase 690 · composition · acts on responses
One API answers from several backends: each callout calls an HTTP backend, before the main backend (a lookup that shapes the request or refuses it) or after it (an enrichment stitched into the answer), and leaves the answer in a named slot. Callouts of one phase run in parallel; after names the ones that must finish first. Slots are read by transform's jq programs as .callouts.
| Setting | Type | Default | Description |
|---|---|---|---|
callouts (required) |
list | The calls, one card each. | |
deadline |
duration | 5s |
Wall clock for all callouts of one request, both phases together, within the route's total timeout. On Apinx Cloud the plan's cap applies when lower. |
allow_http |
boolean | false |
Accept a plain http:// URL beyond this machine. What is fetched or sent then travels in clear; only for an isolated network. |
secrets (secret) |
map | Named secrets for the other backends (an API key, a token), stored encrypted; referenced as ${secret. |
|
set_headers |
map | Headers for the main backend, set after the before phase; values may use every reference, ${callout. |
|
reject |
list | Refusal rules evaluated after the before phase: the first true condition answers the caller with its status and message (APX-PL-0031). | |
run_after_on |
success | always | success |
success: the after phase runs when the backend answered below 400. always: on every backend answer. It never runs on the gateway's own errors. |
respond.status |
integer | 200 |
HTTP status of the composed answer. |
respond.program |
code | jq program whose single output, as JSON, is the body; its input is the request document with .callouts. Empty: the body is an object with one member per callout, named after it, holding the answer's body (null when it failed). | |
respond.content_type |
string | application/json |
Content-Type of the answer. |
respond.headers |
map | Extra response headers, name to value; values may use references. |
policies:
- config:
callouts:
- headers:
X-API-Key: ${secret.customers_key}
name: customer
retries: 1
timeout: 800ms
url: https://customers.internal/v1/customers/${response.body.customer_id}
- name: shipping
optional: true
url: https://shipping.internal/v1/shipments?order=${path.id}
- after:
- customer
name: loyalty
url: https://loyalty.internal/v1/tiers/${callout.customer.body.tier}
deadline: 3s
secrets:
customers_key: env:CUSTOMERS_KEY
type: service-callout
transform¶
Transform — Rewrite headers, path, query, JSON bodies and the response status. · phase 700 · transformation · acts on responses
Header, path and query values may reference the request with ${path.}, ${header.
| Setting | Type | Default | Description |
|---|---|---|---|
request.method |
GET | HEAD | POST | PUT | PATCH | DELETE | OPTIONS | Forward the request with this HTTP method, e.g. GET for a POST the client sent. GET and HEAD send no body: carry its fields in the query with ${body. |
|
request.headers.set |
map | Headers to set, replacing any existing value. | |
request.headers.add |
map | Headers to add, keeping existing values. | |
request.headers.remove |
list | Header names to remove. | |
request.headers.rename |
map | Old name to new name. | |
request.path.strip_prefix |
string | Literal prefix to remove from the path. | |
request.path.add_prefix |
string | Literal prefix to prepend to the path. | |
request.path.replace.pattern |
string | Go regular expression matched against the path. A path too long for the pattern to read in about 200 ms is refused 413 APX-PL-0039, not forwarded unrewritten. | |
request.path.replace.with |
string | Replacement; $1 refers to the first group. | |
request.query.set |
map | Parameters to set. | |
request.query.add |
map | Parameters to add. | |
request.query.remove |
list | Parameters to remove. | |
request.body.program |
code | jq program that produces the new body. Its input is {body, headers, header_values, method, path, query, params, principal, client_ip, host, route, api}; on the response leg also status and request_headers. It must produce exactly one value. | |
request.body.if_not_json |
pass | reject | pass |
A body that is not JSON is passed through untouched (pass) or refused: 400 APX-PL-0012 on the request, 502 APX-PL-0014 on the response. |
request.body.max_bytes |
size | 1MB |
Largest body buffered and produced. A larger request body is refused with 413; a larger backend body becomes a 502. |
response.headers.set |
map | Headers to set, replacing any existing value. | |
response.headers.add |
map | Headers to add, keeping existing values. | |
response.headers.remove |
list | Header names to remove. | |
response.headers.rename |
map | Old name to new name. | |
response.body.program |
code | jq program that produces the new body. Its input is {body, headers, header_values, method, path, query, params, principal, client_ip, host, route, api}; on the response leg also status and request_headers. It must produce exactly one value. | |
response.body.if_not_json |
pass | reject | pass |
A body that is not JSON is passed through untouched (pass) or refused: 400 APX-PL-0012 on the request, 502 APX-PL-0014 on the response. |
response.body.max_bytes |
size | 1MB |
Largest body buffered and produced. A larger request body is refused with 413; a larger backend body becomes a 502. |
response.status.set |
integer | Always answer with this status (100-599). Applied last. | |
response.status.map |
map | Replace one status with another, e.g. {"502": "503"}. | |
response.status.when |
list | Ordered conditions: [{if: }]. The first true condition wins; evaluated before map and set. |
|
time_budget |
duration | 50ms |
Wall-clock budget for every jq program of this binding, per request. Exceeding it fails the transformation with a coded error. |
policies:
- config:
request:
body:
program: '{customer_id: .body.customerId, items: [.body.lines[] | {sku, qty: .quantity}]}'
headers:
remove:
- Cookie
set:
X-Tenant: ${header.X-Org}
path:
add_prefix: /v2
response:
body:
program: '{id: .body.orderId, total: ([.body.lines[].price] | add), currency: "SAR"}'
headers:
remove:
- Server
- X-Powered-By
status:
map:
"502": 503
when:
- if: .body.ok == false
status: 400
type: transform
upstream-auth¶
Backend authentication — Authenticate the gateway to the backend with an OAuth 2 token it obtains and caches. · phase 705 · authentication
For backends that require their own token: the gateway calls the backend's token endpoint with credentials only it holds (OAuth 2 client credentials or a service account's username and password, as form fields; or the backend's own login endpoint with a JSON body, request: json), caches the token until shortly before it expires, and sends it on every request as a bearer header. The caller's identity, checked earlier by api-key or jwt, can be passed to the backend in extra headers with ${claim.
| Setting | Type | Default | Description |
|---|---|---|---|
token_url (required) |
string | The backend's token endpoint: an OAuth 2 one such as https://auth.partner.example/oauth/token, or the backend's own login such as https://hr.example.com/api/auth/login with request: json. | |
allow_http |
boolean | false |
Accept a plain http:// URL beyond this machine. What is fetched or sent then travels in clear; only for an isolated network. |
request |
form | json | form |
form: an OAuth 2 token endpoint; grant_type and the credentials are sent as form fields. json: the backend's own login endpoint; the service account's username and password (and params) are sent as a JSON body, and the token is read from token_field in the JSON answer. |
grant |
client_credentials | password | client_credentials |
client_credentials: a token for the gateway itself. password: a service account's username and password (the resource owner password grant, or a login endpoint with request: json). |
client_id |
string | OAuth 2 client id issued to the gateway. Required with request form; with request json it is sent only when set. | |
client_secret (secret) |
string | OAuth 2 client secret. Stored encrypted. Required with request form. | |
client_auth |
basic | body | basic |
How the client credentials are sent: HTTP Basic (RFC 6749 default) or as client_id and client_secret form fields. |
username |
string | Service account username (grant password). | |
password (secret) |
string | Service account password (grant password). Stored encrypted. | |
username_field |
string | username |
JSON field that carries the username (request json). |
password_field |
string | password |
JSON field that carries the password (request json). |
token_field |
string | access_token |
Where the token is in the answer: a field name, or a dotted path into nested objects such as data.accessToken. |
expires_field |
string | expires_in |
Where the token's lifetime in seconds is in the answer (a field name or dotted path). Absent or empty, the token's exp claim decides, then cache_ttl. |
scopes |
list | Scopes to request, sent space-separated as scope. | |
audience |
string | Audience parameter, for providers that require one (Auth0, some Keycloak setups). | |
params |
map | Extra form fields sent to the token endpoint, name to value. | |
header |
string | Authorization |
Request header that carries the token to the backend. |
prefix |
string | Bearer |
Text placed before the token in the header. |
headers |
map | Extra headers for the backend, name to value; values may use ${claim. |
|
cache_ttl |
duration | 5m |
How long a token is used when the token endpoint gives no expiry (no expires_in and no exp claim). |
refresh_before |
duration | 30s |
A token is renewed this long before its expiry, so no request forwards a token about to expire. |
refresh_before_percent |
integer | 0 |
Renew when this share of the token's lifetime is left: 20 renews a 30-minute token after 24 minutes. The larger of this and refresh_before applies. |
refresh_token_field |
string | refresh_token |
Where a refresh token is in the answer (a field name or dotted path). When the endpoint gives one, renewal uses it (grant_type refresh_token, or a JSON body with this field) instead of the credentials, and falls back to the credentials if the refresh is refused. Empty: never use refresh tokens. |
refresh_url |
string | Endpoint for renewing with a refresh token, when it differs from token_url (a login API with its own /refresh). | |
timeout |
duration | 5s |
Timeout of one call to the token endpoint. |
policies:
- config:
client_id: apinx-gateway
client_secret: ${secret}
headers:
X-User-Id: ${claim.sub}
scopes:
- employees:read
token_url: https://auth.partner.example/oauth/token
type: upstream-auth
set-header¶
Set header — Set fixed headers on the request and the response. · phase 710 · transformation · acts on responses
The simplest transformation: every listed request header is set before forwarding and every listed response header is set before answering. For add, remove and rename, use the transform policy.
| Setting | Type | Default | Description |
|---|---|---|---|
request |
map | Headers to set on the request, name to value. | |
response |
map | Headers to set on the response, name to value. |
compress¶
Response compression — Compress responses the caller accepts compressed. · phase 720 · transformation · acts on responses
Compresses the response body with gzip or brotli when the caller's Accept-Encoding allows it, the body is at least min_bytes and its media type is in the list. A response the backend already encoded, a 204, 304 or partial response, a HEAD answer, or one with Cache-Control: no-transform is left alone. Bodies stream through the compressor as they arrive; a cache hit or a mock is compressed as well. Runs last on the response, so the cache stores the uncompressed body and serves every caller.
| Setting | Type | Default | Description |
|---|---|---|---|
encodings |
list | gzip, br |
Encodings offered, in order of preference: gzip, br (brotli). The caller gets the first one it accepts. |
min_bytes |
size | 1KB |
Smallest body compressed; shorter ones go out as they are. A body of unknown length is read up to this size first to decide. |
content_types |
list | application/json, application/xml, application/javascript, application/x-ndjson, application/problem+json, text/, image/svg+xml |
Media types compressed, matched by prefix (text/ covers every text type); parameters such as charset are ignored. |
level |
fast | default | best | default |
Effort: fast (gzip 1, brotli 2), default (gzip 5, brotli 4), best (gzip 9, brotli 6). Best costs several times the CPU of default for a few percent. |
soap¶
SOAP backend — Publish one operation of a SOAP backend as a JSON operation. · phase 720 · composition · acts on responses
The consumer sends JSON; the gateway renders the request template into a SOAP envelope (the operation element you write, with ${body. as item} … ${end} for arrays and ${if body.
| Setting | Type | Default | Description |
|---|---|---|---|
version |
1.1 | 1.2 | 1.1 |
1.1: text/xml with a SOAPAction header. 1.2: application/soap+xml with the action parameter. |
action |
string | The SOAPAction (1.1) or action parameter (1.2). Empty sends an empty SOAPAction header for 1.1, as many stacks require. | |
namespaces |
map | Prefix to namespace URI, declared on the Envelope so the templates can use the prefixes. | |
request (required) |
code | The body of the envelope: the operation element with references inside. The gateway adds Envelope, Header and Body around it. | |
headers |
code | Extra SOAP header elements (WS-Addressing by hand, custom headers), references allowed. | |
security |
none | username_token | none |
username_token adds a wsse:Security header with a UsernameToken built from username, password, password_type and timestamp. |
username |
string | The token's username; references allowed. | |
password (secret) |
string | The token's password. Stored encrypted; may be an env:, file: or vault: reference. | |
password_type |
text | digest | text |
text sends PasswordText. digest sends PasswordDigest with a Nonce and Created (WSS UsernameToken profile 1.1), so the password itself never travels. |
timestamp |
boolean | false |
Adds wsu:Created to a PasswordText token (a digest token always carries it). |
response.unwrap |
string | Element path under the SOAP Body whose content becomes the JSON, segments separated by /, such as GetOrderResponse/Order. Empty: the first child of the Body (the ...Response element). | |
response.arrays |
list | Element names that are always arrays, even when one element is present (Line, Order). | |
response.attributes |
drop | keep | drop |
keep: attributes become @name keys. drop: they are left out. |
response.types |
string | infer | string |
string: every text value is a string. infer: numbers and booleans are typed. |
response.jq |
code | Optional jq program run on the converted JSON (its input is the converted value); its single output is the body. Same compiler and time budget as transform. | |
response.limits.depth |
integer | 32 |
Deepest element nesting accepted. |
response.limits.elements |
integer | 100000 |
Most elements accepted in one answer. |
response.limits.text |
size | 1MB |
Longest text of one element accepted. |
max_body |
size | 1MB |
Largest consumer JSON body, and largest envelope built from it; over it the request is refused with 413 APX-SOAP-0005. |
max_response |
size | 4MB |
Largest backend XML accepted; over it the answer is 502 APX-SOAP-0004. |
endpoint_path |
string | The path on the backend the envelope is posted to, replacing the request's own: a WSDL's endpoint is one path for every operation. The WSDL import sets it. Empty keeps the request path. |
policies:
- config:
action: urn:example:orders/GetOrder
namespaces:
ord: urn:example:orders
password: env:ORDERS_SOAP_PASSWORD
request: |-
<ord:GetOrder>
<ord:OrderId>${body.orderId}</ord:OrderId>
</ord:GetOrder>
response:
arrays:
- Line
unwrap: GetOrderResponse/Order
security: username_token
username: svc-gateway
version: "1.1"
type: soap