Skip to content

Servers and routes

A server is a backend service the gateway can forward to. A route maps a public path to one server.

Servers live under ServerConfigs, keyed by a name of your choice. At least one is required.

ServerConfigs:
svc-a:
URL: "http://svc-a:9090"
svc-b:
URL: "https://svc-b:9090"
TLS:
CACertFile: "ca.pem"
HeaderRule: strip-and-set
UsageControlRules: [limit-b-server]
Key Required Description
URL yes Where requests are forwarded, including the scheme, e.g. http://localhost:9090.
TLS no Options for HTTPS backends. See below.
HTTP, GRPC, WebSocket no The protocols the server accepts and their limits. No block means plain HTTP with defaults. See Protocols.
HeaderRule, ClientIDRule, AuthMethod no Default for every route that targets this server.
UsageControlRules no Usage control rules applied to every route of this server.
UsageControlMode no Cascade (default) or Strict. See usage control.
RequiredScopes no Scopes the caller’s token must hold on every route of this server, added to the route’s own. See Authentication.
ScopesMode no Additive (default) or Override. See Authentication.

A server that no route targets is reported as a warning, because it can never be reached.

HTTPS is used when URL starts with https://. By default the backend certificate is verified against the system trust store. The optional TLS block covers two cases:

Key Description
CACertFile PEM file with the certificate authority that signed the backend certificate. Use it for internal CAs. The file must exist and contain a valid certificate, nocleye check verifies it. It is a file name inside /etc/nocleye-beta/gateway/certs/, the only folder read: absolute paths, .. and symlinks pointing outside it are rejected.
InsecureSkipVerify true disables certificate verification. Do not use in production, nocleye check warns about it.

A TLS block on a server whose URL does not use https has no effect and is reported as a warning.

A server speaks plain HTTP unless it has a protocol block. A block means the server accepts that protocol, and carries its limits and timeouts. The protocol is never guessed from the URL: use http:// or https:// for all three (grpc:// and ws:// are not valid).

ServerConfigs:
users:
URL: "http://users:9090"
GRPC: # gRPC only: anything that is not gRPC is refused
IdleTimeout: 10m
MaxLifetime: 1h
MaxStreams: 5000
chat:
URL: "http://chat:9000"
WebSocket:
AllowedOrigins: ["https://app.example.com"]
shop:
URL: "https://shop:8443"
HTTP: {} # a mixed server: REST and gRPC on the same upstream
GRPC: {}
  • Write {} for defaults. A block with no body (GRPC:) is read by YAML as null, which means no block, so the server stays plain HTTP.
  • One block is strict. A server with only a GRPC block refuses plain HTTP requests, and one with only a WebSocket block refuses anything that is not a WebSocket handshake. Add HTTP (even HTTP: {}) to accept REST too.
  • Several blocks combine. The gateway looks at each request: Content-Type: application/grpc (also +proto, ;charset=...) is gRPC, Upgrade: websocket is WebSocket, everything else is HTTP. application/grpc-web and Connect are not gRPC to the gateway: they are carried as plain HTTP and never translated. Auth, scopes, usage control and header rules are per route, and one route has one budget for all the protocols of its server. MaxStreams and AllowedOrigins only apply to the half they belong to.
  • Any other Upgrade (like h2c) is refused with 400, on every server.
  • Routes are ordinary path routes. A gRPC route is a prefix like /pkg.Service/, because the RPC name is the request path.

Durations are strings like 30s or 10m. "0s" turns a timeout off where the table says so. The connection keys are the same on every block.

