Gateway Policy & Security
Each API has a gateway policy that controls how the API Gateway treats its calls. Set it in the Gateway policy card on the API's edit page (while the API is in Draft or Rejected), or as gateway_policy in the API.
The defaults are deliberately safe for existing APIs: limits are generous, and the strict checks are opt-in per API.
| Setting | gateway_policy key | Default | What it does |
|---|---|---|---|
| Calls per minute (API) | rate_limit_per_minute | 600 | Total calls to this API per minute, across all users |
| Calls per minute (per user) | user_rate_limit_per_minute | 120 | Calls per signed-in user per minute (needs a caller identity) |
| Max request size | max_request_bytes | 5 MB | Larger request bodies are refused with 413 |
| Max response size | max_response_bytes | 10 MB | Larger upstream responses are refused with 502 |
| Validate requests against the spec | validate_requests | Off | Refuse calls that don't match the OpenAPI spec (400) |
| Require a signed caller identity | require_caller_identity | Off | Refuse calls that don't carry a caller token (401) |
| Mask sensitive data | masking | None | Mask PAN, Aadhaar, card numbers, emails, mobile numbers or custom patterns in responses |
| Validate responses against the spec | validate_responses | Off | warn: pass through and flag; enforce: return 502 when the upstream breaks its contract |
| Cache GET (seconds) | cache_ttl_seconds | 0 (off) | Serve repeated successful GETs from cache, up to 3600 s |
| Pause after failures | breaker_failure_threshold | 5 | Consecutive upstream failures before calls are paused (0 = never) |
| Pause for (seconds) | breaker_cooldown_seconds | 30 | How long calls stay paused before a trial call |
| Alert webhook | alert_webhook_url | None | Gets a JSON (Slack-compatible) message when calls pause and when they resume |
| Upstream timeout (seconds) | upstream_timeout_seconds | 60 | How long the upstream may take to answer each attempt, up to 600 s; then 504 upstream_timeout |
| Calls at once (per worker) | max_concurrent_calls | 100 | Upstream calls to this API in progress at once, per gateway worker; more wait up to a second, then get 503 upstream_busy (0 = no limit). See Concurrency and overload |
| Idempotency-Key kept (seconds) | idempotency_ttl_seconds | 0 (off) | A POST or PATCH repeated with the same Idempotency-Key header gets the first response, up to 86400 s. See Idempotency-Key |
| Web pages that may call this API | cors_allowed_origins | Studio's setting | The sites whose pages may call the API from a browser. See CORS for web pages |
| Caller headers passed to the upstream | forward_request_headers | See Headers | Caller headers the upstream receives |
| Upstream headers returned to callers | forward_response_headers | See Headers | Upstream headers callers receive |
| Deprecated from, Sunset on | deprecated_at, sunset_at | None | Dates sent as Deprecation and Sunset headers. See Deprecation and sunset |
| Migration guide URL | deprecation_link | None | Sent as a Link header with every response |
| Partner access tokens | jwt_auth | Off | Accept access tokens (JWTs) from the partner's own identity provider. See Partner access tokens |
Leave a limit empty to use the instance default. Instance defaults come from environment variables (see Configuration).
In the API, sizes are in bytes (the form shows MB: 10 MB = 10485760), validate_responses is off, warn or enforce, and masking is {"presets": [...], "custom": [{"pattern": "...", "replacement": "..."}]} with the presets pan_in, aadhaar, card_number, email and phone_in. Saving a policy through the API replaces the whole of it (the form keeps the keys it doesn't show); any other key is refused with 422 Unknown gateway_policy keys, which lists the valid ones. For example, 650 calls a minute, 200 per user and 10 MB both ways:
{
"rate_limit_per_minute": 650,
"user_rate_limit_per_minute": 200,
"max_request_bytes": 10485760,
"max_response_bytes": 10485760
}Rate Limits
Two rolling one-minute limits apply to every call: one for the whole API and one per caller (the signed-in user, the consumer key, or the subject of a partner access token). A call over either limit gets:
HTTP/1.1 429 Too Many Requests
Retry-After: 6
{"error": "rate_limited", "message": "Rate limit exceeded for this API (600 calls per minute). Retry shortly.", "reference": "..."}
Limits are counted in Redis when it's configured, in one round trip per call (so they hold across multiple Hrida.ai replicas and gateway pods), and in memory otherwise. Refused calls count toward the limit, so a looping agent can't hammer the upstream by retrying instantly.
Size Caps
- Requests — checked from
Content-Lengthbefore the body is read, and again while it's read. - Responses — read in chunks; the read stops as soon as the cap is passed, so a single huge upstream response can't exhaust server memory.
- JSON nesting depth (
max_json_depth, off by default) — a JSON request body nested deeper than this many levels of objects and arrays is refused with400 request_too_deepbefore anything parses it, so a small crafted body can't exhaust the parser or a mapper. Brackets inside strings don't count, and bodies that aren't JSON aren't checked.32suits nearly every API; the maximum is1000. An admin can set it for a whole gateway under Admin › API Platform.
Request Validation
With Validate requests against the OpenAPI spec on, the gateway checks each call before it reaches any mapper or the upstream:
- Path and query parameters — required parameters present, values match their schema type (integers, numbers, booleans) and constraints.
- JSON request body — validated against the operation's
requestBodyschema, including$refs intocomponents(OpenAPI 3) ordefinitions(Swagger 2), and OpenAPI 3.0nullable.
{
"error": "request_invalid",
"message": "Request does not match the API specification: body.amount: 0 is less than the minimum of 1; body: 'currency' is a required property",
"reference": "..."
}The message lists up to 20 problems so the calling agent can correct its request. Turn it on once your spec accurately describes the upstream — a loose or incomplete spec will refuse valid calls.
Mock Responses
With Mock responses on (mock_responses: true), the gateway answers every operation from the spec and never calls the upstream. Use it to build, test and demo agents before the backend exists, or while it's down for maintenance.
The answer is the operation's first success response (2xx, else default):
- its example: OpenAPI 3
example, the first ofexamples, or Swagger 2examplesforapplication/json; - otherwise a sample built from its schema: the schema's own
exampleordefault, an enum's first value, a value fitting theformat(dates, UUIDs, emails…), every property, and one array item, following$refs and stopping at recursion; - otherwise no body, e.g. for
204.
Everything before the upstream still runs: authentication, rate limits, quotas, and request validation when it's on. Masking applies to the mocked answer. Responses carry X-Hrida-Mock: true and X-Hrida-Warning: mock, and the call log marks the calls mock.
The API's page shows a Mock responses on badge while it's on. Like the rest of the policy, it applies to every environment, prod included, as soon as you save, even while the API is a draft being revised. Turn it off before real use: agents get sample data, not real data.
Caller Identity
With Require a signed caller identity on, the API only accepts calls made by Hrida.ai agents on behalf of a signed-in user. Every call is then attributed to a user in the call log, counted against the per-user limit, and re-checked against the API's access grants.
Leave it off for APIs that automations or scheduled jobs call without a user context. When it's off, a caller token is still verified and enforced if one is sent. See Caller identity for how the token works.
Response Masking
Masking replaces sensitive values in responses before they reach the agent (and therefore the model). It applies to every string in a JSON response, including nested values, and to text responses such as XML or CSV.
| Preset | Example input | Masked |
|---|---|---|
| PAN (India) | ABCDE1234F | AB******4F |
| Aadhaar | 2345 6789 0123 | XXXX XXXX 0123 |
| Card numbers | 4111 1111 1111 1111 | **** **** **** 1111 |
| Email addresses | asha.rao@bank.in | a***@bank.in |
| Mobile numbers (India) | +91 98765 43210 | ******3210 |
- Card numbers are only masked when they pass the Luhn checksum, so other long numbers (order ids, references) are left alone.
- Aadhaar ignores 12-digit runs that are part of a longer number.
- Custom rules take a regular expression (up to 200 characters, checked when you save) and a replacement, for example
ACC-\d+→ACC-****. - Custom patterns are time-limited: each runs for at most 50 ms on a value. One that takes longer masks the whole value (
****) rather than holding up the call, and a pattern that backtracks badly on some inputs, such as(a+)+$, is refused when you save.
Masking runs after the response mappers, so it also covers fields a mapper adds. Individual strings over 100 KB are not masked.
Response Validation
With Validate responses on, every successful JSON response is checked against the schema the spec declares for that status code (exact code, then 2XX, then default). Responses with no declared schema are not checked. The check runs after the operation's response mappers, on what the agent will receive — the spec describes the agent-facing shape, the same one request validation checks.
| Mode | When the response doesn't match |
|---|---|
| Warn | It is returned unchanged; the call log shows ⚠ response_invalid and the response carries X-Hrida-Warning: response_invalid |
| Enforce | The caller gets 502 response_invalid listing where and which rule failed |
Messages name the field and the rule (response.id: fails "type"), never the value, so validation can't leak data that masking would have hidden. Validation runs on the upstream's shape, before response mappers.
GET Response Cache
Set Cache GET (seconds) to serve repeated successful GET calls without calling the upstream. The key is the API, environment, version, path and query string, so a new version never serves an old version's responses.
- Only
2xxresponses up to 1 MB are cached. - The raw upstream response is cached: mappers and masking still run on every call, so changing them takes effect at once.
- Rate limits still apply to cached calls.
- The response carries
X-Hrida-Cache: HITorMISS, and the call log marks cached calls. - Shared across replicas through Redis when it's configured, otherwise per process.
Only use it for data that may be up to the TTL old.
Circuit Breaker and Alerts
When the upstream fails several times in a row — unreachable, timing out, or answering 5xx after the gateway's own retries — the gateway pauses calls for the cooldown instead of piling more load on a struggling service:
- Paused calls get
503 upstream_circuit_openwith aRetry-Afterheader, and the upstream isn't called. Cached responses are still served. - After the cooldown, exactly one trial call is let through, across all replicas, while the others keep getting
503: success resumes normal traffic, failure pauses again. - With Redis, failures from every replica count together and each update is atomic. A worker that last found the upstream healthy checks again at most every second (
API_GATEWAY_BREAKER_SYNC_SECONDS), so a pause decided elsewhere reaches it within about a second, and a healthy API costs no Redis round trips. 4xxresponses never count; they're the caller's problem, not the upstream's.- Each environment has its own breaker.
With an Alert webhook set, the gateway POSTs a JSON message when calls pause and when they resume:
{"text": ":red_circle: API \"Customers\" (prod): upstream failing — gateway paused calls for 30s after 5 failures in a row. Last error: HTTP 503",
"event": "breaker_opened", "api_definition_id": "…", "environment": "prod", "failures": 5, "cooldown_seconds": 30, "last_error": "HTTP 503"}The text field works with Slack and Teams incoming webhooks. The URL must be public; internal and metadata addresses are refused.
The Environments card shows each environment's breaker (failures in a row, last error) with a Reset button to resume calls at once. Also available as GET /api/v1/api-definitions/{id}/gateway-health and POST …/gateway-health/reset.
Concurrency and Overload
A slow or hung upstream shouldn't take every connection and worker down with it. Three limits protect the gateway, each per gateway worker process:
| Limit | Setting | Default | Past it |
|---|---|---|---|
| Calls to one API at once | Calls at once (max_concurrent_calls) | 100 | The call waits up to API_GATEWAY_QUEUE_TIMEOUT_MS (1 second) for a slot, then gets 503 upstream_busy with Retry-After: 1 |
| Gateway calls at once, all APIs | API_GATEWAY_MAX_IN_FLIGHT | 1000 | 503 overloaded at once, with Retry-After: 1, instead of queueing until every call times out |
| Retries | API_GATEWAY_RETRY_BUDGET_RATIO | 0.2 | Retries spend a budget that calls earn, one retry per five calls by default, so retries can't multiply the load on a failing upstream. Past it, the failure is returned |
Retries wait an exponential backoff with random jitter, so callers that failed together don't all retry at the same moment. A response streamed to the caller keeps its slot until it ends. Identical GETs that miss the cache at the same moment share one upstream call.
Headers
By default the gateway passes these caller headers to the upstream:
Accept-Language, If-Match, If-None-Match, If-Modified-Since, If-Unmodified-Since, Idempotency-Key, Prefer, X-Request-Id
and returns these upstream headers to the caller:
Location, Content-Location, Content-Disposition, Content-Language, ETag, Last-Modified, Cache-Control, Expires, Link, Retry-After, RateLimit, RateLimit-Policy, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-Total-Count, Deprecation, Sunset, Preference-Applied
Set Caller headers passed to the upstream and Upstream headers returned to callers (forward_request_headers, forward_response_headers, at most 50 names each) to change the lists; leave them empty for the defaults.
- Upstream URLs in
Location,Content-LocationandLinkare rewritten to the gateway URL the caller used, so callers keep going through the gateway and never see the upstream's address. - Some headers can't be listed, because the gateway owns them: credentials and cookies (
Authorization,Cookie,Set-Cookie,WWW-Authenticate), framing and connection headers (Host,Content-Length,Content-Type,Transfer-Encoding, …), trace context, security headers, anything starting withAccess-Control-,Proxy-orX-Hrida-.
Idempotency-Key
Payment and order APIs often take an Idempotency-Key header, so a client that lost the answer can safely send the request again. Set Idempotency-Key kept (seconds) to have the gateway guarantee it, whatever the upstream does:
- A
POSTorPATCHrepeated with the sameIdempotency-Keyby the same caller within that time gets the first response again, markedIdempotent-Replayed: true. The upstream isn't called a second time. - A repeat while the first is still running gets
409 idempotency_in_progresswithRetry-After: 1. - The same key with a different request (method, path, query or body) gets
422 idempotency_key_reused. 5xxresponses and failed calls aren't kept, so the caller can retry with the same key. Neither are responses over 1 MB or streamed ones.- Keys belong to their caller: two consumer keys using the same
Idempotency-Keyvalue never collide. A key over 255 characters gets400 idempotency_key_invalid.
Keys are kept in Redis when it's configured, so every replica and gateway pod sees them. Without Redis each process keeps its own, which is only a best effort.
CORS for Web Pages
A browser lets a web page on another site call your API only if the gateway allows that site (CORS). Web pages that may call this API (cors_allowed_origins) sets it per API:
| Setting | cors_allowed_origins | Effect |
|---|---|---|
| Studio's setting | not set | The instance's CORS_ALLOW_ORIGIN, as before this setting existed |
| None | [] | No web page on another site may call the API |
| Only these sites | ["https://app.example.com"] | Exactly these origins (scheme://host[:port]), or ["*"] for any site |
- The gateway answers the browser's preflight (
OPTIONS) itself, per API. It never reaches the upstream and isn't logged. - Allowed responses, errors included, carry
Access-Control-Allow-Originand let the page read the gateway's headers and the forwarded ones. Cookies are never allowed (Access-Control-Allow-Credentialsis never sent): callers authenticate with a Bearer token. - Calls from servers, scripts and agents aren't affected: CORS only concerns browsers.
Anyone who opens a page can read a consumer key in it. For browser apps, prefer partner access tokens, which expire, or restrict the key with allowed addresses and quotas.
Deprecation and Sunset
When an API is going away, tell its callers in every response, errors included:
- Deprecated from (
deprecated_at) →Deprecation: @1767225600(RFC 9745). The date may be in the past or the future. - Sunset on (
sunset_at) →Sunset: Wed, 30 Jun 2027 00:00:00 GMT(RFC 8594). - Migration guide URL (
deprecation_link) →Link: <https://docs.example.com/migrate>; rel="deprecation"; type="text/html".
Dates are YYYY-MM-DD (midnight UTC), or a full ISO 8601 date and time through the API, and the sunset can't be before the deprecation. Calls keep working after the sunset date: unpublish the API, or move its callers to a new version, to stop them.
Partner Access Tokens (JWT)
Instead of a consumer key, a partner's systems can call the API with an access token from the partner's own identity provider: Microsoft Entra ID, Okta, Auth0, Keycloak and the like. Turn on Accept access tokens from the partner's identity provider (JWT) and set:
| Field | jwt_auth key | Example |
|---|---|---|
| Issuer | issuer | https://login.example.com/: the token's iss claim must equal it |
| Audience | audience | orders-api: the token's aud must include it |
| JWKS URL | jwks_url | https://login.example.com/.well-known/jwks.json: the provider's published signing keys |
| Required scopes | required_scopes | orders:read: every token must carry them in scope (or scp) |
The caller sends the token as Authorization: Bearer <token>. The gateway checks:
- the signature, against the provider's keys. Only asymmetric algorithms are accepted (
RS*,PS*,ES*,EdDSA);noneand HMAC are refused; - the issuer, audience, expiry and not-before, with 60 seconds of clock leeway;
- the required scopes: a token without them gets
403 insufficient_scope, with aWWW-Authenticateheader naming them.
A token that fails a check gets 401 unauthorized and counts as a failed login. The caller is known by the token's subject (sub): it gets its own per-caller rate limit, and the call log shows it as jwt:<subject>. A token can also read the spec at the gateway URL. As with consumer keys, an API that requires a signed caller identity refuses partner tokens.
The signing keys are fetched through the gateway's own connection pool, with the same address checks and host allow-list as upstreams, and kept for 10 minutes (API_GATEWAY_JWKS_CACHE_SECONDS). A token signed with a key the gateway doesn't have makes it fetch them again, at most every 30 seconds, so the provider's key rotation is picked up at once. If the provider can't be reached and no keys are cached, calls get 503 jwks_unavailable.
Failed Logins
A made-up consumer key costs the gateway little: it's recognised in memory, without a database query. To keep floods of guesses out of the call log too, an address with more than API_GATEWAY_AUTH_FAILURES_PER_MINUTE (30) failed logins in a minute gets 429 auth_throttled with Retry-After: 60 for further failures, and those aren't logged. A failed login is a wrong or unknown consumer key, gateway secret or partner token. Only failures count: a valid credential keeps working from that address, since several callers can share one address behind NAT.
The address is the client's as the gateway sees it, from X-Forwarded-For: see client addresses behind a load balancer for what to trust.
Upstream Host Allow-List
Admins can restrict which hosts any API's upstream may point at. Open API Builder → Gateway settings (admins only) and list one host per line:
api.partner.com
*.bank.internal
*.bank.internalmatches any subdomain ofbank.internal, but notbank.internalitself.- An empty list allows any host (subject to the network protections below).
- The list is checked when an API is saved, when it's published, and on every gateway call — tightening the list immediately blocks published APIs on hosts that are no longer allowed (
502 upstream_blocked).
The initial value can come from API_BUILDER_UPSTREAM_ALLOWED_HOSTS (comma-separated); after that it's managed in the UI.
Network Protections
These apply to every API regardless of policy:
- Upstream URLs must be absolute
http/httpsURLs with no credentials embedded (put credentials in the auth settings). - Internal addresses are blocked — loopback (
localhost,127.0.0.1,::1), link-local and cloud-metadata addresses (169.254.0.0/16, including169.254.169.254), unspecified and multicast addresses. Private networks such as10.xand192.168.xstay allowed, since internal enterprise APIs are a primary use case. - Every new connection checks the addresses the upstream's host name resolves to, so a host name that later starts resolving to a blocked address (DNS rebinding) is still refused.
- Path tricks —
.and..segments are refused, and only operations in the spec are reachable. - XML from upstreams and samples is parsed with protections against entity-expansion and external-entity attacks.
API_BUILDER_ALLOW_LOCAL_UPSTREAMS=true allows loopback upstreams for local development. Link-local and metadata addresses stay blocked even then.
Configuration
| Environment variable | Default | Purpose |
|---|---|---|
API_GATEWAY_RATE_LIMIT_PER_MINUTE | 600 | Default calls per minute per API |
API_GATEWAY_USER_RATE_LIMIT_PER_MINUTE | 120 | Default calls per minute per user |
API_GATEWAY_MAX_REQUEST_BYTES | 5242880 | Default max request body (bytes) |
API_GATEWAY_MAX_RESPONSE_BYTES | 10485760 | Default max upstream response (bytes) |
API_GATEWAY_CALLER_TOKEN_TTL_SECONDS | 900 | Lifetime of caller identity tokens |
API_GATEWAY_CALL_LOG_RETENTION_DAYS | 30 | How long call log rows are kept |
API_GATEWAY_BREAKER_FAILURES | 5 | Default consecutive failures before calls pause (0 = off) |
API_GATEWAY_BREAKER_COOLDOWN_SECONDS | 30 | Default pause length |
API_GATEWAY_UPSTREAM_TIMEOUT_SECONDS | 60 | Default upstream timeout per attempt, in seconds. When unset, AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER is used if set |
API_GATEWAY_MAX_CONCURRENT_CALLS | 100 | Default calls to one API at once, per gateway worker (0 = no limit) |
API_GATEWAY_MAX_IN_FLIGHT | 1000 | Gateway calls at once per worker, all APIs, before 503 overloaded (0 = no limit) |
API_GATEWAY_QUEUE_TIMEOUT_MS | 1000 | How long a call waits for a slot of its API before 503 upstream_busy |
API_GATEWAY_RETRY_BUDGET_RATIO | 0.2 | Retries each call earns (0.2 = one retry per five calls) |
API_GATEWAY_STREAM_THRESHOLD_BYTES | 1048576 | A response nothing changes is streamed to the caller when it is larger than this, or doesn't declare its length |
API_GATEWAY_AUTH_FAILURES_PER_MINUTE | 30 | Failed logins per address and minute before 429 auth_throttled (0 = no limit) |
API_GATEWAY_CLIENT_CERT_HEADER | (unset) | The header your TLS-terminating proxy passes the client certificate in, for keys bound to a certificate |
API_GATEWAY_BREAKER_SYNC_SECONDS | 1 | How long a worker trusts that an upstream is healthy before checking the shared breaker again (0 = on every call) |
API_GATEWAY_JWKS_CACHE_SECONDS | 600 | How long partner identity providers' signing keys are kept |
SAFE_EVAL_MAX_STEPS | 250000 | Steps one mapper expression may take; past it the mapping fails instead of holding up the worker |
REDIS_URL | (unset) | Shares rate limits, cache and breaker state across replicas; without it each process keeps its own (a warning is logged at startup) |
API_BUILDER_UPSTREAM_ALLOWED_HOSTS | (empty) | Initial host allow-list, comma-separated |
API_BUILDER_ALLOW_LOCAL_UPSTREAMS | false | Allow loopback upstreams (local development only) |
ENABLE_API_BUILDER | true | Turn API Builder on or off for the whole instance |
The features.api_builder user permission controls which non-admin users can use API Builder. Both it and ENABLE_API_BUILDER are enforced by the server, not just by hiding the menu.
Related
- API Gateway — the full request pipeline and error codes
- Upstream Authentication & TLS — how the gateway authenticates to the upstream
- Gateway Call Log — see what the policy refused and why