Gateway
The Plat5 gateway (services/gateway/). How it decides a request: access. What services receive: reference/headers.md. Environment: reference/env.md.
Responsibilities
Section titled “Responsibilities”| Layer | Responsibility |
|---|---|
| Gateway | Routing, authentication (JWT, API key), resolving path slugs to node ids, admission, permission checks, rate limits, upstream fill, audit intent and outcome, route checks, CORS, security headers, body limits, trace propagation |
| Edge / load balancer | TLS termination |
| Identity | Admit: the member and permissions for a credential on a node chain |
| Services | Business logic, data access, and state rules over the node ids they receive |
Credentials
Section titled “Credentials”Every credential is Authorization: Bearer. Three dot-separated segments is a JWT, verified locally against JWKS; a JWT that fails is 401 without an identity call. Anything else is sent to admit as a key, as presented: the gateway doesn’t know the key format.
POST {IDENTITY_INTERNAL_URL}/internal/admit{ "credential" | "idp", "chain": [{ "kind", "ref" }], "allow_deleted" }→ { "valid", "key_id", "allowed_cidrs", "root_allowed_cidrs", "credential_scopes", "nodes": [{ "kind", "id" }], "member_id", "user_id", "permissions", "rate_limit_tier", "expires_at", "invalidation_seq", "config_revision" }On identity’s INTERNAL_PORT. An empty chain is a user route. Contract: reference/api/internal.md.
In-process per replica, backed by identity’s invalidation feed (GET {IDENTITY_INTERNAL_URL}/internal/admit-invalidations, reference/api/internal.md).
| Key | The credential (a key as presented, or a verified JWT’s issuer, subject, forwarded scopes when AUTH_SCOPE_CLAIM is set, and forwarded policy claims when policy_claims is set in config), allow_deleted, and the chain refs as written in the path |
| Invalidation | Targeted epoch checks (key_id, user_id, member_id, root_id, global reset, and identity’s config_revision) driven by identity’s invalidation feed; entries stamped before the admit call so in-flight revocations are never pinned. A lagging identity replica returning an older config_revision is served without caching |
| TTL | ADMIT_CACHE_TTL (default 5m), capped at expires_at - now when admit returns a key or binding expiry — fallback upper bound if the invalidation feed is disconnected |
| Negative entries | For invalid credentials and member_id: null, for ADMIT_NEGATIVE_CACHE_TTL (default 10s). Authenticated tree refusals (valid: true, member_id: null) and JWT refusals are invalidated immediately via the invalidation feed; invalid API keys live until TTL or DB reset. Never cached for identity errors |
| Singleflight | Concurrent misses for one key share a single identity call |
| JWT cache | Validated JWT claims are cached in memory (keyed by BLAKE3 hash of the token) with per-entry TTL derived from exp minus a safety buffer, so expired tokens are evicted before expiry |
Control plane
Section titled “Control plane”Routes, kinds, rate limits and defaults come from the control plane (CONTROL_PLANE_URL, required to boot). The gateway reads GET {CONTROL_PLANE_URL}/internal/gateway.
- Boot. Binds
/health/live,/health/ready, and/metricsonINTERNAL_PORTright away and loads the first snapshot in the background (/health/readyreturns 503 withchecks.config_ready: false, and public routes answer 503, until the first snapshot arrives). - Running. Long-polls with
?after={revision}and swaps them whole on each change. - Control plane down. Keeps serving the last snapshot.
- Invalid snapshot. Refused whole: keeps the current snapshot, logs an error, counts it, and reports the revision and reason on its next poll.
- Reporting. Every long poll carries the replica id and loaded revision (feeds).
Rate limits
Section titled “Rate limits”Controlled by RATE_LIMIT_ENABLED (default true). When enabled, counters live in Valkey so replicas share one budget: VALKEY_URL is required to boot (URL syntax is validated at boot). Rate limiting always fails open when Valkey is unreachable or times out (> 500ms): requests are allowed without X-RateLimit-* headers, the failure is logged on state transitions and counted (rate_limit_fail_open_total), and a background reconnect loop restores enforcement automatically once Valkey recovers. Valkey availability does not block boot or fail /health/ready.
When RATE_LIMIT_ENABLED=false, VALKEY_URL is ignored, Valkey need not run, and configured rate limits (including the failed-auth IP limiter) are skipped. The gateway logs the mode at boot.
Policies and buckets: rate limits.
| Check | Every policy on the route in one round trip, counted only if all pass |
| Exceed | 429 RATE_LIMITED, details.retry_after_seconds, Retry-After |
| Admitted headers | On limited routes (2xx and 429) when Valkey answered: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, for the tightest policy (omitted when failing open) |
| Keys | Under VALKEY_KEY_PREFIX (default plat5:rl:) |
| Failed-auth IP | RATE_LIMIT_AUTH_FAILURE_REQUESTS / RATE_LIMIT_AUTH_FAILURE_WINDOW (default 60 / 60s; 0 requests = off). What it counts: access. 429 sets Retry-After; no X-RateLimit-* |
Controlled by AUDIT_MODE (sync, async, or off, default sync). In sync mode, on an audited route other than public, the gateway writes an intent after the permission check and before forward, and an outcome after; an unwritten intent returns 503 and the service isn’t called. In async mode, audited requests forward immediately and queue one completed event in the background after the response. In both modes, gateway refusals after admit are one background event. AUDIT_URL is required to boot unless AUDIT_MODE=off. Contract: concepts/audit.md.
Client IP
Section titled “Client IP”What an audit event records as ip, and what public routes and the failed-auth limiter key on.
The TCP peer, unless the peer is in TRUSTED_PROXIES (comma-separated addresses and CIDRs). Then X-Forwarded-For is walked from the right, past trusted proxies, and the first address that isn’t one is the client. Nothing left of an untrusted hop is read. An entry that isn’t an address stops the walk at the last trusted proxy.
TRUSTED_PROXIES empty (the default): X-Forwarded-For is ignored.
A param value of . or .., or one holding /, ? or # once decoded, is 400: it would change the path the upstream sees. The query string is forwarded as sent.
Request bodies
Section titled “Request bodies”A body larger than the service’s max_body_bytes (or defaults.max_body_bytes, default 10 MiB) is 413 PAYLOAD_TOO_LARGE, checked on Content-Length and while streaming.
Route checks
Section titled “Route checks”Whether the caller may call each of a batch of routes, for a UI that hides what the caller can’t use (access). Answered directly by the gateway at POST /access/routes; no service route may register /access/routes.
POST /access/routesAuthorization: Bearer …{ "checks": [ { "method": "GET", "path": "/orgs/acme/projects/web/bindings" }, { "method": "DELETE", "path": "/orgs/acme" } ]}→ 200{ "checks": [ { "allowed": true }, { "allowed": false } ] }| Field | Rule |
|---|---|
checks |
1 to 100. Answered in request order, one each |
method |
GET, POST, PUT, PATCH, DELETE or HEAD, uppercase |
path |
A public path: starts with /, visible ASCII, no ? or #, at most 2048 characters |
Each allowed runs the gateway’s own route match, admit (using the admit cache) and permission check:
| The route | allowed |
|---|---|
| None matches the path and method | false |
public |
true |
user |
true when admit returns a user_id (an unrestricted user credential), false otherwise (service account, narrowed personal key, or scoped JWT) |
| A kind | true when admit accepts the caller on the chain (a deleted node only on an allow_deleted route), the root’s allowed_cidrs permits the client IP, and either built-in permissions or the configured top-level authorizer (batched) allows the route |
- Credential. Missing, malformed, or locally refused JWT → 401. Any admit answering
valid: falsemakes the whole call 401 (counted once by the failed-auth limiter when enabled). A batch that needs no admit (allpublicor unmatched) never calls identity. - Rate limit. When rate limiting is enabled and
defaults.rate_limitis set, counted once per call againstdefaults.rate_limitper admitted credential (or by client IP when the batch needs no admit), withX-RateLimit-*on 200 and 429. - Not audited, and nothing is forwarded. A new user’s first check that hits admit creates them, like any first request.
- Validation. Bad JSON,
checksoutside 1–100, or badmethod/path→ 422VALIDATION_ERROR. Body over 256 KiB → 413PAYLOAD_TOO_LARGE. Other methods on/access/routes→ 404.
TLS termination and upstream Host
Section titled “TLS termination and upstream Host”TLS terminates at the edge or load balancer, not the gateway. Services behind the gateway receive plaintext HTTP (or HTTPS when their url is https://…). On every forwarded request — both http:// and https:// — the gateway rewrites the Host header to the upstream’s authority (host or host:port), so virtual-hosted upstreams and proxies always see their own host.
Upstream security
Section titled “Upstream security”- Request signing. Set
UPSTREAM_SIGNING_KEY(and optionallyUPSTREAM_SIGNING_KEY_ID) to attach an Ed25519X-Plat5-Signatureheader to every forwarded request (reference/headers.md), so services outside the private network can verify requests came from the gateway. - Egress & SSRF isolation. Service
urlvalues andAUTHORIZER_URLare operator-configured, not end-user inputs. The gateway does not filter private or reserved IP ranges in-process; if your deployment forwards to untrusted or third-party endpoints and needs private-IP / metadata SSRF protection, enforce egress restrictions at the network layer (VPC security groups, KubernetesNetworkPolicy, or a dedicated egress proxy).
Outbound authorizer
Section titled “Outbound authorizer”When top-level authorizer is configured (standalone or combined with Plat5-stored roles; reference/config/authorizer.md), every permission-gated kind route consults that external OpenID AuthZEN 1.0 PDP (using the route’s resource: { type, id } template when set, or the route’s target node). Decisions fail closed (503 on timeout/error), respect credential scope narrowing, and batch into one /access/v1/evaluations call during POST /access/routes. AUTHORIZER_CACHE_TTL and AUTHORIZER_NEGATIVE_CACHE_TTL control response caching (0s by default for immediate consistency).
Configured on the gateway process via CORS_ALLOWED_ORIGINS and CORS_ALLOWED_HEADERS (reference/env.md). The gateway answers every OPTIONS request as a preflight: 204 No Content, Access-Control-Allow-* and Access-Control-Max-Age: 86400. It adds Access-Control-Allow-Origin and Access-Control-Expose-Headers on responses.
| Header | Value |
|---|---|
Access-Control-Allow-Origin |
With CORS_ALLOWED_ORIGINS=*, *. Otherwise an Origin in the comma-separated list, echoed, with Vary: Origin; otherwise omitted |
Access-Control-Allow-Methods |
GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS |
Access-Control-Allow-Headers |
Authorization, Content-Type, plus CORS_ALLOWED_HEADERS |
Access-Control-Expose-Headers |
X-Request-ID, Retry-After, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset |
Security headers
Section titled “Security headers”On public proxy responses (errors included, not /health or /metrics), each added only when the upstream response hasn’t set it:
X-Content-Type-Options: nosniffX-Frame-Options: DENYReferrer-Policy: strict-origin-when-cross-origin
AUTH_JWKS_URI is optional: when omitted, the gateway discovers jwks_uri from {AUTH_ISSUER}/.well-known/openid-configuration, falling back to {AUTH_ISSUER}/.well-known/oauth-authorization-server. Set AUTH_JWKS_URI explicitly when the issuer doesn’t serve discovery metadata or when the gateway reaches JWKS over a container-internal URL that differs from AUTH_ISSUER. An empty cache retries every 2s until loaded; a loaded cache refreshes every 15 minutes (and on demand on an unknown kid, with a 30s cooldown). Tokens must use an allowed asymmetric algorithm (RS256/384/512, PS256/384/512, ES256/384, EdDSA), carry valid exp, nbf (if present), and iss claims (60s clock-skew leeway), and match AUTH_ALLOWED_AUDIENCES (required; * accepts any audience) (reference/idp.md).
Boot and ready
Section titled “Boot and ready”The gateway binds its internal health/metrics port immediately at boot so orchestrators can probe /health/live (200) while it waits for its first control-plane snapshot and JWKS. /health/ready is 200 when both checks.config_ready and checks.jwks_ready are true, otherwise 503 (and public requests before the first snapshot return 503). The JSON body still reports checks.valkey_ready for visibility when RATE_LIMIT_ENABLED=true, but a Valkey outage does not fail readiness (rate limiting fails open). The control plane and audit aren’t part of ready after initial load: while the control plane is down, the gateway serves its last snapshot; while audit is down, audited routes return 503 in sync mode (or queue in async mode) and unaudited routes keep working.
Errors
Section titled “Errors”| Case | Code |
|---|---|
| Bad or missing credential, or key IP allowlist refusal | UNAUTHORIZED (401) |
| Node not found, not in the tree, org security policy/IP refusal, or permission/authorizer denied | FORBIDDEN (403) |
| A service account, narrowed personal key, or scoped JWT on a user route | FORBIDDEN (403) |
| Route not registered | NOT_FOUND (404) |
| Request body too large | PAYLOAD_TOO_LARGE (413) |
Bad /access/routes body |
VALIDATION_ERROR (422) |
| Rate limit (route policy or failed-auth IP) | RATE_LIMITED (429) |
| JWKS, identity, outbound authorizer, or sync audit intent down | SERVICE_UNAVAILABLE (503) |
| Upstream unreachable, timed out, or failing mid-proxy | 502 SERVICE_UNAVAILABLE |
Path param . / .. or containing / / ? / # |
INVALID_REQUEST (400) |
All use the Plat5 error envelope (reference/errors.md).