Key Blocks Default Description
DialTimeout all 10s Connecting to the backend. Must be above zero.
TLSHandshakeTimeout all 10s TLS handshake with an https:// backend. Must be above zero.
IdleConnTimeout all 90s How long an unused backend connection is kept. Must be above zero.
MaxIdleConnsPerHost all 10000 (HTTP), 10 (gRPC, WebSocket) Idle backend connections kept per server.
ResponseHeaderTimeout HTTP, WebSocket 60s (HTTP), 10s (WebSocket) Wait for the response headers (for WebSocket, the handshake up to the 101). "0s" = none. A timeout answers 504.
IdleTimeout all 5m Ends a request or stream with no bytes in either direction for this long. "0s" = none.
MaxLifetime GRPC, WebSocket none Hard cap per stream or tunnel. Must be at least IdleTimeout when both are written.
MaxStreams GRPC, WebSocket 1024 Concurrent calls (gRPC) or tunnels (WebSocket) on this server. Over the cap: 503 / UNAVAILABLE. There is no “unlimited”, use a bigger number. About 36 KiB (gRPC) and 60 KiB (WebSocket) of memory per idle stream were measured, size the cap to your memory.
MaxConnsPerHost HTTP 10000 Cap of backend connections. gRPC has none on purpose: HTTP/2 opens extra connections at the backend’s own stream limit.
MaxRequestBodySize HTTP 10MiB Larger request bodies are refused with 413. "0" = no limit.
AllowedOrigins WebSocket none See WebSocket.

A quiet stream is cut after IdleTimeout. For a WebSocket, pings and pongs are bytes in the tunnel and count as activity, so keep your ping interval below IdleTimeout. For gRPC, HTTP/2 PING frames do not count: a Watch or subscribe call that stays quiet needs IdleTimeout: 0s (or a bigger value), or the app must send data.

  • Works over cleartext (http://, HTTP/2 prior knowledge, h2c) and TLS (https://, the backend must negotiate h2). The gateway listener accepts both too.
  • Only POST over HTTP/2 with a gRPC content type is accepted by a gRPC-only server. Other requests get plain HTTP answers, as the gRPC spec asks: 405 (with Allow: POST), 400 (HTTP/1.1) and 415.
  • Every call is its own request, so authentication, usage control and rate limits run per call. Metadata keys with an underscore are dropped like HTTP headers with one.
  • grpc-timeout is forwarded to the backend untouched, the client’s own deadline is what ends the call. The gateway adds no deadline except MaxLifetime.
  • RemovePathPattern and AddPathPrefix change the RPC name the backend sees. nocleye check warns about them on a gRPC route.
  • Errors the gateway makes on a gRPC request are answered as gRPC (HTTP 200, grpc-status and grpc-message in the headers, no body), even before a route is found:
Cause gRPC status
Missing or invalid credentials UNAUTHENTICATED (16)
Scope or permission refused PERMISSION_DENIED (7)
No route, or the route is not a gRPC route, or a path with . segments UNIMPLEMENTED (12)
Rate limited UNAVAILABLE (14). Clients retry this one with backoff.
Usage control quota exceeded RESOURCE_EXHAUSTED (8)
MaxStreams reached, backend down, shutting down, config replaced UNAVAILABLE (14)
Deadline or MaxLifetime reached DEADLINE_EXCEEDED (4)
  • Errors the backend returns pass through untouched. They are HTTP 200 on the wire, so look at grpc_status in the access log and the grpc_status label of gw_requests_total.
  • IdleTimeout and MaxLifetime reset the stream (RST_STREAM, clients see INTERNAL) like Envoy and nginx do. A shutdown, a replaced config or a backend that dies mid-call end the call cleanly with trailers (UNAVAILABLE).
  • WebSocket over HTTP/1.1 (RFC 6455) only. WebSocket over HTTP/2 (RFC 8441) is not implemented: browsers fall back to HTTP/1.1 on their own.
  • The handshake is checked first: no valid upgrade is 426 (with Upgrade: websocket), a malformed one (not GET, version other than 13, missing key) is 400. On a server that also accepts HTTP, a request with Upgrade: websocket but no Connection: upgrade is 400, it never falls to the HTTP half.
  • After the 101 the gateway only copies bytes: no frame is read, no message is limited. Compression (permessage-deflate) and subprotocols are negotiated end to end.
  • Authentication and rate limits run once, at the handshake. See authentication.
  • When the gateway ends a tunnel (idle, MaxLifetime, shutdown, config replaced) it closes the TCP connection without a Close frame, so clients see code 1006 and should reconnect. Same as Envoy, nginx and HAProxy.
  • AllowedOrigins is the defence against Cross-Site WebSocket Hijacking: a handshake with an Origin not in the list gets 403. Each entry is scheme://host[:port], no path, wildcard or trailing slash ("null" only when written). A request without Origin is allowed, because every browser sends it and other clients do not: the list is not authentication. nocleye check warns when a WebSocket server has none and a route reaching it forwards cookies.
  • Backends that compare Origin with Host (the default of many libraries) reject browsers behind the gateway, because the backend receives its own host. Set PreserveHost: true in the route’s header rule or relax the backend’s check.

A server with HTTP and GRPC on an http:// URL needs a backend that answers HTTP/1.1 and h2c on the same port, nocleye check warns about it. The warning is not shown for https:// (ALPN picks the protocol) or when there is no explicit HTTP block.

Routes live under ServerRoutes, keyed by a name of your choice. At least one is required. A route is matched by path, by header, or by both, and can reshape the request before it is forwarded.

ServerRoutes:
auth-v1:
TargetServer: auth-server
MatchOptions:
PathPattern: /api/auth
BeforeForwarding:
RemovePathPattern: true
AddPathPrefix: /api/v1
beta-users:
TargetServer: auth-server-beta
MatchOptions:
Header:
Name: X-Version
Value: beta
Priority: 10
BeforeForwarding:
RemoveHeader: true
AddHeader:
Header: X-Route
Value: beta-users
Key Required Description
TargetServer yes Name of a server in ServerConfigs.
MatchOptions yes How the route is matched. At least one of PathPattern or Header is required. See below.
BeforeForwarding no Changes applied to the request before it is forwarded. See below.
HeaderRule, ClientIDRule, AuthMethod no Override the server and global value for this route.
UsageControlRules no Usage control rules applied to this route.
UsageControlMode no Cascade (default) or Strict. See usage control.
RequiredScopes no Scopes the caller’s token must hold on this route. See Authentication.
ScopesMode no Additive (default) or Override. See Authentication.
Key Description
PathPattern Path prefix this route handles, e.g. /api/users.
Header.Name Name of the request header to look at. Case insensitive. Must be a valid header name, and can’t be Host.
Header.Value Value to compare with. Case sensitive.
Header.Mode Exact (default), Prefix or Suffix.
Header.Priority 1 to 255. 1 is the highest priority and 255 the lowest. When several header routes match, the highest priority (the smallest number) wins. Omitted means 255, the lowest. Must be unique across all header routes, so only one route can omit it.

A route with both PathPattern and Header matches when either one matches.

Matching runs in two passes:

  1. Header pass. Among the routes whose header matches the request, the one with the highest priority wins (Priority: 1 is the highest, 255 the lowest).
  2. Path pass. Only if no header route matched. A request matches a route when its path starts with the route’s PathPattern, on a path segment boundary, and the longest PathPattern wins. Routes without a PathPattern are skipped.

Other rules:

  • Two routes with exactly the same PathPattern are an error.
  • Two header matches with the same Name, Mode and Value, or with the same Priority, are an error. Routes can share a header Name as long as Mode or Value differ.
  • A request that matches no route gets 404.
  • Paths containing . or .. segments are rejected with 400.
Key Description
RemovePathPattern true removes PathPattern from the path before forwarding. Only applies when the route matched by path, after a header match the path is forwarded untouched. Needs a PathPattern. Default false.
AddPathPrefix Prefix added to the path before forwarding. Must start with / and not end with /. Always applied, after the pattern is removed.
RemoveHeader true drops the header used to match the route. Only applies after a header match, and needs MatchOptions.Header. nocleye check warns when it removes Authorization or Cookie.
AddHeader Header and Value of a header added to the forwarded request. Always applied, and not affected by the header rule of the route. See below.

AddHeader can’t use headers the gateway or HTTP manage: X-Nocleye-* and identity headers like X-User-Id or X-Tenant, hop-by-hop and framing headers like Connection, Content-Length or Host, X-Forwarded-*, Forwarded and trace headers. The name can’t contain underscores and the value can’t contain line breaks or other control characters. nocleye check warns when it sets the same header the route matched on.

The path the backend receives is built in two steps:

  1. If RemovePathPattern is true and the route matched by path, PathPattern is removed from the start of the path.
  2. If AddPathPrefix is set, it is added to the start of the result.
Request path PathPattern Remove Add Prefix Backend receives
/api/auth/login /api/auth true /api/v1 /api/v1/login
/api/checkout/pay /api/checkout false /v1 /v1/api/checkout/pay
/a/open/status/500 /a/open true none /status/500

The query string is always forwarded unchanged.

The gateway adds X-Forwarded-For, X-Forwarded-Host and X-Forwarded-Proto to forwarded requests, and a request ID header, X-Nocleye-Request-Id, that is also written to the access log. It also sends X-Nocleye-Authenticated (true or false) on every request, see Authentication. Any X-Forwarded-* value sent by the client is discarded, unless the request comes from a trusted proxy.

The gateway never compresses or decompresses a body. Accept-Encoding is forwarded as the client sent it (and not added when the client sent none), and the backend’s Content-Encoding and body reach the client byte for byte.

When the backend answers with a Location header, the gateway rewrites it so clients that follow redirects stay on the gateway and internal addresses don’t leak. The rewrite is the inverse of the route’s path rewriting:

Location from the backend Client receives
Absolute URL with the backend’s own host and port, http://backend:9090/api/v1/login The client’s own scheme and Host, with the public path: https://gw.example.com/api/auth/login
Path starting with /, /api/v1/login The public path: /api/auth/login
Relative path (login), another host, or //host/path Unchanged

AddPathPrefix is removed and PathPattern is put back (when RemovePathPattern is true). The query string and fragment are kept, and the rewrite applies to every status code.

The Domain and Path of Set-Cookie headers are rewritten the same way. Content-Location and Refresh are not rewritten.

The rewrite only knows the route that served the request. Keep in mind:

  • A redirect to another backend behind the same gateway is not mapped: the client receives the other backend’s own address. The backend should send a public URL (or a relative one) instead.
  • A path starting with / is always taken as a path on the same backend. If it is outside the AddPathPrefix of the route, PathPattern is still put back in front of it.
Status When
400 Path contains . or .. segments, the request is malformed (see below), or it carries an Upgrade the server does not accept.
414, 431 The request line or the headers are too large.
401 Authentication failed (a missing credential, unless the method has AllowAnonymous, or an invalid or expired one), or none of the route’s client ID rule modes found an identifier in the request.
403 A scope is missing, or a WebSocket Origin is not allowed.
404 No route matches the path.
405, 415 A gRPC server got a request that is not a gRPC POST (gRPC).
413 The request body is above MaxRequestBodySize.
426 A WebSocket server got a request that is not a handshake.
429 A usage control limit was exceeded.
502, 504 The backend could not be reached, or did not answer in time.
503 MaxStreams reached, or the gateway is shutting down.

A request that looks like gRPC gets these as gRPC statuses instead, see gRPC.

The gateway parses HTTP/1.1 itself and forwards a clean request, never the raw bytes it received. Requests that break framing rules are rejected with 400: duplicate or invalid Content-Length, an unsupported Transfer-Encoding, NUL or CR characters in headers, a space before the colon of a header, and CONNECT.

Two ambiguous cases are normalized, not rejected:

  • A request with both Content-Length and Transfer-Encoding: chunked is accepted. The gateway removes Content-Length and the backend receives only the chunked body, as RFC 9112 allows. The backend never sees both headers, so this can’t be used for request smuggling. Other gateways, like nginx and Envoy, answer 400 here.
  • An obsolete folded header line (a value continued on the next line) is joined into a single line before it is forwarded.