diff --git a/README.md b/README.md index dabbf1f..bcc6547 100644 --- a/README.md +++ b/README.md @@ -103,8 +103,8 @@ The release has `proxyfile-linux-amd64`, `proxyfile-linux-arm64`, `proxyfile-dar `proxyfile-darwin-arm64`, with `checksums.txt` and `proxyfile.schema.json` beside them. ```sh -curl -fsSLO https://github.com/kitecorp/proxyfile/releases/download/v2.2.0/proxyfile-linux-amd64 -curl -fsSLO https://github.com/kitecorp/proxyfile/releases/download/v2.2.0/checksums.txt +curl -fsSLO https://github.com/kitecorp/proxyfile/releases/download/v2.4.0/proxyfile-linux-amd64 +curl -fsSLO https://github.com/kitecorp/proxyfile/releases/download/v2.4.0/checksums.txt shasum -a 256 -c --ignore-missing checksums.txt install -m 0755 proxyfile-linux-amd64 /usr/local/bin/proxyfile ``` @@ -112,13 +112,13 @@ install -m 0755 proxyfile-linux-amd64 /usr/local/bin/proxyfile In a Dockerfile, copy the program out of the image. The image holds `/proxyfile` and nothing else. ```dockerfile -COPY --from=ghcr.io/kitecorp/proxyfile:2.2.0 /proxyfile /usr/local/bin/proxyfile +COPY --from=ghcr.io/kitecorp/proxyfile:2.4.0 /proxyfile /usr/local/bin/proxyfile ``` With Go installed (the Go version `go.mod` names or newer): ```sh -go install github.com/kitecorp/proxyfile/v2/cmd/proxyfile@v2.2.0 +go install github.com/kitecorp/proxyfile/v2/cmd/proxyfile@v2.4.0 ``` ## Commands diff --git a/conformance/client_test.go b/conformance/client_test.go index cd33c25..af84dc1 100644 --- a/conformance/client_test.go +++ b/conformance/client_test.go @@ -251,10 +251,15 @@ func (w *world) offering(offer tlsOffer) *http.Client { } // readEcho returns what the stub that wrote the answer received, or nil when no stub wrote it: a stub's echo is a -// JSON object naming its service, sent as field 1 of the message when the answer is gRPC. +// JSON object naming its service, sent as field 1 of the message when the answer is gRPC, and so as field 1 of the +// whole body when the answer is a Connect call's in protobuf, which the Connect bridge makes of the stub's gRPC answer +// by taking the message out of its frame. func readEcho(contentType string, body []byte) *echo { - if strings.HasPrefix(contentType, "application/grpc") { + switch { + case strings.HasPrefix(contentType, "application/grpc"): body = field1(body) + case contentType == "application/proto": + body = messageField1(body) } var e echo if json.Unmarshal(body, &e) != nil || e.Service == "" { @@ -269,7 +274,7 @@ func readEcho(contentType string, body []byte) *echo { } // field1 returns the bytes of field 1 of the one message in a gRPC body, or nil. The body is a flag byte, the -// message's length as a big-endian uint32 and the message; field 1 is the tag 0a, a varint length and the bytes. +// message's length as a big-endian uint32 and the message. func field1(body []byte) []byte { if len(body) < 5 { return nil @@ -279,7 +284,11 @@ func field1(body []byte) []byte { if uint64(len(message)) < uint64(length) { return nil } - message = message[:length] + return messageField1(message[:length]) +} + +// messageField1 returns the bytes of field 1 of message, or nil: the tag 0a, a varint length and the bytes. +func messageField1(message []byte) []byte { if len(message) < 2 || message[0] != 0x0a { return nil } diff --git a/conformance/scenarios_test.go b/conformance/scenarios_test.go index 5488cfd..c460dcd 100644 --- a/conformance/scenarios_test.go +++ b/conformance/scenarios_test.go @@ -2,6 +2,7 @@ package conformance import ( "crypto/tls" + "encoding/base64" "fmt" "maps" "math/rand/v2" @@ -16,7 +17,7 @@ import ( // wait beside the rest of their own scenario alone: a later scenario's quiet and burst count on nothing else reaching // the proxy meanwhile. The rate limit runs last, so the requests the scenarios before it send to its route come first, // and its quiet lets that route's bucket fill again before its burst. -var scenarios = []scenario{routing, mutualTLS, cors, unlisted, auth, toldScheme, timeout, retry, gRPC, paths, asWritten, offRoute, clientKeys, hash, tracing, tracingRetried, rateLimit, cost, backendLimits, traffic} +var scenarios = []scenario{routing, mutualTLS, cors, unlisted, auth, toldScheme, timeout, retry, gRPC, requestLimit, paths, asWritten, offRoute, clientKeys, hash, tracing, tracingRetried, rateLimit, cost, backendLimits, traffic} // get is a GET over HTTP/1.1 to localhost, a host of the example's local environment. func get(path string) request { @@ -2427,6 +2428,159 @@ var gRPC = scenario{name: "gRPC", "failure_mode_allowed": logText("true"), "route": logText("shop"), "status": logNumber(200)}}}}, }} +// requestLimit: a method's request limit, rpc.methods[].max_request_bytes, on conformance/testdata/request-limit.yaml +// and on examples/full, each of which limits example.shop.v1.CartService/AddItem to 2,048 bytes. Every value as +// measured on Envoy 1.40.2 with the buffer filter and the routes the Envoy output writes for a limit, at a limit of +// 2,048 bytes. A Connect call's body counts with the 5 bytes of the gRPC prefix the bridge writes before it, as a gRPC +// call's frame does, so a body or a message of exactly the limit is served and one byte more is refused: a Connect call +// with 413 in plain text, and a gRPC call over HTTP/1.1, the form a proxy in front speaking HTTP/1.1 sends, with HTTP +// 200 and grpc-status 2. A compressed request is refused whatever its size, before any filter counts its bytes: a +// Connect call with 415, and a gRPC call with grpc-status 2. A limited method takes its message in a request body only: +// a Connect GET, whose message is in the query, where the buffer filter counts nothing, is answered 405 with allow: +// POST, a POST or a DELETE with no body and its message in the query is answered 400, and a call in the Connect +// streaming form, which names its compression in connect-content-encoding, is refused as the other compressed calls +// are, with 415. Those rows were written before the routes that answer them: through the routes written before them, +// Envoy 1.40.2 answered the GET with the stub's 200 and the streaming call with a 200 no stub wrote, and with the GET's +// route in place it answered the POST and the DELETE with the stub's 200. A compression header written on two lines, +// identity on one and gzip on the other, is refused in either order as the one line gzip is: Envoy 1.40.2 matches each +// value of such a header on its own, and a service may read either line. A call that names identity alone is served. +// A Connect unary body the bridge does not frame, one sent without connect-protocol-version, is counted without the +// 5-byte prefix, so up to the limit and 5 bytes of it reach the service and one byte more is refused. Each refused row +// wants an answer no stub wrote; the battery reads no list of the calls a stub received, so no row shows that the stub +// never received one. Only Envoy's entry runs the scenario, as the nginx and HAProxy generators refuse the key. +var requestLimit = scenario{name: "a method's request limit", + exchanges: []exchange{ + {name: "a Connect call whose body is the limit is served", keys: requestLimitKeys, send: connectCall(2048, nil), + want: answer{status: 200, service: "shop", port: "8081", proto: "HTTP/2.0", path: limitedPath}}, + {name: "a Connect call whose body is one byte over the limit is answered 413 in plain text", keys: requestLimitKeys, + send: connectCall(2049, nil), + want: answer{status: 413, headers: map[string]string{"content-type": "text/plain"}, ownBody: "Payload Too Large"}}, + {name: "a gRPC call over HTTP/1.1 whose message is one byte over the limit is answered grpc-status 2", keys: requestLimitKeys, + send: grpcOverHTTP1(2049), + want: answer{status: 200, grpcStatus: "2", headers: map[string]string{"grpc-message": "Payload Too Large"}}}, + {name: "a Connect call with content-encoding gzip is answered 415", keys: requestLimitKeys, + send: connectCall(16, map[string]string{"content-encoding": "gzip"}), want: answer{status: 415}}, + {name: "a gRPC call with grpc-encoding gzip is answered grpc-status 2", keys: requestLimitKeys, + send: request{proto: "grpc", method: "POST", host: "localhost", path: limitedPath, headers: map[string]string{"grpc-encoding": "gzip"}}, + want: answer{grpcStatus: "2"}}, + {name: "a Connect GET whose message is under the limit is answered 405 with allow POST", keys: requestLimitKeys, + send: connectQuery("GET", 16), want: answer{status: 405, headers: map[string]string{"allow": "POST"}}}, + // The bridge reads a message from the query of any request that ends with its headers, whatever its method, so a + // query on the limited path is refused before the bridge for every method but GET, which the 405 takes first. + {name: "a POST with no body and its message in the Connect query form is answered 400", keys: requestLimitKeys, + send: connectQuery("POST", 16), want: answer{status: 400}}, + {name: "a DELETE with no body and its message in the Connect query form is answered 400", keys: requestLimitKeys, + send: connectQuery("DELETE", 16), want: answer{status: 400}}, + // The envelope's flag says its message is compressed; its 16 bytes are not gzip, as the 415 is decided by the + // header alone, before any filter reads the body. + {name: "a call in the Connect streaming form with connect-content-encoding gzip is answered 415", keys: requestLimitKeys, + send: request{proto: "http/1.1", method: "POST", host: "localhost", path: limitedPath, + headers: map[string]string{"content-type": "application/connect+proto", "connect-content-encoding": "gzip"}, + body: framed(1, strings.Repeat("x", 16))}, + want: answer{status: 415}}, + {name: "a gRPC call with grpc-encoding identity then gzip on two lines is answered grpc-status 2", keys: requestLimitKeys, + send: grpcRaw(twice("grpc-encoding", "identity", "gzip")), want: answer{grpcStatus: "2"}}, + {name: "a gRPC call with grpc-encoding gzip then identity on two lines is answered grpc-status 2", keys: requestLimitKeys, + send: grpcRaw(twice("grpc-encoding", "gzip", "identity")), want: answer{grpcStatus: "2"}}, + {name: "a call in the Connect streaming form with connect-content-encoding identity then gzip on two lines is answered 415", + keys: requestLimitKeys, send: streamingRaw(twice("connect-content-encoding", "identity", "gzip")), want: answer{status: 415}}, + {name: "a call in the Connect streaming form with connect-content-encoding gzip then identity on two lines is answered 415", + keys: requestLimitKeys, send: streamingRaw(twice("connect-content-encoding", "gzip", "identity")), want: answer{status: 415}}, + {name: "a Connect call with content-encoding identity then gzip on two lines is answered 415", keys: requestLimitKeys, + send: connectRaw(twice("content-encoding", "identity", "gzip")), want: answer{status: 415}}, + {name: "a Connect call with content-encoding gzip then identity on two lines is answered 415", keys: requestLimitKeys, + send: connectRaw(twice("content-encoding", "gzip", "identity")), want: answer{status: 415}}, + {name: "a gRPC call with grpc-encoding identity is served", keys: requestLimitKeys, + send: request{proto: "grpc", method: "POST", host: "localhost", path: limitedPath, headers: map[string]string{"grpc-encoding": "identity"}}, + want: answer{status: 200, grpcStatus: "0", service: "shop", path: limitedPath}}, + {name: "a Connect body without connect-protocol-version of the limit and 5 bytes is served whole", keys: requestLimitKeys, + send: unframedCall(2053), want: answer{status: 200, service: "shop", path: limitedPath, body: strings.Repeat("x", 2053)}}, + {name: "a Connect body without connect-protocol-version of the limit and 6 bytes is answered 413 in plain text", keys: requestLimitKeys, + send: unframedCall(2054), + want: answer{status: 413, headers: map[string]string{"content-type": "text/plain"}, ownBody: "Payload Too Large"}}, + }} + +// twice is a header written on two lines of a raw HTTP/1.1 request, first then second: the value of the first line, +// then the second line whole, as sendRaw writes a value after its name. +func twice(name, first, second string) map[string]string { + return map[string]string{name: first + "\r\n" + name + ": " + second} +} + +// grpcRaw is a unary gRPC call to limitedPath over HTTP/1.1 sent by hand, so a header may be written on two lines: one +// message of 16 bytes behind the prefix, its flag saying it is compressed, chunked, with the headers in more. +func grpcRaw(more map[string]string) request { + headers := map[string]string{"content-type": "application/grpc", "te": "trailers"} + maps.Copy(headers, more) + return request{proto: "http/1.1", method: "POST", host: "localhost", path: limitedPath, headers: headers, raw: true, + body: framed(1, strings.Repeat("x", 16))} +} + +// streamingRaw is a call to limitedPath in the Connect streaming form over HTTP/1.1 sent by hand: one envelope of 16 +// bytes, its flag saying the message is compressed, chunked, with the headers in more. +func streamingRaw(more map[string]string) request { + headers := map[string]string{"content-type": "application/connect+proto"} + maps.Copy(headers, more) + return request{proto: "http/1.1", method: "POST", host: "localhost", path: limitedPath, headers: headers, raw: true, + body: framed(1, strings.Repeat("x", 16))} +} + +// connectRaw is a Connect unary call to limitedPath over HTTP/1.1 sent by hand: a body of 16 bytes, chunked, with +// protobuf's content type, Connect-Protocol-Version and the headers in more. +func connectRaw(more map[string]string) request { + headers := map[string]string{"content-type": "application/proto", "connect-protocol-version": "1"} + maps.Copy(headers, more) + return request{proto: "http/1.1", method: "POST", host: "localhost", path: limitedPath, headers: headers, raw: true, + body: strings.Repeat("x", 16)} +} + +// unframedCall is a Connect unary call to limitedPath over HTTP/1.1 without Connect-Protocol-Version: the bridge then +// leaves it as it is, so its body of size bytes, framed by its length, goes to the service with no gRPC prefix. +func unframedCall(size int) request { + return request{proto: "http/1.1", method: "POST", host: "localhost", path: limitedPath, + headers: map[string]string{"content-type": "application/proto"}, body: strings.Repeat("x", size)} +} + +// requestLimitKeys are what the rows of a method's request limit depend on: the limit the method writes. +var requestLimitKeys = []string{"rpc.methods[].max_request_bytes"} + +// limitedPath is the path of the method request-limit.yaml and examples/full limit to 2,048 bytes. +const limitedPath = "/example.shop.v1.CartService/AddItem" + +// connectCall is a Connect unary call to limitedPath over HTTP/1.1, as a browser sends one: a body of size bytes framed +// by its length, protobuf's content type, Connect-Protocol-Version and the headers in more. +func connectCall(size int, more map[string]string) request { + headers := map[string]string{"content-type": "application/proto", "connect-protocol-version": "1"} + for name, value := range more { + headers[name] = value + } + return request{proto: "http/1.1", method: "POST", host: "localhost", path: limitedPath, headers: headers, + body: strings.Repeat("x", size)} +} + +// grpcOverHTTP1 is a unary gRPC call to limitedPath over HTTP/1.1: one uncompressed message of size bytes behind the +// 5-byte prefix, framed by its length. +func grpcOverHTTP1(size int) request { + return request{proto: "http/1.1", method: "POST", host: "localhost", path: limitedPath, + headers: map[string]string{"content-type": "application/grpc", "te": "trailers"}, body: framed(0, strings.Repeat("x", size))} +} + +// framed is one message behind the 5-byte prefix a gRPC frame and an envelope of the Connect streaming form share: a +// flag byte, 1 when the message is compressed, and the message's length as a big-endian uint32. +func framed(flag byte, message string) string { + n := len(message) + return string([]byte{flag, byte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n)}) + message +} + +// connectQuery is a request to limitedPath over HTTP/1.1 with method and no body, its message in the query as a Connect +// GET carries it, the form a Connect client may send for a method without side effects: protobuf encoded (field 1 +// holding size bytes, under 128 so its length is one byte) and then base64url encoded without padding. net/http sends +// Content-Length: 0 with a POST or a DELETE and none with a GET (transfer.go, shouldSendContentLength). +func connectQuery(method string, size int) request { + message := append([]byte{0x0a, byte(size)}, strings.Repeat("x", size)...) + return request{proto: "http/1.1", method: method, host: "localhost", + path: limitedPath + "?connect=v1&encoding=proto&base64=1&message=" + base64.RawURLEncoding.EncodeToString(message)} +} + // paths: every value measured on Envoy 1.40.2; no key, because path normalisation is written for every file // (docs/portability.md). A segment that is . or .. followed by ;, or by ; escaped once in either case of hex, is // refused wherever the proxy's normalisation leaves it; ; escaped twice, ; on any other segment and anything in the diff --git a/conformance/targets_test.go b/conformance/targets_test.go index 086be49..586d2c0 100644 --- a/conformance/targets_test.go +++ b/conformance/targets_test.go @@ -66,6 +66,9 @@ var ( // own, which only Envoy's entry runs, as the nginx and HAProxy generators refuse the key; it runs the rows of that // scenario alone. unlistedFile = file{label: "unlisted-origins", proxyfile: "testdata/unlisted-origins.yaml", scenarios: []string{unlisted.name}} + // requestLimitFile is the battery's file with a method's request limit, which only Envoy's entry runs, as the nginx + // and HAProxy generators refuse the key; it runs the rows of that scenario alone. + requestLimitFile = file{label: "request-limit", proxyfile: "testdata/request-limit.yaml", scenarios: []string{requestLimit.name}} ) // haproxyLimitsFile is the battery's file for HAProxy's connection limit, which Envoy's entry and each HAProxy entry @@ -115,6 +118,7 @@ func targets(t testing.TB) []target { limitsFile, connectionFile, unlistedFile, + requestLimitFile, }, image: image, // Envoy writes its log lines to stdout every 10 s by default; every 100 ms, a row that reads them (answer.logged) diff --git a/conformance/testdata/request-limit.yaml b/conformance/testdata/request-limit.yaml new file mode 100644 index 0000000..0ae5916 --- /dev/null +++ b/conformance/testdata/request-limit.yaml @@ -0,0 +1,20 @@ +# yaml-language-server: $schema=../../schema/proxyfile.schema.json +# The conformance battery's file for a method's request limit (rpc.methods[].max_request_bytes): shop's gRPC port at +# its two addresses in the world, the package example.shop.v1 routed to it, and AddItem limited to 2,048 bytes, as +# examples/full limits it, with the Connect bridge on. It runs the scenario of a method's request limit alone, and only +# Envoy's entry runs it: the nginx and HAProxy generators refuse the key. It writes no tls, so the battery's clients +# reach it in plain HTTP. +listen: 10000 +admin: 9901 +services: + shop: + grpc: 8081 + addresses: ["10.0.1.11", "10.0.1.12"] +origins: + local: {hosts: [127.0.0.1, localhost]} +routes: + - rpc: {to: {"example.shop.*": shop}} +rpc: + methods: + - {service: example.shop.v1.CartService, method: AddItem, max_request_bytes: 2048} +envoy: {connect_bridge: true} diff --git a/docs/conformance.md b/docs/conformance.md index 29a92df..dc8df7d 100644 --- a/docs/conformance.md +++ b/docs/conformance.md @@ -26,7 +26,9 @@ found by name, and, with a connection limit, connection` and no `tls`, [`conformance/testdata/connection.yaml`](../conformance/testdata/connection.yaml), which every entry runs but those on nginx's images tagged `-otel`, and, with an environment that puts an origin no list holds to a check of its own, [`conformance/testdata/unlisted-origins.yaml`](../conformance/testdata/unlisted-origins.yaml), -which Envoy's entry alone runs, as the nginx and HAProxy generators refuse its keys. +which Envoy's entry alone runs, as the nginx and HAProxy generators refuse its keys, and, with a method's request +limit, [`conformance/testdata/request-limit.yaml`](../conformance/testdata/request-limit.yaml), which Envoy's entry +alone runs too, as the nginx and HAProxy generators refuse `max_request_bytes`. The nginx entries `nginx-1.30` and `nginx-1.31` run on the images pinned in `scripts/nginx-images`, one entry for each line, and run nginx's own files but those with tracing, `examples/full`, which nginx refuses, `examples/portable` and `connection.yaml`. The nginx entries `nginx-otel-1.30` and `nginx-otel-1.31` run on the images @@ -112,6 +114,11 @@ with an `authorization` header; and its `local` environment writes no `ask_unlis an origin no list holds alone, and Envoy's entry alone runs it, as the nginx and HAProxy generators refuse `ask_unlisted` and `question`. +`request-limit.yaml` writes `shop`'s gRPC port at its two addresses in the world, the package `example.shop.v1` routed +to it with the Connect bridge on, and one method, `example.shop.v1.CartService/AddItem`, limited to 2,048 bytes by +`max_request_bytes`, as `examples/full` limits it. It runs the rows of the scenario a method's request limit alone, and +Envoy's entry alone runs it, as the nginx and HAProxy generators refuse the key. + nginx's `nginx-checks.yaml` is `two-checks.yaml` for nginx: the same check service with two addresses, `when_unavailable: deny`, the `x-api-key` condition and `send_request: true`, with `remove_from_clients` naming `x-request-id` alone, because the nginx generator refuses a name with a `*` prefix there, so each answer the check cannot give runs on nginx under @@ -177,17 +184,17 @@ scenario waits a second before it is sent, so the route's bucket fills again bet serves before it and those from it on, however fast a runner sends them; the comments beside those rows in [`conformance/scenarios_test.go`](../conformance/scenarios_test.go) count the requests each part sends the route, with those routing's and CORS's rows send it before them, against the 20 the bucket of `portable` holds. The scenarios run -in this order: in Envoy's entry 616 rows on `full`, 524 on `portable`, 350 on `nginx-file`, 259 on `nginx-plain`, 381 on +in this order: in Envoy's entry 634 rows on `full`, 524 on `portable`, 350 on `nginx-file`, 259 on `nginx-plain`, 381 on `nginx-checks`, 537 on `nginx-auth`, 576 on `nginx-tracing`, 39 on `nginx-tracing-by-name` and 3 on `nginx-limits`, nginx's own files, 477 on `haproxy-file`, 364 on `two-checks`, 37 on `haproxy-traffic` and 1 on `haproxy-limits`, -HAProxy's own, 11 on `connection` and 20 on `unlisted-origins`; in each nginx entry on the plain image 350 on -`nginx-file`, 259 on +HAProxy's own, 11 on `connection`, 20 on `unlisted-origins` and 18 on `request-limit`; in each nginx entry on the +plain image 350 on `nginx-file`, 259 on `nginx-plain`, 381 on `nginx-checks`, 537 on `nginx-auth`, 524 on `portable`, 3 on `nginx-limits` and 11 on `connection`; in each nginx entry on the image tagged `-otel` 576 on `nginx-tracing` and 39 on `nginx-tracing-by-name`; and in each HAProxy entry 477 on `haproxy-file`, 364 on `two-checks`, 12 on -`haproxy-traffic`, 1 on `haproxy-limits` and 11 on `connection`. That is 4,195 rows in Envoy's entry, 2,065 in each +`haproxy-traffic`, 1 on `haproxy-limits` and 11 on `connection`. That is 4,231 rows in Envoy's entry, 2,065 in each nginx entry on the plain image, 615 in each nginx entry on the image tagged `-otel` and 865 in each HAProxy entry, -11,285 in all, and each passes. The battery counts these rows, and those each scenario's line in the table below +11,321 in all, and each passes. The battery counts these rows, and those each scenario's line in the table below gives for each file of Envoy's entry, before any container starts, and fails when one of these numbers is not what it counts. Before nginx wrote rate limits, RPC retries, balance, hash and DNS names the same entries ran 3,041, 1,310 and 791 rows: 40 rows were added, among them the scenarios client keys and hash, nginx's files gained the traffic @@ -232,7 +239,9 @@ with an empty `Origin` and one from a listed origin in capitals, which run on `u origin check admitted an `http` origin too they ran 4,192, 2,065, 615 and 865: one row was added in that scenario, a request from `http://files.acme.example`, which runs on `unlisted-origins`. Before an own host on another scheme or port was put to the check they ran 4,193, 2,065, 615 and 865: two rows were added in that scenario, from -`http://api.example.com` and from `https://api.example.com:8443`, which run on `unlisted-origins`. In order: +`http://api.example.com` and from `https://api.example.com:8443`, which run on `unlisted-origins`. Before a method's +request limit they ran 4,195, 2,065, 615 and 865: `request-limit.yaml` was added with the scenario a method's request +limit, whose 18 rows run on it and on `full`, which limits the same method. In order: | Scenario | Keys | What its rows check | |---|---|---| @@ -245,6 +254,7 @@ port was put to the check they ran 4,193, 2,065, 615 and 865: two rows were adde | timeout | `auth.timeout`, `auth.when_unavailable`, `timeouts.idle` | The check holds the request for 3 s, past `auth.timeout`'s 1500 ms, and its `401`, and its `200`, send their body of 100 bytes a byte every 100 ms, so it ends after 10 s. The request reaches the service with the mark of a request the check could not answer under `allow`, and is answered `403` under `deny`, on `two-checks` and `nginx-checks`, after at least 1.45 s and in under 2.95 s, 50 ms inside the two times because the row reads a different clock from the proxy's and the check's (below). With `timeouts.idle`, 2 s on `nginx-file`, `nginx-auth`, `nginx-tracing` and `haproxy-traffic` and 90 s on `full` and `portable`, the rows of the idle time run too. In "a service silent past the idle time" the stub holds its answer for 3 s (`x-stub-delay: 3s`), and Envoy and nginx answer `504` as `text/plain`, Envoy's own text where nginx's own page would be `text/html`, after at least 1.95 s and under 2.95 s (measured at 2.002 to 2.005 s on Envoy 1.40.2 and on nginx), where `full` and `portable` serve it with `200` after 2.95 s or more. In "an answer that pauses less than the idle time" the stub sends the status and headers, then a space after each of two pauses of 1.25 s (`x-stub-trickle: 2x1250ms`), then its echo: each pause is 0.75 s under the idle time and the answer ends 0.5 s past it, so a limit on the whole answer would end it, and every proxy serves it with `200` after at least 2.45 s. In "a request body that pauses past the idle time" a `POST` with `Content-Length: 4` is sent by hand, `ab`, then `cd` after 3 s: Envoy answers `408` after at least 1.95 s, so the row shows the idle time ended it, where nginx closes the connection with no answer, a declared difference on `timeouts.idle`, and `full` and `portable` serve it with `200` and the body `abcd`. Each bound keeps 50 ms from the time it tests, for the two clocks, and the `504` comes within 1 s past the idle time, for a loaded runner. In Envoy's entry: 6 rows on `full`, `portable`, `nginx-auth` and `nginx-tracing`, 3 on `haproxy-file`, `two-checks` and `nginx-checks`, which write no `timeouts.idle`, and 3 on `nginx-file` and `haproxy-traffic`, which write no check. | | retry | `routes[].retries`, `routes[].rpc.retries` | A request that reached the service is never tried again: a first try the service closes before any answer gives `502`, a gRPC call whose first try is reset gives `grpc-status` `14`, and a `503` from the service is passed on from its first try. A request whose connection a backend refused is tried again on the other: with one of the two shop backends refusing connections, 40 requests to the shop route and 40 gRPC calls to shop are each answered by the other backend; on `nginx-file`, whose shop route writes `retries: 0`, each of the 40 requests to the shop route is answered `502` with no service, as no other backend is tried, or by the backend that is up, and at least one of each, so a proxy that answered every request `502` would fail the row. On `nginx-plain`, whose rpc entry retries once and sends `example.hold.*` to the two backends that take no connection, a call is answered `200` with `grpc-status` `14` after at least 9.95 s and under 10.95 s, the two tries' connect time of 5 s each, and a request to its route `/held/`, which retries once to the same backends, `502` in the same bounds, which a script that found the route's time spent after the first try (`504` at 5 s) or a missing copy for the second try (`500`) fails; on the other files, which list no such method and no such route, both reach the shop route's service. A gRPC call that is not `POST`, a `GET` with gRPC's content type over HTTP/1.1 whose first try the service closes, is answered `200` with `grpc-status` `14` and not tried again. `nginx-auth`, `nginx-checks` and `nginx-plain`, whose shop routes write no retries, get `nginx-file`'s answers there. The rows of a retried route send to `/retried/products/1`, the route `/retried/` of `nginx-file`, `nginx-auth` and `nginx-checks` and the shop route of `full`, which retries; `nginx-plain` serves it by its shop route, which tries each request once, so there each answer is `502` or the other backend's, and at least one of each. nginx reads whole before the first try of a retried route a body with a length of at most 1 MiB and a request with no body, and sends any other, one in chunks among them, as it arrives and tries it once ([nginx](nginx.md#retries)). With one shop backend refusing connections, 40 requests are each answered by the other, and 40 `POST`s with neither `Content-Length` nor `Transfer-Encoding`; of 40 `GET`s whose 180,000 bytes come in one-byte chunks, each reaches the other backend whole through Envoy, which tries it again, and nginx answers `502` each one the refusing backend drew and serves the others, a declared difference; 40 `PUT`s of 1 MiB each reach it whole; of 40 `PUT`s of 1,048,577 bytes, one more than Envoy's buffer for a retry, at least one is answered `507` by Envoy and `502` by nginx, which tries it once, a declared difference; of 40 chunked `PUT`s, and of 40 over HTTP/2 with no content-length, at least one reaches the other backend with its body through Envoy, which tries again a body under its bound, and at least one is answered `502` by nginx, a declared difference. A row that needs the refusing backend drawn, or each backend, sends 40 requests, so a backend drawn at random is missed with a chance of 2^-40. A `PUT` whose first try the service closed once it arrived is answered `502` and not tried again, over HTTP/1.1 and over HTTP/2. A request whose every backend refuses is answered `502` and writes one upstream-failure line, with the flags `URX,UF`, its route and the status `502`, on Envoy and on both nginx versions; the line carries no request id, so the row finds it by route and status among the lines the proxy wrote after the row began. A `PUT` of 1,048,577 bytes with no backend refusing is served once, whole. In Envoy's entry: 19 rows on `full` and `nginx-file`, 18 on `nginx-plain`, which writes no `log`, 15 on `nginx-auth` and `nginx-tracing`, which write no `routes[].rpc.retries`, 15 on `haproxy-traffic`, whose rpc entry writes no retries, and 14 on `nginx-checks`, which writes neither `log` nor `routes[].rpc.retries`; `portable` writes no retries. | | gRPC | `routes[].rpc`, `routes[].rpc.to`, `routes[].rpc.to.`, `routes[].rpc.to..service`, `rpc.methods`, `rpc.methods[].service`, `rpc.methods[].method`, `rpc.methods[].action`, `rpc.methods[].reports`, `services..grpc`, `auth.ask`, `auth.when_unavailable`, `log` | A method of a package mapped to `shop` reaches shop's gRPC port over HTTP/2 and answers `grpc-status` `0`; a method of any other package reaches `accounts`; the check is told a method's action and reports, and not an action the client sent, and the service receives neither; a gRPC service's `X-Accel-Redirect` is passed on, not followed; a call through a `..` segment reaches the method's path; a call whose service refuses the connection on every backend is answered `200` with `grpc-status` `14`, `content-type` `application/grpc` and no `grpc-message`; a call whose service resets its stream is answered the same, with Envoy's and HAProxy's `grpc-message` naming the reset, where nginx sends none, a declared difference, and a request that is not a gRPC call, sent to that route, `503` with Envoy's text, where nginx and HAProxy answer `502` with no body, a declared difference; a call the check denies is answered in gRPC's form, `200` with `grpc-status` `16` and the denial's body in `grpc-message`, percent-encoded where it holds a `%`, a letter outside ASCII or a line feed. A call the check denies with `403` is answered `200` with `grpc-status` `7`; a call the check cannot answer goes on with the unchecked mark under `allow`, and is answered `200` with `grpc-status` `7` under `deny`; a call whose check's answer cannot be read is a check that could not answer; and a call the check cannot answer logs an unanswered check with the method's action. A call whose accepted header the check sends empty reaches the service with that header empty, where nginx sends a gRPC service none, a declared difference. In Envoy's entry: 16 rows on `full`, `portable`, `nginx-auth` and `nginx-tracing`, 15 on `haproxy-file`, which writes no `log`, 11 on `two-checks` and `nginx-checks`, which write neither that nor `rpc.methods[].action`, and 7 on `nginx-file` and `nginx-plain`, which write no `rpc.methods[].action` and no `auth.ask`. | +| a method's request limit | `rpc.methods[].max_request_bytes` | On `request-limit` and `full`, each of which limits `/example.shop.v1.CartService/AddItem` to 2,048 bytes: a Connect call over HTTP/1.1 whose body is exactly the limit is served by `shop`; one whose body is a byte longer is answered `413` with `content-type: text/plain` and the body `Payload Too Large`; a gRPC call over HTTP/1.1 whose message is a byte over the limit is answered HTTP `200` with `grpc-status` 2 and `grpc-message: Payload Too Large`; a Connect call with `content-encoding: gzip` is answered `415`, and a gRPC call over HTTP/2 with `grpc-encoding: gzip` gets `grpc-status` 2; a Connect GET whose message, in the query, is under the limit is answered `405` with `allow: POST`, a `POST` and a `DELETE` with no body and their message in the query as a Connect GET carries it are answered `400`, and a call in the Connect streaming form with `connect-content-encoding: gzip` is answered `415`. A compression header written on two lines, `identity` on one and `gzip` on the other, is refused in either order as the one line `gzip` is: `grpc-encoding` in a gRPC call over HTTP/1.1 with `grpc-status` 2, and `content-encoding` in a Connect call and `connect-content-encoding` in a call in the Connect streaming form with `415`; a gRPC call over HTTP/2 with `grpc-encoding: identity` alone is served. A Connect call over HTTP/1.1 without `connect-protocol-version`, whose body the bridge does not frame, is counted without the 5-byte prefix: a body of the limit and 5 bytes reaches `shop` whole, and one of the limit and 6 bytes is answered `413` with `Payload Too Large`. Each refused row wants an answer no stub wrote; the battery reads no list of the calls a stub received. In Envoy's entry: 18 rows on `full` and `request-limit`. | | path normalisation | none: it is written for every file ([Written with no key](portability.md#written-with-no-key)) | `..`, `.`, `//`, `%2F` and `%2e%2e` in a path are resolved before a route is picked, and the service hears the normalised path; so are `..` followed by an escaped slash (`..%2f`), by a backslash written as `%5C`, and by a written backslash; `..;` and `.;`, written with dots, resolved as `..` and `.`, which nginx and HAProxy answer `400`, a declared difference; an exact path reached through `..`. An invalid escape, `%zz`, is passed on to the service, whose own `400` answers it, and nginx answers it `400` itself, a declared difference. An escaped `+` and an empty query reach the service as sent; an empty query after a path that needs normalising reaches it after the normalised path, and nginx answers it `400`, a declared difference. A path that still holds a dot segment with a `;` parameter after normalisation answers `400` and reaches no service, the `;` written or escaped once: `/catalog/%2e%2e;/products/1`; `..%3B` and `..%3b`; `.%3B` and `%2e%3b`; dots written escaped, in either case of hex, before an escaped `;`; an escaped `;` with a value or twice over; on the last segment and on the first; between backslashes, written or as `%5C`; and before an escaped slash. These reach the service as sent: a `;` parameter on an ordinary segment, on a name and on a name that starts with a dot; a `;` and an escaped `;` after three dots; an escaped `;` after a name that ends in two dots and inside a name; a `;` escaped twice after `..`; a query that holds `/..;/` or `/..%3B/`; and an escaped `?` after `..`. A dot segment with an escaped `;` that a `..` after it removes reaches the service resolved, and nginx answers it `400`, a declared difference. A path with an empty segment before a dot-dot segment, `/catalog//../products/1`, reaches `catalog` as `/catalog/products/1` through Envoy and HAProxy, where nginx answers `400`, a declared difference, and so does the same path with the slash escaped, `/catalog/%2F../products/1`, and over HTTP/2; an empty segment after a dot-dot segment, `/products/../catalog//items`, reaches `catalog` as `/catalog/items` through every proxy. After the `400` of a dot segment with an escaped `;`, sent with a body that holds a second request and then the client's next request in the same write, Envoy closes the connection and answers no next request, as nginx does, where HAProxy keeps the connection and answers the next request, a declared difference. In Envoy's entry: 47 rows on `full`, `portable`, `nginx-file`, `nginx-plain`, `haproxy-file`, `two-checks`, `nginx-checks`, `nginx-auth` and `nginx-tracing`. | | the path as the client wrote it | none: it is written for every file ([Written with no key](portability.md#written-with-no-key)) | A path with nothing to normalise, or with only an escape Envoy keeps, is matched and reaches the service as written: `/api/x%3Bv=1/admin`, `/api/a%20b/admin`, `/u/%40bob`, `/l/a%20b` and `/api/a%7cb`, in the case of hex written, where nginx's and HAProxy's own files have patterns that would take the decoded character; `/x%C3%A9` is not taken by the pattern `^/x..$`; an empty query on such a path reaches the service as sent. A path that needs normalising and keeps no escape is matched and sent normalised. A raw `\|` reaches the service as `%7C`. nginx answers `400`, each a declared difference, to a path that needs normalising and keeps an escape, `/api/a%2fb%3bc`; to a byte Envoy escapes beside an escape; to a byte Envoy escapes on `nginx-file`, which has pattern routes; to an escape and to an empty query on a route with a `rewrite`; and to an empty query after a byte Envoy escapes. A `#` in the target is answered `400` over HTTP/1.1 and HTTP/2, where HAProxy resets the HTTP/2 stream, a declared difference, and so is one to a host no environment names, before its `404`. An escaped NUL, `%00`, in the path is answered `400`, and a byte above 0x7F sent raw over HTTP/2 reaches the service escaped, `%C3%A9` for `é`, which nginx answers `400` on `nginx-file`, a declared difference. In Envoy's entry: 21 rows on `full`, `portable`, `nginx-file`, `nginx-plain`, `haproxy-file`, `two-checks`, `nginx-checks`, `nginx-auth` and `nginx-tracing`. | | an auth-off prefix route | `routes[].prefix`, `routes[].auth`, `auth.ask`, `auth.only_with_header`, `auth.accept`, `auth.send_request` | On `portable`, which sends `/public/` to `shop` with `auth = off` before its other prefix routes: a path under it reaches the service unchecked with a token the check denies, and so does one with a repeated slash, which the service hears merged; a client's own copy of the mark of a request the check could not answer does not reach the service there either. A path that `..`, `%2e%2e`, `..%2f`, `..%5C` or `..\` takes out of `/public/` leaves the route: with a token the check denies it gets the check's `401`, and with a token the check allows it reaches the service, and the check is told the path the service hears, the normalised one; without the normalisation each would stay on the route and reach the service unchecked. `..;` with a token the check denies leaves the route too and gets the check's `401`, and so does an empty segment before a `..`, `/products//../public/readme`, written or, over HTTP/2, escaped, which the `..` removes, where nginx answers `400`, a declared difference. A dot segment with a `;` parameter is answered `400` and reaches no service with no token and with a token the check allows, the `;` written after `%2e%2e` or escaped as `%3B` after `..`. On `full`, which has no such route, the first and the third are answered `401` by the check its shop route asks. A client's own user, question and unchecked mark do not reach the service on that route either, and a request to it logs no check time. In Envoy's entry: 22 rows on `full`, `portable`, `nginx-auth` and `nginx-tracing`, and 21 on `haproxy-file`, which writes no `log`. | diff --git a/docs/editors.md b/docs/editors.md index c571857..fdc4faa 100644 --- a/docs/editors.md +++ b/docs/editors.md @@ -5,7 +5,7 @@ HOCON proxyfile, see [Editor support](#editor-support) below. Put this line firs use the YAML language server, such as VS Code with the YAML extension: ```yaml -# yaml-language-server: $schema=https://raw.githubusercontent.com/kitecorp/proxyfile/v2.2.0/schema/proxyfile.schema.json +# yaml-language-server: $schema=https://raw.githubusercontent.com/kitecorp/proxyfile/v2.4.0/schema/proxyfile.schema.json ``` In a JetBrains IDE, open Settings, Languages & Frameworks, Schemas and DTDs, JSON Schema Mappings. Add a mapping with the diff --git a/docs/format.md b/docs/format.md index 1eb00a8..ea3c9e9 100644 --- a/docs/format.md +++ b/docs/format.md @@ -97,7 +97,7 @@ rpc: methods: - {service: example.shop.v1.CartService, method: GetCart, action: browse} - {service: example.accounts.v1.ProfileService, method: GetProfile} - - {service: example.shop.v1.CartService, method: AddItem, action: buy, reports: [browse]} + - {service: example.shop.v1.CartService, method: AddItem, action: buy, reports: [browse], max_request_bytes: 2048} log: {status_from: 400, sample: 1%} tracing: provider: @@ -263,3 +263,11 @@ writes none: the check is told the connection's scheme, whatever the client writ `:scheme` or its own `X-Forwarded-Proto` ([What the check is told](auth.md#what-the-check-is-told)), where 2.2.0 told it the request's own. Such an nginx file's `nginx.conf` changes too. Until a file is rendered again, `proxyfile check` reports its 2.2.0 output as different. HAProxy's files do not change. + +## After 2.3.1 + +2.4 adds one key, `rpc.methods[].max_request_bytes`, which a `.proto` option's message can hold as a field of that name +too: the largest request message a method is passed ([A method's request limit](limits.md#a-methods-request-limit)). A +file that sets it nowhere renders byte for byte as 2.3.1 renders it, for each target, and so does its RPC table. +`--target nginx` and `--target haproxy` refuse a file that sets it, naming the key where it is written, in the +proxyfile, a methods file or a `.proto` file; leave it out, or render the file for Envoy. diff --git a/docs/limits.md b/docs/limits.md index 89992e9..e6840a1 100644 --- a/docs/limits.md +++ b/docs/limits.md @@ -1,6 +1,7 @@ # `limits` -`limits` caps the gateway's connections and the header block of a request. A size is written as +`limits` caps the gateway's connections and the header block of a request; [a method's request +limit](#a-methods-request-limit) is written on the method. A size is written as [the format](format.md#sizes-times-and-percentages) says, and [Defaults](defaults.md) says when the overload manager runs. The heap budget is [`envoy.heap`](envoy.md#envoyheap), because only Envoy's overload manager has one. @@ -13,3 +14,78 @@ runs. The heap budget is [`envoy.heap`](envoy.md#envoyheap), because only Envoy' | `limits.request_headers.size` | The largest header block of a request. | Required. A size such as 96KiB. At most `8MiB`. | core | | `limits.request_headers.count` | The most header fields in a request. | Required. A whole number from 1 to 4294967295. | core | + +## A method's request limit + +`rpc.methods[].max_request_bytes`, or the field of that name of the message of the option `rpc.proto` names, is the +largest request message, in bytes as serialized, the gateway passes to one RPC method ([`rpc`](rpc.md)): a whole +number from 1 to 4294967290. A method that does not write it has no limit. Only the Envoy output writes it; nginx and +HAProxy refuse it ([Portability](portability.md)). + +The Envoy output turns on Envoy's buffer filter on the method's route, with the limit and the 5 bytes of the gRPC +prefix, which a gRPC call's frame carries and the Connect bridge writes before the body of a Connect call it converts, +so in those calls a message of exactly the limit is served and one byte more is refused. A method with a limit takes +its message in a request body only, so five routes on the method's path come before its own. The first answers `405` +with `allow: POST` to a `GET`, and the second `400` to a request of any other method whose path carries a query +string: the Connect bridge builds a message from the query of a request that has no body, whatever its method, and +the filter counts no byte of it. No gRPC call and no Connect call with a body carries a query; a browser's preflight +`OPTIONS` to the method's path with a query gets the `400` too. The other three answer `415` to a request whose +`grpc-encoding`, `content-encoding` or `connect-content-encoding` has any value other than `identity`, also when the +header is written more than once, whatever its size: the filter counts the bytes it receives, and a compressed message +is inflated only in the service. Each is refused before the service reads any of it. The five routes carry the method +route's metadata and its question for the auth check, so a refused request takes a token from the rpc entry's +`rate_limit` and the check is asked about it as about the method's own call; only the answer differs. What a caller +gets, as the [conformance battery](conformance.md) checks it on Envoy 1.40.2 with a limit of 2,048 bytes and the +Connect bridge on: + +| Request | Answer | +|---|---| +| A Connect call over HTTP/1.1 whose body is exactly the limit | served | +| A Connect call over HTTP/1.1 whose body is one byte over the limit | `413`, `content-type: text/plain`, the body `Payload Too Large`; for a body 1 to 5 bytes over, the service may see the call opened and reset, with no byte of the message, and over HTTP/2 for a larger body too (below) | +| A gRPC call over HTTP/1.1 whose message is one byte over the limit | HTTP `200`, `grpc-status` 2, `grpc-message: Payload Too Large` | +| A Connect call with `content-encoding: gzip` | `415` | +| A gRPC call over HTTP/2 with `grpc-encoding: gzip` | `grpc-status` 2 | +| A gRPC call over HTTP/1.1 with `grpc-encoding` written on two lines, `identity` and `gzip`, in either order | `grpc-status` 2 | +| A Connect call with `content-encoding`, or a call in the Connect streaming form with `connect-content-encoding`, written on two lines, `identity` and `gzip`, in either order | `415` | +| A gRPC call over HTTP/2 with `grpc-encoding: identity` | served | +| A Connect GET over HTTP/1.1 whose message, in the query, is under the limit | `405`, `allow: POST` | +| A call in the Connect streaming form with `connect-content-encoding: gzip` | `415` | +| A `POST` or a `DELETE` over HTTP/1.1 with no body and its message in the query, as a Connect GET carries it | `400` | +| A Connect call over HTTP/1.1 without `connect-protocol-version` whose body is the limit and 5 bytes | served, the body whole | +| The same call with a body of the limit and 6 bytes | `413`, `content-type: text/plain`, the body `Payload Too Large` | + +Over HTTP/1.1, the form the battery's rows send a body in, the limit holds as the table says. The 5 bytes are a gRPC +prefix only for a body that carries one or that the bridge writes one before. A Connect unary call the bridge leaves as +it is, one sent without `connect-protocol-version` +(`source/extensions/filters/http/connect_grpc_bridge/filter.cc` lines 263 and 264 at Envoy 1.40.2) or any Connect +unary call in a file without the bridge, is counted without a prefix: up to the limit and 5 bytes of it reach the +service, as the last two rows show. The filter counts the bytes sent, so a gRPC-Web text call, whose body is base64, +carries a message of at most about three quarters of the limit. + +Over HTTP/2 Envoy's buffer filter passes on without counting it a body that arrives whole in the request's one DATA +frame, the frame that ends the request (`source/extensions/filters/http/buffer/buffer_filter.cc` lines 69 to 75 at +Envoy 1.40.2: a body that ends the request continues at once). HTTP/2's frames hold 16,384 bytes unless the listener +raises the size (RFC 9113, section 4.2), so over HTTP/2 a limit under one frame can let through, in one frame, a +message of up to 16,379 bytes, a frame less the 5 bytes of the gRPC prefix, in a gRPC call, a gRPC-Web call or a call +in the Connect streaming form, and a body without a frame prefix of up to 16,384 bytes. A Connect unary call the +bridge converts is counted as the bridge adds the prefix: in one frame, a body of up to the limit and 5 bytes reaches +the method, and a longer one gets `413` with Envoy's text `Request rejected because the filter's internal buffer size +exceeds the configured limit.` (measured on Envoy 1.40.2). Over HTTP/2 the service may see a Connect call the bridge +converts opened and reset, with no byte of the message, whenever the call is refused for its size, sent in one frame +or in more (measured on Envoy 1.40.2); over HTTP/1.1 only when its body is 1 to 5 bytes over the limit. + +A limit is for a method whose request is one message. The filter holds a request until it ends (`buffer_filter.cc` +lines 69 to 79), so on a method that takes a stream of requests the limit would count the whole stream, and the +service would read no message until the client ends it. With `rpc.proto` such a method with a limit is a problem +([`rpc`](rpc.md)); a methods file does not say which methods stream, so leave the key out on such a method there. The +filter adds `content-length` to a call sent without one (`buffer_filter.cc` lines 91 to 97), so the service sees one. + +The limit binds on the method's own route alone. A route written before the rpc entry whose `prefix`, `path` or +`pattern` takes the method's path would serve every call to it first, with no limit, so such a file is a problem, +whatever the route's other conditions: `route "cart" is written before the rpc entry and takes the path of +shop.v1.CartService/AddItem, so that method's max_request_bytes would not apply; write the route after the rpc +entry`. A route after the rpc entry that sends the same paths to the same service is not limited either, and takes the +spellings of the method's path that Envoy's normalisation does not turn into that path: a trailing slash, another +case, `;p=1` on the method or on the service, `%3Bp=1`, `%20` and a trailing dot (measured on Envoy 1.40.2). Whether +the service reads one of them as the method depends on the service. The spellings Envoy does normalise, such as `//`, +`%2F`, an escaped letter, `/./`, `/x/../` and a backslash, reach the method's route and its limit. diff --git a/docs/portability.md b/docs/portability.md index cb14e7a..e1425da 100644 --- a/docs/portability.md +++ b/docs/portability.md @@ -62,6 +62,7 @@ HAProxy's own OpenTelemetry filter from 3.4 on, where its OpenTracing filter is | `routes[].retries`, `rpc.retries` | a retry policy with Envoy's conditions, to a backend not tried yet when the service has one (the `previous_hosts` predicate) | for a route, `proxy_next_upstream off` and an `error_page` that sends a request no service read to a copy of the route's location for the next backend, the body read first; for the rpc entry `grpc_next_upstream error timeout` and `grpc_next_upstream_tries`, on calls whose method is `POST` | `set-retries` per route, `retry-on conn-failure` (the default) and `option redispatch`; `rpc.retries` refused | core; what "never reached the service" means differs by proxy, and nginx tries again only a request whose body it reads whole first, within 1 MiB | | `routes[].rate_limit`, `routes[].rpc.rate_limit` | the local rate limit filter, before the check, with one token bucket for each route, which the route's metadata names | a `limit_req_zone` of 16 MiB for each limited entry, keyed by `$binary_remote_addr` under `client_address: connection`, by the client `proxyfile.js` reads from `X-Forwarded-For` as Envoy does under `forwarded`, or by a constant for `all`, with `rate=r/s` or `r/m`, so a rate of no whole number of requests a second or a minute is refused; `limit_req ... burst= nodelay`, and a location for each kind of answer Envoy gives a request over the limit: `429` with `local_rate_limited`, the Connect error `resource_exhausted`, and for a gRPC call `200` with `grpc-status` 8 | a `stick-table` storing `http_req_rate()`, `http-request track-sc0`, and `http-request deny deny_status 429 if { sc_http_req_rate(0) gt }`, a sliding window, so a `burst` above 0 is refused | core; nginx and HAProxy differ as their columns say | | the `rpc` entry of `routes`, `rpc.to`, `rpc.methods`, `rpc.proto` | one exact-path route for each method | a `location = /./` with `grpc_pass` for each method | a `path` ACL for each method, to an HTTP/2 backend | core | +| `rpc.methods[].max_request_bytes`, and the field of that name of a `.proto` option's message | the buffer filter on the method's route, with the limit and the 5 bytes of the gRPC prefix, and five routes before it, carrying its metadata and its question for the check, that answer `405` to a `GET`, `400` to a request whose path carries a query and `415` to a request that names a compression other than `identity`; a file with a route before the rpc entry that takes the method's path is refused | not written by this version's generator: leave `max_request_bytes` out, or render it for Envoy | not written by this version's generator: leave `max_request_bytes` out, or render it for Envoy | core | | the action and the reports each RPC route tells the check | the route's own check settings | a `set` of `$pf_action` and `$pf_reports` in the location of each method, which the check location sends as `x-gateway-action` and `x-gateway-reports` | `http-request set-header` of `x-gateway-action` and `x-gateway-reports` by the method's path, for the check alone | core | | `envoy.connect_bridge` | the Connect-gRPC bridge and the Lua status fix on RPC routes | none | none | envoy | | `log.status_from`, `log.sample` | access log filters | `access_log ... if=`, with a `map` of `$status` for `status_from` and `split_clients` on the request id for `sample` | a `log-format` of HAProxy's own fields on standard output; `http-after-response set-log-level silent` by status and `rand(100)` | core | @@ -190,6 +191,7 @@ proxy refuses. | `rpc.methods[].method` | supported | supported | supported | | `rpc.methods[].action` | supported | supported | supported | | `rpc.methods[].reports` | supported | supported | supported | +| `rpc.methods[].max_request_bytes` | supported | refused: not written by this version's nginx generator; leave max\_request\_bytes out, or render it for envoy | refused: not written by this version's HAProxy generator; leave max\_request\_bytes out, or render it for envoy | | `rpc.proto` | supported | supported | supported | | `rpc.proto.roots` | supported | supported | supported | | `rpc.proto.option` | supported | supported | supported | diff --git a/docs/routes.md b/docs/routes.md index 1111852..92c02f4 100644 --- a/docs/routes.md +++ b/docs/routes.md @@ -26,7 +26,10 @@ The rpc entry (`- rpc:` in YAML, `{ rpc { ... } }` in HOCON) is a place in the l of `rpc.methods`, of the `.proto` files `rpc.proto` reads, or of the methods file, matched on the exact path a call carries, `/./`. Those routes are sorted by path and written where the entry stands, so a plain route written above the entry is tried before the RPC routes, and one written below it after them. A file has -at most one rpc entry, and it needs methods from exactly one of `rpc.methods`, `rpc.proto` and `--rpc-methods`. +at most one rpc entry, and it needs methods from exactly one of `rpc.methods`, `rpc.proto` and `--rpc-methods`. A +plain route above the entry whose `prefix`, `path` or `pattern` takes the path of a method with `max_request_bytes` +is a problem, whatever its `method`, because that method's limit is held by its own route +([A method's request limit](limits.md#a-methods-request-limit)). A method goes to the mapping with its exact service name if there is one. Otherwise it goes to the matching pattern with the longest text, and `*` is last. The order in which the patterns are written does not matter. A method that no diff --git a/docs/rpc.md b/docs/rpc.md index 2129894..ab151bd 100644 --- a/docs/rpc.md +++ b/docs/rpc.md @@ -6,6 +6,15 @@ A `rate_limit` on the rpc entry is one limit for every method the entry routes: all of them take their tokens from one bucket ([Rate limits](routes.md#rate-limits)). +A method's `max_request_bytes` is the largest request message, in bytes as serialized, the gateway passes to that +method, over HTTP/1.1, in a body with a gRPC frame prefix or one the Connect bridge converts; for a body without one, +over HTTP/2, and for a method that takes a stream of requests, see [A method's request +limit](limits.md#a-methods-request-limit). Such a method takes its message in a request body only: the Envoy output +answers a `GET` to it with `405` and `allow: POST`, a request of any other method whose path carries a query string +with `400`, and a request that names a compression other than `identity`, by `grpc-encoding`, `content-encoding` or +the Connect streaming form's `connect-content-encoding`, with `415`, which a gRPC call gets as HTTP `200` with +`grpc-status` 2. Only the Envoy output writes the key; nginx and HAProxy refuse it. + | Key | Meaning | Rule | Class | |---|---|---|---| @@ -15,6 +24,7 @@ bucket ([Rate limits](routes.md#rate-limits)). | `rpc.methods[].method` | The method's name. | Required. A method name such as AddItem. | core | | `rpc.methods[].action` | The action the check is told for this method. | Text. Sent to the check in `x-gateway-action`; empty when not written. | core | | `rpc.methods[].reports` | The reports the check is told for this method. | A list; each item is text. Sent to the check in `x-gateway-reports`. No report contains a comma, because the list is sent as one value joined by commas. | core | +| `rpc.methods[].max_request_bytes` | The largest request message, in bytes as serialized, the gateway passes to this method. | A whole number from 1 to 4294967290. No limit when not written. The Envoy output refuses any request to the method that names a compression other than `identity`, and a larger message, over HTTP/1.1, in a body with a gRPC frame prefix or one the Connect bridge converts, before the service reads it; for a body without one, over HTTP/2, and for a method that takes a stream of requests, see docs/limits.md. nginx and HAProxy refuse the key. | core | | `rpc.proto` | The RPC methods, read from the .proto files under roots: each method that carries the method option named by option. | A mapping. Compiled each time proxyfile runs. Not given with `--rpc-methods`. Exactly one of `methods` and `proto` is written. | core | | `rpc.proto.roots` | The directories of .proto files, each an import root: relative to the proxyfile's directory, or absolute. | Required. A list; each item is text. Not empty, and no directory written twice. A root may not contain another, because the files under both would be compiled twice. Each is an import root, as protoc's `--proto_path` is: a file's import path is its path under its root, written with `/`. A relative directory is read from the proxyfile's own directory, as `origins: ` is, also when the key is written in an included file; an absolute one as written. | core | | `rpc.proto.option` | The full name of the method option that marks a method the gateway routes. | Required. An option's full name such as example.gateway.v1.route. Written `.`, with no leading dot. | core | @@ -32,7 +42,7 @@ written as `rpc.methods`, it is the same list. [ {"service": "example.shop.v1.CartService", "method": "GetCart", "action": "browse"}, {"service": "example.accounts.v1.ProfileService", "method": "GetProfile"}, - {"service": "example.shop.v1.CartService", "method": "AddItem", "action": "buy", "reports": ["browse"]} + {"service": "example.shop.v1.CartService", "method": "AddItem", "action": "buy", "reports": ["browse"], "max_request_bytes": 2048} ] ``` @@ -43,6 +53,7 @@ written as `rpc.methods`, it is the same list. | `method` | The method's name. | Required. A method name such as AddItem. | core | | `action` | The action the check is told for this method. | Text. Sent to the check in `x-gateway-action`; empty when not written. | core | | `reports` | The reports the check is told for this method. | A list; each item is text. Sent to the check in `x-gateway-reports`. No report contains a comma, because the list is sent as one value joined by commas. | core | +| `max_request_bytes` | The largest request message, in bytes as serialized, the gateway passes to this method. | A whole number from 1 to 4294967290. No limit when not written. The Envoy output refuses any request to the method that names a compression other than `identity`, and a larger message, over HTTP/1.1, in a body with a gRPC frame prefix or one the Connect bridge converts, before the service reads it; for a body without one, over HTTP/2, and for a method that takes a stream of requests, see docs/limits.md. nginx and HAProxy refuse the key. | core | A method listed twice is a problem. @@ -135,17 +146,23 @@ What proxyfile does with the keys, in this order, each step only when the steps method declared twice never reaches the routes), an option used where its type does not fit. 5. It finds the option by its full name among the compiled files. It extends `google.protobuf.MethodOptions` and holds one message, and that message has a field `action` that holds one string; anything else is a problem. A field - `reports` is optional; when the message has it, it holds a list of strings. Other fields of the message are left - alone. -6. It routes each method of each compiled service that carries the option, with the option's `action`, and its - `reports` when the message has that field (none otherwise). A method without the option is not routed. A method - whose option leaves `action` empty is routed with the empty action, as a methods-file entry with no `action` is. + `reports` is optional; when the message has it, it holds a list of strings. A field `max_request_bytes` is optional + too; when the message has it, it holds one `uint32`. Other fields of the message are left alone. +6. It routes each method of each compiled service that carries the option, with the option's `action`, its `reports` + when the message has that field (none otherwise), and its `max_request_bytes` when the message has that field and + the method sets it, or the field declares a default, above 0 (no limit otherwise, as a methods-file entry with no + `max_request_bytes` has none). A value above 4294967290 is a problem at the option key, naming the method and its + value: the Envoy output writes the limit with the 5 bytes of the gRPC prefix, and Envoy reads that as a `uint32`. A + method that takes a stream of requests and has a limit above 0 is a problem at the method: the limit would count + the whole stream. A method without the option is not routed. A method whose option leaves `action` empty is routed + with the empty action, as a methods-file entry with no `action` is. 7. It sorts the methods by path, `//`, in byte order, and hands them on. Accepted without a word: a method without the option; an option whose message has no `reports` field (then no method -reports anything); a method whose `action` is empty; an option that no method carries, which routes nothing, as +reports anything), or no `max_request_bytes` field (then no method has a request limit); a method whose `action` is +empty; an option that no method carries, which routes nothing, as `methods: []` does; a file that declares no service and that no such file imports, even one whose imports name no -file; every field of the option's message other than `action` and `reports`. +file; every field of the option's message other than `action`, `reports` and `max_request_bytes`. The syntax is fixed, with no key: proxyfile reads proto2, proto3 and edition 2023 files, and a file in edition 2024 is a compile error. It reads no descriptor set, no `buf.yaml` and nothing from the network: only the files under the @@ -175,6 +192,9 @@ its root, resolved against the proxyfile's directory, joined with its import pat | The option does not hold one message | the `option` key | `the option o.v1.route holds a string, not one message`, or `holds a list of messages, not one` | | No `action` that holds one string | the `option` key | `the option's message o.v1.Route has no field action that holds one string` | | A `reports` that is not a list of strings | the `option` key | `the field reports of the option's message o.v1.Route is not a list of strings` | +| A `max_request_bytes` that is not one `uint32` | the `option` key | `the field max_request_bytes of the option's message o.v1.Route is not one uint32` | +| A method's `max_request_bytes` above 4294967290 | the `option` key | `the field max_request_bytes of the option's message o.v1.Route must be a whole number from 0 to 4294967290; o.v1.S/M sets 4294967291` | +| A method that takes a stream of requests with a `max_request_bytes` above 0 | the method | `the field max_request_bytes of the option's message o.v1.Route must be 0 on o.v1.S/M, which takes a stream of requests; it sets 2048` | | An `action` or a report that holds a control character other than tab | the method | `the action "a\nb" contains a newline; no key or value may hold a control character other than tab`, as for a key or a value of a file | `check` compiles the sources as `render` does, so a change to a routed method makes `check` fail until the next @@ -184,13 +204,14 @@ its root, resolved against the proxyfile's directory, joined with its import pat `--rpc-table` writes the routes as JSON for other programs to read, for example one that answers the check. It is a JSON array with one object per line, sorted by path, and it ends with a newline. Each object has `service`, `method`, -`action` (empty when not written), `reports` (empty when not written) and `cluster`, the cluster the call goes to. With -no methods the table is `[]`. This is the table of the methods above: +`action` (empty when not written), `reports` (empty when not written), `max_request_bytes` for a method with a request +limit alone, and `cluster`, the cluster the call goes to. With no methods the table is `[]`. This is the table of the +methods above: ```json [ {"service": "example.accounts.v1.ProfileService", "method": "GetProfile", "action": "", "reports": [], "cluster": "accounts_grpc"}, - {"service": "example.shop.v1.CartService", "method": "AddItem", "action": "buy", "reports": ["browse"], "cluster": "shop_grpc"}, + {"service": "example.shop.v1.CartService", "method": "AddItem", "action": "buy", "reports": ["browse"], "max_request_bytes": 2048, "cluster": "shop_grpc"}, {"service": "example.shop.v1.CartService", "method": "GetCart", "action": "browse", "reports": [], "cluster": "shop_grpc"} ] ``` diff --git a/examples/full/hocon/Proxyfile b/examples/full/hocon/Proxyfile index b5f6e36..dfa0f9f 100644 --- a/examples/full/hocon/Proxyfile +++ b/examples/full/hocon/Proxyfile @@ -112,7 +112,7 @@ rpc { methods = [ { service = "example.shop.v1.CartService", method = GetCart, action = browse } { service = "example.accounts.v1.ProfileService", method = GetProfile } - { service = "example.shop.v1.CartService", method = AddItem, action = buy, reports = [browse] } + { service = "example.shop.v1.CartService", method = AddItem, action = buy, reports = [browse], max_request_bytes = 2048 } ] } diff --git a/examples/full/hocon/envoy.yaml b/examples/full/hocon/envoy.yaml index 78cfca5..10533e4 100644 --- a/examples/full/hocon/envoy.yaml +++ b/examples/full/hocon/envoy.yaml @@ -311,6 +311,11 @@ static_resources: response_handle:headers():replace(":status", status) end end + - name: envoy.filters.http.buffer + disabled: true + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.buffer.v3.Buffer + max_request_bytes: 2053 - name: envoy.filters.http.connect_grpc_bridge disabled: true typed_config: @@ -369,7 +374,12 @@ static_resources: "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute disabled: true - {name: "accounts-rpc", match: {path: "/example.accounts.v1.ProfileService/GetProfile"}, metadata: {filter_metadata: {"example.gateway": {action: ""}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "accounts-rpc", propagate: false}, typed_per_filter_config: {envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "accounts_grpc", host_rewrite_literal: "127.0.0.1:7070", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem"}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: ":method", string_match: {exact: "GET"}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 405}, response_headers_to_add: [{header: {key: "allow", value: "POST"}}]} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: ":path", string_match: {contains: "?"}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 400}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "grpc-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "content-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "connect-content-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem"}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.buffer: {"@type": type.googleapis.com/envoy.extensions.filters.http.buffer.v3.BufferPerRoute, buffer: {max_request_bytes: 2053}}, envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - {name: "shop", match: {path: "/example.shop.v1.CartService/GetCart"}, metadata: {filter_metadata: {"example.gateway": {action: "browse"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - name: "accounts-webhooks" match: {path: "/api/webhooks", headers: [{name: ":method", string_match: {exact: "POST"}}]} @@ -436,7 +446,12 @@ static_resources: "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute disabled: true - {name: "accounts-rpc", match: {path: "/example.accounts.v1.ProfileService/GetProfile"}, metadata: {filter_metadata: {"example.gateway": {action: ""}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "accounts-rpc", propagate: false}, typed_per_filter_config: {envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "accounts_grpc", host_rewrite_literal: "127.0.0.1:7070", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem"}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: ":method", string_match: {exact: "GET"}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 405}, response_headers_to_add: [{header: {key: "allow", value: "POST"}}]} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: ":path", string_match: {contains: "?"}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 400}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "grpc-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "content-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "connect-content-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem"}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.buffer: {"@type": type.googleapis.com/envoy.extensions.filters.http.buffer.v3.BufferPerRoute, buffer: {max_request_bytes: 2053}}, envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - {name: "shop", match: {path: "/example.shop.v1.CartService/GetCart"}, metadata: {filter_metadata: {"example.gateway": {action: "browse"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - name: "accounts-webhooks" match: {path: "/api/webhooks", headers: [{name: ":method", string_match: {exact: "POST"}}]} @@ -502,7 +517,12 @@ static_resources: "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute disabled: true - {name: "accounts-rpc", match: {path: "/example.accounts.v1.ProfileService/GetProfile"}, metadata: {filter_metadata: {"example.gateway": {action: ""}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "accounts-rpc", propagate: false}, typed_per_filter_config: {envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "accounts_grpc", host_rewrite_literal: "127.0.0.1:7070", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem"}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: ":method", string_match: {exact: "GET"}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 405}, response_headers_to_add: [{header: {key: "allow", value: "POST"}}]} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: ":path", string_match: {contains: "?"}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 400}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "grpc-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "content-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "connect-content-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem"}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.buffer: {"@type": type.googleapis.com/envoy.extensions.filters.http.buffer.v3.BufferPerRoute, buffer: {max_request_bytes: 2053}}, envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - {name: "shop", match: {path: "/example.shop.v1.CartService/GetCart"}, metadata: {filter_metadata: {"example.gateway": {action: "browse"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - name: "accounts-webhooks" match: {path: "/api/webhooks", headers: [{name: ":method", string_match: {exact: "POST"}}]} diff --git a/examples/full/hocon/haproxy.refused b/examples/full/hocon/haproxy.refused index 7e8ae83..9752fd8 100644 --- a/examples/full/hocon/haproxy.refused +++ b/examples/full/hocon/haproxy.refused @@ -10,6 +10,7 @@ examples/full/hocon/Proxyfile: auth.jwt.keys: "auth.jwt.keys" is refused by --ta examples/full/hocon/Proxyfile: auth.jwt.optional: "auth.jwt.optional" is refused by --target haproxy: HAProxy's jwt_verify takes one key file, with no key set, URL, issuer or audience check; verify the token in the service auth.ask names examples/full/hocon/Proxyfile: routes[1].rpc.retries: "routes[].rpc.retries" is refused by --target haproxy: with retry-on at HAProxy's default, a gRPC call whose connection to the service failed was not sent again, and the wider retry-on that sends it also sends again a request a service may have read; leave retries out of the rpc entry, or render it for envoy examples/full/hocon/Proxyfile: routes[3].rate_limit.burst: "routes[].rate_limit.burst" above 0 is refused by --target haproxy: HAProxy's rate counts the requests of a period and has no burst; write burst: 0 or leave it out, or render it for envoy +examples/full/hocon/Proxyfile: rpc.methods[2].max_request_bytes: "rpc.methods[].max_request_bytes" is refused by --target haproxy: not written by this version's HAProxy generator; leave max_request_bytes out, or render it for envoy examples/full/hocon/Proxyfile: services.shop.health.grpc: "services..health.grpc" is refused by --target haproxy: HAProxy has no gRPC health check: http-check send writes a text body, not the health service's gRPC message; write health.path on the service's http port examples/full/hocon/Proxyfile: tracing: "tracing" is refused by --target haproxy: the official HAProxy images have no tracing filter (the OpenTelemetry filter is an addon built from source); remove tracing, or render it for envoy examples/full/hocon/Proxyfile: tracing.path_in_url: "tracing.path_in_url" is refused by --target haproxy: the official HAProxy images have no tracing filter (the OpenTelemetry filter is an addon built from source); remove tracing, or render it for envoy diff --git a/examples/full/hocon/nginx.refused b/examples/full/hocon/nginx.refused index 208c79b..053443d 100644 --- a/examples/full/hocon/nginx.refused +++ b/examples/full/hocon/nginx.refused @@ -10,3 +10,4 @@ examples/full/hocon/Proxyfile: auth.jwt.issuer: "auth.jwt.issuer" is refused by examples/full/hocon/Proxyfile: auth.jwt.keys: "auth.jwt.keys" is refused by --target nginx: nginx open source cannot verify a token (nginx Plus's auth_jwt); verify it in the service, or render it for envoy examples/full/hocon/Proxyfile: auth.jwt.optional: "auth.jwt.optional" is refused by --target nginx: nginx open source cannot verify a token (nginx Plus's auth_jwt); verify it in the service, or render it for envoy examples/full/hocon/Proxyfile: remove_from_clients: "remove_from_clients" holding a name with a * prefix is refused by --target nginx: nginx takes each header by name; write each name in full +examples/full/hocon/Proxyfile: rpc.methods[2].max_request_bytes: "rpc.methods[].max_request_bytes" is refused by --target nginx: not written by this version's nginx generator; leave max_request_bytes out, or render it for envoy diff --git a/examples/full/hocon/rpc-table.json b/examples/full/hocon/rpc-table.json index 6233520..0cd23d7 100644 --- a/examples/full/hocon/rpc-table.json +++ b/examples/full/hocon/rpc-table.json @@ -1,5 +1,5 @@ [ {"service": "example.accounts.v1.ProfileService", "method": "GetProfile", "action": "", "reports": [], "cluster": "accounts_grpc"}, - {"service": "example.shop.v1.CartService", "method": "AddItem", "action": "buy", "reports": ["browse"], "cluster": "shop_grpc"}, + {"service": "example.shop.v1.CartService", "method": "AddItem", "action": "buy", "reports": ["browse"], "max_request_bytes": 2048, "cluster": "shop_grpc"}, {"service": "example.shop.v1.CartService", "method": "GetCart", "action": "browse", "reports": [], "cluster": "shop_grpc"} ] diff --git a/examples/full/yaml/envoy.yaml b/examples/full/yaml/envoy.yaml index 78cfca5..10533e4 100644 --- a/examples/full/yaml/envoy.yaml +++ b/examples/full/yaml/envoy.yaml @@ -311,6 +311,11 @@ static_resources: response_handle:headers():replace(":status", status) end end + - name: envoy.filters.http.buffer + disabled: true + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.buffer.v3.Buffer + max_request_bytes: 2053 - name: envoy.filters.http.connect_grpc_bridge disabled: true typed_config: @@ -369,7 +374,12 @@ static_resources: "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute disabled: true - {name: "accounts-rpc", match: {path: "/example.accounts.v1.ProfileService/GetProfile"}, metadata: {filter_metadata: {"example.gateway": {action: ""}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "accounts-rpc", propagate: false}, typed_per_filter_config: {envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "accounts_grpc", host_rewrite_literal: "127.0.0.1:7070", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem"}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: ":method", string_match: {exact: "GET"}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 405}, response_headers_to_add: [{header: {key: "allow", value: "POST"}}]} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: ":path", string_match: {contains: "?"}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 400}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "grpc-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "content-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "connect-content-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem"}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.buffer: {"@type": type.googleapis.com/envoy.extensions.filters.http.buffer.v3.BufferPerRoute, buffer: {max_request_bytes: 2053}}, envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - {name: "shop", match: {path: "/example.shop.v1.CartService/GetCart"}, metadata: {filter_metadata: {"example.gateway": {action: "browse"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - name: "accounts-webhooks" match: {path: "/api/webhooks", headers: [{name: ":method", string_match: {exact: "POST"}}]} @@ -436,7 +446,12 @@ static_resources: "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute disabled: true - {name: "accounts-rpc", match: {path: "/example.accounts.v1.ProfileService/GetProfile"}, metadata: {filter_metadata: {"example.gateway": {action: ""}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "accounts-rpc", propagate: false}, typed_per_filter_config: {envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "accounts_grpc", host_rewrite_literal: "127.0.0.1:7070", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem"}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: ":method", string_match: {exact: "GET"}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 405}, response_headers_to_add: [{header: {key: "allow", value: "POST"}}]} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: ":path", string_match: {contains: "?"}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 400}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "grpc-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "content-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "connect-content-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem"}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.buffer: {"@type": type.googleapis.com/envoy.extensions.filters.http.buffer.v3.BufferPerRoute, buffer: {max_request_bytes: 2053}}, envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - {name: "shop", match: {path: "/example.shop.v1.CartService/GetCart"}, metadata: {filter_metadata: {"example.gateway": {action: "browse"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - name: "accounts-webhooks" match: {path: "/api/webhooks", headers: [{name: ":method", string_match: {exact: "POST"}}]} @@ -502,7 +517,12 @@ static_resources: "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute disabled: true - {name: "accounts-rpc", match: {path: "/example.accounts.v1.ProfileService/GetProfile"}, metadata: {filter_metadata: {"example.gateway": {action: ""}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "accounts-rpc", propagate: false}, typed_per_filter_config: {envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "accounts_grpc", host_rewrite_literal: "127.0.0.1:7070", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem"}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: ":method", string_match: {exact: "GET"}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 405}, response_headers_to_add: [{header: {key: "allow", value: "POST"}}]} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: ":path", string_match: {contains: "?"}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 400}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "grpc-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "content-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "connect-content-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem"}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.buffer: {"@type": type.googleapis.com/envoy.extensions.filters.http.buffer.v3.BufferPerRoute, buffer: {max_request_bytes: 2053}}, envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - {name: "shop", match: {path: "/example.shop.v1.CartService/GetCart"}, metadata: {filter_metadata: {"example.gateway": {action: "browse"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - name: "accounts-webhooks" match: {path: "/api/webhooks", headers: [{name: ":method", string_match: {exact: "POST"}}]} diff --git a/examples/full/yaml/haproxy.refused b/examples/full/yaml/haproxy.refused index edd7bfd..aeb1042 100644 --- a/examples/full/yaml/haproxy.refused +++ b/examples/full/yaml/haproxy.refused @@ -11,6 +11,7 @@ examples/full/yaml/proxyfile.yaml:43:14: "auth.jwt.claims.
" is refu examples/full/yaml/proxyfile.yaml:43:30: "auth.jwt.claims.
" is refused by --target haproxy: HAProxy's jwt_verify takes one key file, with no key set, URL, issuer or audience check; verify the token in the service auth.ask names examples/full/yaml/proxyfile.yaml:66:7: "routes[].rpc.retries" is refused by --target haproxy: with retry-on at HAProxy's default, a gRPC call whose connection to the service failed was not sent again, and the wider retry-on that sends it also sends again a request a service may have read; leave retries out of the rpc entry, or render it for envoy examples/full/yaml/proxyfile.yaml:72:89: "routes[].rate_limit.burst" above 0 is refused by --target haproxy: HAProxy's rate counts the requests of a period and has no burst; write burst: 0 or leave it out, or render it for envoy +examples/full/yaml/proxyfile.yaml:78:95: "rpc.methods[].max_request_bytes" is refused by --target haproxy: not written by this version's HAProxy generator; leave max_request_bytes out, or render it for envoy examples/full/yaml/proxyfile.yaml:80:1: "tracing" is refused by --target haproxy: the official HAProxy images have no tracing filter (the OpenTelemetry filter is an addon built from source); remove tracing, or render it for envoy examples/full/yaml/proxyfile.yaml:81:3: "tracing.provider" is refused by --target haproxy: the official HAProxy images have no tracing filter (the OpenTelemetry filter is an addon built from source); remove tracing, or render it for envoy examples/full/yaml/proxyfile.yaml:82:5: "tracing.provider.otel" is refused by --target haproxy: the official HAProxy images have no tracing filter (the OpenTelemetry filter is an addon built from source); remove tracing, or render it for envoy diff --git a/examples/full/yaml/nginx.refused b/examples/full/yaml/nginx.refused index 55178c3..664ab80 100644 --- a/examples/full/yaml/nginx.refused +++ b/examples/full/yaml/nginx.refused @@ -10,3 +10,4 @@ examples/full/yaml/proxyfile.yaml:43:5: "auth.jwt.claims" is refused by --target examples/full/yaml/proxyfile.yaml:43:14: "auth.jwt.claims.
" is refused by --target nginx: nginx open source cannot verify a token (nginx Plus's auth_jwt); verify it in the service, or render it for envoy examples/full/yaml/proxyfile.yaml:43:30: "auth.jwt.claims.
" is refused by --target nginx: nginx open source cannot verify a token (nginx Plus's auth_jwt); verify it in the service, or render it for envoy examples/full/yaml/proxyfile.yaml:44:1: "remove_from_clients" holding a name with a * prefix is refused by --target nginx: nginx takes each header by name; write each name in full +examples/full/yaml/proxyfile.yaml:78:95: "rpc.methods[].max_request_bytes" is refused by --target nginx: not written by this version's nginx generator; leave max_request_bytes out, or render it for envoy diff --git a/examples/full/yaml/proxyfile.yaml b/examples/full/yaml/proxyfile.yaml index 6d3e3b3..2bbe6a4 100644 --- a/examples/full/yaml/proxyfile.yaml +++ b/examples/full/yaml/proxyfile.yaml @@ -75,7 +75,7 @@ rpc: methods: - {service: example.shop.v1.CartService, method: GetCart, action: browse} - {service: example.accounts.v1.ProfileService, method: GetProfile} - - {service: example.shop.v1.CartService, method: AddItem, action: buy, reports: [browse]} + - {service: example.shop.v1.CartService, method: AddItem, action: buy, reports: [browse], max_request_bytes: 2048} log: {status_from: 400, sample: 1%} tracing: provider: diff --git a/examples/full/yaml/rpc-table.json b/examples/full/yaml/rpc-table.json index 6233520..0cd23d7 100644 --- a/examples/full/yaml/rpc-table.json +++ b/examples/full/yaml/rpc-table.json @@ -1,5 +1,5 @@ [ {"service": "example.accounts.v1.ProfileService", "method": "GetProfile", "action": "", "reports": [], "cluster": "accounts_grpc"}, - {"service": "example.shop.v1.CartService", "method": "AddItem", "action": "buy", "reports": ["browse"], "cluster": "shop_grpc"}, + {"service": "example.shop.v1.CartService", "method": "AddItem", "action": "buy", "reports": ["browse"], "max_request_bytes": 2048, "cluster": "shop_grpc"}, {"service": "example.shop.v1.CartService", "method": "GetCart", "action": "browse", "reports": [], "cluster": "shop_grpc"} ] diff --git a/internal/envoy/fragments/filter-buffer.yaml b/internal/envoy/fragments/filter-buffer.yaml new file mode 100644 index 0000000..ff2f912 --- /dev/null +++ b/internal/envoy/fragments/filter-buffer.yaml @@ -0,0 +1,28 @@ +# The request limit of the RPC methods that write one, rpc.methods[].max_request_bytes or the field of that name of a +# .proto option's message. Envoy's buffer filter holds a request until its body is whole and sets the request's +# buffer limit to its max_request_bytes, and the connection manager answers 413 to a request whose body passes that +# limit, before the router sends any of it to the service (Envoy 1.40.2: buffer.proto, Buffer.max_request_bytes; +# buffer_filter.cc, decodeHeaders). +# +# Disabled here and turned on by each limited method's route alone, with the method's own limit (rpc-route.yaml), so no +# other request is held whole: a route's own configuration of a filter the listener's list writes as disabled turns it +# on for that route (Envoy 1.40.2, http_filters.rst, "Disabled flag based route filter chain"), and replaces the +# filter's configuration here (buffer.proto, BufferPerRoute.buffer). So the max_request_bytes here limits no request; +# it is written because Envoy refuses the entry without one above 0 (buffer.proto), and it is the smallest of the +# routes' values, the one that would let through no request a route refuses. +# +# Right before the Connect bridge, or before the router when the file has no bridge, after the rate limit and the +# checks, so a request they refuse is never held by it. In this place a Connect call's body the bridge converts counts +# with the 5 bytes of the gRPC prefix the bridge writes before it, as a gRPC call's message counts with its frame's: +# with the method's limit and those 5 bytes, a body or a message of exactly the limit is served and one byte more is +# refused, a Connect call with 413 and a gRPC call with grpc-status 2 (measured on Envoy 1.40.2). The 5 bytes are a +# prefix only for such a framed body. A Connect unary body the bridge leaves as it is, one sent without +# connect-protocol-version (Envoy 1.40.2, connect_grpc_bridge/filter.cc lines 263 and 264) or any in a file without the +# bridge, is counted without a prefix, so up to the limit and 5 bytes of it reach the service (measured on Envoy +# 1.40.2; docs/limits.md). The filter counts the bytes it receives, so a compressed request is refused before it, by +# the routes of rpc-route-compressed.yaml. +name: envoy.filters.http.buffer +disabled: true +typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.buffer.v3.Buffer + max_request_bytes: {{.MaxRequestBytes}} diff --git a/internal/envoy/fragments/rpc-route-compressed.yaml b/internal/envoy/fragments/rpc-route-compressed.yaml new file mode 100644 index 0000000..b10e70a --- /dev/null +++ b/internal/envoy/fragments/rpc-route-compressed.yaml @@ -0,0 +1,44 @@ +# One of the three routes after the GET's (rpc-route-get.yaml) and the query's (rpc-route-query.yaml), and right before +# the route of each RPC method with a request limit (rpc-route.yaml), on the same exact path, written for Header +# grpc-encoding, then content-encoding, then connect-content-encoding: the header each form of call names its +# compression in. A gRPC call writes grpc-encoding, which the Connect bridge leaves as it is; a Connect unary call +# writes content-encoding, and a call in the Connect streaming form (content type application/connect+) +# connect-content-encoding, and the bridge renames each to grpc-encoding only after the route is chosen (Envoy 1.40.2, +# connect_grpc_bridge/filter.cc lines 281 and 256), so each is matched by its own name. Each route answers 415 to a +# request whose header has any value other than identity, also when the header is written more than once: the buffer +# filter counts the bytes it receives (filter-buffer.yaml), and a compressed message is inflated only in the service, +# so one under the limit could hold far more than the limit once read. +# +# One expression that takes every value but exactly identity, the empty value among them, and no inverted match of +# identity: Envoy 1.40.2 matches each value of a header written more than once on its own, and an inverted matcher +# fails as soon as one value matches what it inverts (source/common/http/header_utility.h, lines 136 to 163, +# matchesHeadersIndividually), so an inverted exact match of identity let a request that wrote identity and gzip on +# two lines through to the method's route. The runtime setting envoy.reloadable_features.match_headers_individually, +# on by default (source/common/runtime/runtime_features.cc, line 123), picks that matching (header_utility.h, lines +# 165 to 168); with it off Envoy matches the values joined by commas (lines 119 to 134, matchesHeaders), and the +# expression still takes every request with a value other than identity, as a joined value that holds one is never +# exactly identity; it then also takes identity written twice. The expression compares case by case, so IDENTITY is +# refused too. A request without the header matches no value and goes on to the method's own route. The routes of a +# virtual host are matched in order (route_components.proto, VirtualHost.routes), so these three take such a request +# before the method's own route. The router answers with the status (DirectResponseAction) and no body; a gRPC call +# gets Envoy's answer to a gRPC request, HTTP 200 with grpc-status 2 (measured on Envoy 1.40.2). +# +# It carries the rpc entry's name, as the method's route does, and the method route's metadata and header_mutation +# entry, $metadata and $question, filled once for the method (generate.go, carried). The rate limit filter picks a +# request's bucket by the id in its route's metadata, and a route with no id is never limited +# (filter-local-ratelimit.yaml), so a refused call is counted in the rpc entry's bucket, and the auth check is asked +# about it as about the method's own call; only the answer differs. It turns on neither the buffer filter, the bridge +# nor its Lua filter, so a Connect call gets the 415 as it is. +# +# Written in flow style, so the generated file holds each on one line. +{ + name: {{q .Name}}, + match: {path: {{q .Path}}, headers: [{name: {{q .Header}}, string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, +{{- if .Metadata}} + metadata: $metadata, +{{- end}} +{{- if .Question}} + typed_per_filter_config: {envoy.filters.http.header_mutation: $question}, +{{- end}} + direct_response: {status: 415} +} diff --git a/internal/envoy/fragments/rpc-route-get.yaml b/internal/envoy/fragments/rpc-route-get.yaml new file mode 100644 index 0000000..5584ebd --- /dev/null +++ b/internal/envoy/fragments/rpc-route-get.yaml @@ -0,0 +1,34 @@ +# The first of the routes right before the route of each RPC method with a request limit (rpc-route.yaml), on the same +# exact path: it answers 405 to a GET, and the route after it (rpc-route-query.yaml) 400 to a request of any other +# method whose path carries a query, so a method with a limit takes its message in a request body only. A Connect GET +# carries its message in the query: the Connect bridge turns a request whose query holds connect=v1 into a POST whose +# message is the query's message, compressed as its compression parameter says (Envoy 1.40.2, +# connect_grpc_bridge/filter.cc lines 299 to 343), and the buffer filter holds and counts no request that ends with +# its headers (buffer/buffer_filter.cc lines 52 to 55), so the method's limit would not count that message at all. +# +# It matches the method GET exactly, never every method but POST, so a request of any other method, a browser's +# preflight OPTIONS among them, goes on to the routes after it as before; the query route refuses only one whose path +# carries a query. The router answers with the status (route_components.proto, DirectResponseAction) and adds the +# route's response_headers_to_add to that answer (router.cc line 561, finalizeResponseHeaders), here allow: POST, which +# HTTP requires of a 405 (RFC 9110, section 15.5.6). +# +# It carries the rpc entry's name, as the method's route does, and the method route's metadata and header_mutation +# entry, $metadata and $question, filled once for the method (generate.go, carried). The rate limit filter picks a +# request's bucket by the id in its route's metadata, and a route with no id is never limited +# (filter-local-ratelimit.yaml), so a refused call is counted in the rpc entry's bucket, and the auth check is asked +# about it as about the method's own call; only the answer differs. It turns on neither the buffer filter, the bridge +# nor its Lua filter, so a Connect GET gets the 405 as it is. +# +# Written in flow style, so the generated file holds it on one line. +{ + name: {{q .Name}}, + match: {path: {{q .Path}}, headers: [{name: ":method", string_match: {exact: "GET"}}]}, +{{- if .Metadata}} + metadata: $metadata, +{{- end}} +{{- if .Question}} + typed_per_filter_config: {envoy.filters.http.header_mutation: $question}, +{{- end}} + direct_response: {status: 405}, + response_headers_to_add: [{header: {key: "allow", value: "POST"}}] +} diff --git a/internal/envoy/fragments/rpc-route-metadata.yaml b/internal/envoy/fragments/rpc-route-metadata.yaml new file mode 100644 index 0000000..1d848bd --- /dev/null +++ b/internal/envoy/fragments/rpc-route-metadata.yaml @@ -0,0 +1,10 @@ +# The metadata of an RPC method's route (rpc-route.yaml) and of each route before it that refuses a form of call to a +# method with a request limit (rpc-route-get.yaml, rpc-route-query.yaml, rpc-route-compressed.yaml). It is filled once +# for the method and given to each of those routes as $metadata, so they carry the same. With auth.ask it keeps the +# method's action for the auth-unavailable log line (log-auth-unavailable.yaml), and with a rate limit on the rpc +# entry it names the entry's bucket under the rate-limit namespace, the id the rate limit filter picks a request's +# bucket by (filter-local-ratelimit.yaml). +{filter_metadata: { {{- if .Auth}}{{q .Namespace}}: {action: {{q .Action}}}{{end}} +{{- if and .Auth .RateLimit}}, {{end}} +{{- with .RateLimit}}{{q .Namespace}}: { {{- .By}}: {{q .ID}}}{{end -}} +}} diff --git a/internal/envoy/fragments/rpc-route-query.yaml b/internal/envoy/fragments/rpc-route-query.yaml new file mode 100644 index 0000000..e01b53b --- /dev/null +++ b/internal/envoy/fragments/rpc-route-query.yaml @@ -0,0 +1,33 @@ +# The second of the routes right before the route of each RPC method with a request limit (rpc-route.yaml), after the +# GET's (rpc-route-get.yaml), on the same exact path: it answers 400 to a request whose path carries a query string, a +# ? in :path, which the exact path match of the method's route leaves out. The Connect bridge turns any request whose +# query holds connect=v1 and that is not Connect by its headers into a POST whose message is the query's message, +# whatever its method (Envoy 1.40.2, connect_grpc_bridge/filter.cc lines 299 to 343), and the buffer filter holds and +# counts no request that ends with its headers (buffer/buffer_filter.cc lines 52 to 55), so without this route a POST, +# a PUT or a DELETE with no body would bring the method a message the limit never counted. +# +# It matches the query string itself, not the bridge's parameters: no gRPC call and no Connect call with a body carries +# a query, so the route refuses no call a client sends with its message in the body, and what it refuses does not +# depend on how a version of the bridge reads the query. A browser's preflight OPTIONS to the path with a query gets +# the 400 too. The GET's route comes first, so a GET with a query keeps its 405 and allow: POST. The router answers +# with the status (route_components.proto, DirectResponseAction) and no body or header of the route's own. +# +# It carries the rpc entry's name, as the method's route does, and the method route's metadata and header_mutation +# entry, $metadata and $question, filled once for the method (generate.go, carried). The rate limit filter picks a +# request's bucket by the id in its route's metadata, and a route with no id is never limited +# (filter-local-ratelimit.yaml), so a refused call is counted in the rpc entry's bucket, and the auth check is asked +# about it as about the method's own call; only the answer differs. It turns on neither the buffer filter, the bridge +# nor its Lua filter, so a Connect call gets the 400 as it is. +# +# Written in flow style, so the generated file holds it on one line. +{ + name: {{q .Name}}, + match: {path: {{q .Path}}, headers: [{name: ":path", string_match: {contains: "?"}}]}, +{{- if .Metadata}} + metadata: $metadata, +{{- end}} +{{- if .Question}} + typed_per_filter_config: {envoy.filters.http.header_mutation: $question}, +{{- end}} + direct_response: {status: 400} +} diff --git a/internal/envoy/fragments/rpc-route-question.yaml b/internal/envoy/fragments/rpc-route-question.yaml new file mode 100644 index 0000000..3890c3b --- /dev/null +++ b/internal/envoy/fragments/rpc-route-question.yaml @@ -0,0 +1,17 @@ +# The header_mutation entry of an RPC method's route (rpc-route.yaml) and of each route before it that refuses a form +# of call to a method with a request limit (rpc-route-get.yaml, rpc-route-query.yaml, rpc-route-compressed.yaml). It is +# filled once for the method and given to each of those routes as $question, so the auth check is asked the same +# question on each: the method's action and reports, in the x-gateway- headers it adds. The router removes those +# headers after every filter, so no service sees them (listener.yaml). +{ + "@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, + mutations: {request_mutations: [ +{{- with .Action}} + {append: {header: {key: x-gateway-action, value: {{q .}}}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}} +{{- end}} +{{- if and .Action .Reports}},{{end}} +{{- with .Reports}} + {append: {header: {key: x-gateway-reports, value: {{q .}}}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}} +{{- end}} + ]} +} diff --git a/internal/envoy/fragments/rpc-route.yaml b/internal/envoy/fragments/rpc-route.yaml index b532139..b0cede3 100644 --- a/internal/envoy/fragments/rpc-route.yaml +++ b/internal/envoy/fragments/rpc-route.yaml @@ -1,44 +1,38 @@ # One route per RPC method, listed in rpc.methods or in the --rpc-methods file, matched on the exact path a call carries -# (/./), asking the auth check the method's action and reports through the x-gateway- headers -# its own header_mutation entry adds; its metadata keeps the action for the auth-unavailable log line, and with a limit -# on the rpc entry the entry's bucket, under the rate-limit namespace (filter-local-ratelimit.yaml). With -# envoy.connect_bridge, each turns on the bridge, which turns the call into gRPC before the router, and the Lua filter -# that sets Connect's current status on the bridge's errors: a FilterConfig entry turns on, for its route, a filter the -# listener's list writes as disabled (Envoy 1.40.2, http_filters.rst, "Disabled flag based route filter chain"). Without -# the bridge a route with no question carries no typed_per_filter_config at all. With OpenTelemetry the decorator names -# the route's span after the route, where Envoy's own name is ingress (measured on Envoy 1.40.2). propagate: false keeps -# the name out of the answer: with Envoy's default of true every response carries the route's name in -# x-envoy-decorator-operation (measured on Envoy 1.40.2). With X-Ray or no tracing a route carries none. +# (/./). Its metadata (rpc-route-metadata.yaml) keeps the action for the auth-unavailable log +# line and, with a rate limit on the rpc entry, the entry's bucket; its header_mutation entry (rpc-route-question.yaml) +# asks the auth check the method's action and reports through the x-gateway- headers. Both are filled once for the +# method and spliced in, as $metadata and $question, here and in each route that refuses a form of call to a method +# with a limit, so those routes carry the same. With envoy.connect_bridge, each turns on the bridge, which turns the +# call into gRPC before the router, and the Lua filter that sets Connect's current status on the bridge's errors: a +# FilterConfig entry turns on, for its route, a filter the listener's list writes as disabled (Envoy 1.40.2, +# http_filters.rst, "Disabled flag based route filter chain"). A method with max_request_bytes turns on the buffer +# filter the same way, with a BufferPerRoute that holds the method's limit and the 5 bytes of the gRPC prefix +# (filter-buffer.yaml), and the five routes before its own refuse a GET (rpc-route-get.yaml), a request whose path +# carries a query (rpc-route-query.yaml) and a compressed request (rpc-route-compressed.yaml). Without the bridge or a +# limit a route with no question carries no typed_per_filter_config at all, so a file without the key renders as +# before it. With OpenTelemetry the decorator names the route's span after the route, where Envoy's own name is ingress +# (measured on Envoy 1.40.2). propagate: false keeps the name out of the answer: with Envoy's default of true every +# response carries the route's name in x-envoy-decorator-operation (measured on Envoy 1.40.2). With X-Ray or no tracing +# a route carries none. # # Written in flow style, so the generated file holds each RPC route on one line. { name: {{q .Name}}, match: {path: {{q .Path}}}, -{{- if or .Auth .RateLimit}} - metadata: {filter_metadata: { {{- if .Auth}}{{q .Namespace}}: {action: {{q .Action}}}{{end}} -{{- if and .Auth .RateLimit}}, {{end}} -{{- with .RateLimit}}{{q .Namespace}}: { {{- .By}}: {{q .ID}}}{{end -}} - }}, +{{- if .Metadata}} + metadata: $metadata, {{- end}} {{- with .Decorator}} decorator: {operation: {{q .}}, propagate: false}, {{- end}} -{{- $question := and .Auth (or .Action .Reports)}} -{{- if or $question .Bridge}} +{{- if or .Question .Bridge .Limit}} typed_per_filter_config: { -{{- if $question}} - envoy.filters.http.header_mutation: { - "@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, - mutations: {request_mutations: [ -{{- with .Action}} - {append: {header: {key: x-gateway-action, value: {{q .}}}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}} +{{- with .Limit}} + envoy.filters.http.buffer: {"@type": type.googleapis.com/envoy.extensions.filters.http.buffer.v3.BufferPerRoute, buffer: {max_request_bytes: {{.}}}}{{if or $.Question $.Bridge}},{{end}} {{- end}} -{{- if and .Action .Reports}},{{end}} -{{- with .Reports}} - {append: {header: {key: x-gateway-reports, value: {{q .}}}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}} -{{- end}} - ]} - }{{if .Bridge}},{{end}} +{{- if .Question}} + envoy.filters.http.header_mutation: $question{{if .Bridge}},{{end}} {{- end}} {{- if .Bridge}} envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, diff --git a/internal/envoy/generate.go b/internal/envoy/generate.go index 36fcd41..7cbefda 100644 --- a/internal/envoy/generate.go +++ b/internal/envoy/generate.go @@ -20,6 +20,7 @@ import ( "github.com/kitecorp/proxyfile/v2/internal/model" "github.com/kitecorp/proxyfile/v2/internal/origins" "github.com/kitecorp/proxyfile/v2/internal/quote" + "github.com/kitecorp/proxyfile/v2/internal/rpc" ) // fragments holds one YAML document per part of the file, each a text/template. A plain scalar $name as a mapping @@ -37,7 +38,10 @@ var connectStatus string // The filters, in order: set_metadata, the header mutation (Vary on every answer, and each RPC route's question for the // check), the check of each environment that writes ask_unlisted, the RBAC refusal of a foreign browser origin, CORS, // the rate limit (with a rate_limit), the token filter (with auth.jwt), ext_authz (with auth.ask), the Lua filter that -// corrects the status of the bridge's errors and the Connect-gRPC bridge (both with envoy.connect_bridge), the router. +// corrects the status of the bridge's errors (with envoy.connect_bridge), the buffer filter that holds an RPC method's +// request to its limit (with a method that writes max_request_bytes), the Connect-gRPC bridge (with +// envoy.connect_bridge), the router. The buffer filter sits right before the bridge, where a Connect body one byte past +// a method's limit was measured refused as a gRPC message one byte past it is (filter-buffer.yaml). // An origin no list holds is put to its environment's check before RBAC, which reads the check's answer; the check is // written once for the environment and turned on by its virtual host, never once for each route // (filter-unlisted-origin.yaml). A foreign origin is refused before ext_authz could call the check; a browser's @@ -61,6 +65,7 @@ var httpFilters = []struct { {"filter-jwt-authn.yaml", once(hasJWT)}, {"filter-ext-authz.yaml", once(hasAuth)}, {"filter-lua.yaml", once(hasBridge)}, + {"filter-buffer.yaml", requestLimits}, {"filter-connect-bridge.yaml", once(hasBridge)}, {"filter-router.yaml", once(always)}, } @@ -92,6 +97,31 @@ func hasRateLimit(g *model.Gateway) bool { return len(generator.Buckets(g)) > 0 // hasBridge says whether the RPC routes take Connect calls, which the bridge and its Lua status filter serve. func hasBridge(g *model.Gateway) bool { return hasRPC(g) && g.Envoy.ConnectBridge } +// requestLimits is the buffer filter's one copy when an RPC method writes max_request_bytes, and none otherwise, so a +// file without the key writes no buffer filter. Its value is the smallest of the routes' (filter-buffer.yaml says why). +func requestLimits(in generator.Input, _ data) []data { + var smallest int64 + for _, r := range in.RPC { + if limit := requestLimit(r); limit > 0 && (smallest == 0 || limit < smallest) { + smallest = limit + } + } + if smallest == 0 { + return nil + } + return []data{{"MaxRequestBytes": smallest}} +} + +// requestLimit is the buffer filter's max_request_bytes on the route of r, 0 when r's method has no limit: the +// method's limit and the gRPC prefix, which a gRPC call's frame carries and the bridge writes before a Connect body. +// It is counted in int64, so no sum can wrap; the format's largest limit keeps it within the uint32 Envoy reads. +func requestLimit(r rpc.Route) int64 { + if r.MaxRequestBytes == 0 { + return 0 + } + return int64(r.MaxRequestBytes) + model.GRPCPrefixBytes +} + // Generate returns the whole envoy.yaml as the one file, the configuration: Envoy loads no other file proxyfile // writes. Its error means a fragment did not fill or parse: a bug, never a problem in the input, which earlier stages // have refused. @@ -282,7 +312,11 @@ func health(service model.Service, protocol model.Protocol) data { } // routes is the route list every virtual host holds: the refused route (route-refused.yaml), then the plain routes in -// the order written, with the RPC routes, sorted by path, at the place of the rpc entry. +// the order written, with the RPC routes, sorted by path, at the place of the rpc entry. The route of a method with a +// request limit follows, on its path, the route that refuses a GET (rpc-route-get.yaml), the one that refuses a request +// whose path carries a query (rpc-route-query.yaml) and the three that refuse a compressed request +// (rpc-route-compressed.yaml), each carrying the method route's metadata and question (carried). The five are filled +// from one data value, the method's name, path and what they carry, and the compressed ones add their header to it. func (b *builder) routes(in generator.Input) []*yaml.Node { g := in.Gateway // The refusal of a dot segment with a parameter comes first, so no route of the file takes such a path. @@ -290,17 +324,27 @@ func (b *builder) routes(in generator.Input) []*yaml.Node { for _, route := range g.Routes { if route.RPC != nil { for _, r := range in.RPC { + limit := requestLimit(r) + carried, splices := b.carried(g, r, routeLimit(g, &route)) + if limit > 0 { + refusal := data{"Name": r.Name, "Path": r.Path(), "Metadata": carried["Metadata"], + "Question": carried["Question"]} + routes = append(routes, b.fill("rpc-route-get.yaml", refusal, splices...), + b.fill("rpc-route-query.yaml", refusal, splices...)) + for _, header := range compressionHeaders { + refusal["Header"] = header + routes = append(routes, b.fill("rpc-route-compressed.yaml", refusal, splices...)) + } + } routes = append(routes, b.fill("rpc-route.yaml", data{ "Name": r.Name, "Path": r.Path(), - "Auth": g.Auth != nil, - "Namespace": g.Envoy.Namespace, - "Action": r.Action, - "Reports": strings.Join(r.Reports, ","), + "Metadata": carried["Metadata"], + "Question": carried["Question"], "Bridge": g.Envoy.ConnectBridge, - "RateLimit": routeLimit(g, &route), "Decorator": decorator(g, r.Name), - }, splice{"action", b.action(g, r.Target, model.GRPC, nil, route.RPC.Retries)})) + "Limit": limit, + }, append([]splice{{"action", b.action(g, r.Target, model.GRPC, nil, route.RPC.Retries)}}, splices...)...)) } continue } @@ -323,6 +367,31 @@ func (b *builder) routes(in generator.Input) []*yaml.Node { return routes } +// carried is what the route of r and each route that refuses a form of call to r's method carry for the filters before +// the router, each filled once for the method: the metadata (rpc-route-metadata.yaml), which the rate limit filter +// picks the rpc entry's bucket by, given bucket, and the auth-unavailable log line reads the action from; and the +// header_mutation entry (rpc-route-question.yaml), which asks the auth check the method's action and reports. Its data +// says which of the two a route holds, Metadata and Question, and its splices give each one held. A refused call is so +// counted and asked about as the method's own call is, and only the answer differs. +func (b *builder) carried(g *model.Gateway, r rpc.Route, bucket data) (data, []splice) { + values := data{"Auth": g.Auth != nil, "Namespace": g.Envoy.Namespace, "Action": r.Action, + "Reports": strings.Join(r.Reports, ","), "RateLimit": bucket} + metadata, question := g.Auth != nil || bucket != nil, g.Auth != nil && (r.Action != "" || len(r.Reports) > 0) + var splices []splice + if metadata { + splices = append(splices, splice{"metadata", b.fill("rpc-route-metadata.yaml", values)}) + } + if question { + splices = append(splices, splice{"question", b.fill("rpc-route-question.yaml", values)}) + } + return data{"Metadata": metadata, "Question": question}, splices +} + +// compressionHeaders are the headers a caller names a request's compression in, in the order their refusal routes are +// written: grpc-encoding for a gRPC call, content-encoding for a Connect unary call and connect-content-encoding for a +// call in the Connect streaming form. +var compressionHeaders = []string{"grpc-encoding", "content-encoding", "connect-content-encoding"} + // refused is the route that refuses a dot segment with a parameter (route-refused.yaml). With check, the name of an // environment's check of an origin no list holds, it turns that check off; with "", it is the route every virtual // host without the check holds. diff --git a/internal/format/spec.go b/internal/format/spec.go index e6b510a..839c2b8 100644 --- a/internal/format/spec.go +++ b/internal/format/spec.go @@ -608,4 +608,12 @@ var methodField = Field{Doc: "One RPC method.", Kind: Map, Fields: []Field{ Rule: "Sent to the check in `x-gateway-action`; empty when not written."}, withRule(texts("reports", "The reports the check is told for this method.", false), "Sent to the check in `x-gateway-reports`. No report contains a comma, because the list is sent as one value joined by commas."), + // The largest is model.LargestRequestLimit: the Envoy output writes the limit and the 5 bytes of the gRPC prefix + // as a uint32. 0 is refused, because a method that leaves the key out has no limit already. + {Name: "max_request_bytes", Doc: "The largest request message, in bytes as serialized, the gateway passes to this method.", + Kind: Int, Min: 1, Max: model.LargestRequestLimit, + Rule: "No limit when not written. The Envoy output refuses any request to the method that names a compression " + + "other than `identity`, and a larger message, over HTTP/1.1, in a body with a gRPC frame prefix or one the " + + "Connect bridge converts, before the service reads it; for a body without one, over HTTP/2, and for a method " + + "that takes a stream of requests, see docs/limits.md. nginx and HAProxy refuse the key."}, }} diff --git a/internal/format/support_haproxy.go b/internal/format/support_haproxy.go index b0e2aa6..2476171 100644 --- a/internal/format/support_haproxy.go +++ b/internal/format/support_haproxy.go @@ -373,9 +373,13 @@ var haproxyTarget = Target{Name: "haproxy", Title: "HAProxy", Keys: map[string]S "rpc.methods[].method": {Level: Supported}, "rpc.methods[].action": {Level: Supported}, "rpc.methods[].reports": {Level: Supported}, - "rpc.proto": {Level: Supported}, - "rpc.proto.roots": {Level: Supported}, - "rpc.proto.option": {Level: Supported}, + // This version's HAProxy file writes no body limit on a method's path; refused, so a limit is never dropped + // without a word. render.Read refuses it in a .proto option's field too, through rpc.Tree. + "rpc.methods[].max_request_bytes": {Level: Refused, + Note: "not written by this version's HAProxy generator; leave max_request_bytes out, or render it for envoy"}, + "rpc.proto": {Level: Supported}, + "rpc.proto.roots": {Level: Supported}, + "rpc.proto.option": {Level: Supported}, // Every file logs every request of the public listener on standard output, as the Envoy output does with no log key, // in a log-format of HAProxy's own fields that leaves out what defaults.md promises no line holds; with log, diff --git a/internal/format/support_nginx.go b/internal/format/support_nginx.go index f9a29b1..5e11d62 100644 --- a/internal/format/support_nginx.go +++ b/internal/format/support_nginx.go @@ -630,9 +630,13 @@ var nginxTarget = Target{Name: "nginx", Title: "nginx", Keys: map[string]Support // A value holding " or $ reaches the check as written, as through Envoy (quoted, and $ as ${pf_dollar}). "rpc.methods[].action": {Level: Supported}, "rpc.methods[].reports": {Level: Supported}, - "rpc.proto": {Level: Supported}, - "rpc.proto.roots": {Level: Supported}, - "rpc.proto.option": {Level: Supported}, + // This version's nginx file writes no body limit on a method's location; refused, so a limit is never dropped + // without a word. render.Read refuses it in a .proto option's field too, through rpc.Tree. + "rpc.methods[].max_request_bytes": {Level: Refused, + Note: "not written by this version's nginx generator; leave max_request_bytes out, or render it for envoy"}, + "rpc.proto": {Level: Supported}, + "rpc.proto.roots": {Level: Supported}, + "rpc.proto.option": {Level: Supported}, // The fields measured on nginx 1.30.6 and 1.31.8 beside Envoy 1.40.2 for a served request, a service's 404 and 503, // a host no environment names, the requests each refuses before a route, an id and a Host holding 0xE9 or a quote, a diff --git a/internal/format/support_test.go b/internal/format/support_test.go index 77a1b68..a56f27c 100644 --- a/internal/format/support_test.go +++ b/internal/format/support_test.go @@ -39,7 +39,7 @@ func TestCoreKeys(t *testing.T) { name string got, want any }{ - {name: "the count", got: len(full), want: 131}, + {name: "the count", got: len(full), want: 132}, {name: "the first", got: first, want: "listen"}, {name: "the last", got: last, want: "tracing.path_in_url"}, {name: "a key of a Dict's value", got: slices.Contains(full, "services..http"), want: true}, @@ -958,6 +958,8 @@ func TestHAProxyWrites(t *testing.T) { "origins..ask_unlisted", "origins..question"}, "with retry-on at HAProxy's default, a gRPC call whose connection to the service failed was not sent again, and the wider retry-on that sends it also sends again a request a service may have read; leave retries out of the rpc entry, or render it for envoy": { "routes[].rpc.retries"}, + "not written by this version's HAProxy generator; leave max_request_bytes out, or render it for envoy": { + "rpc.methods[].max_request_bytes"}, "HAProxy has no gRPC health check: http-check send writes a text body, not the health service's gRPC message; write health.path on the service's http port": { "services..health.grpc"}, "HAProxy's jwt_verify takes one key file, with no key set, URL, issuer or audience check; verify the token in the service auth.ask names": { diff --git a/internal/model/model.go b/internal/model/model.go index 99e4321..96173b8 100644 --- a/internal/model/model.go +++ b/internal/model/model.go @@ -1,6 +1,9 @@ package model -import "strings" +import ( + "math" + "strings" +) // Gateway is one proxyfile after reading: every default filled in and every rule checked. Each value a rule or a // later stage may name in a problem keeps the position it was written at; a default that was not written has no @@ -278,6 +281,17 @@ type RPCTarget struct { Pos Pos // the pattern } +// GRPCPrefixBytes is the prefix of a gRPC message: a flag byte and the message's length as a big-endian uint32. A +// method's request limit counts the message alone, and a gRPC call's frame carries the prefix before it, as the +// Connect bridge writes it before a Connect call's body, so the Envoy output's limit on the method's route is the +// method's limit and these bytes. +const GRPCPrefixBytes = 5 + +// LargestRequestLimit is the largest request limit a method may set, rpc.methods[].max_request_bytes or the field of +// that name of a .proto option's message: Envoy reads the route's limit, this and GRPCPrefixBytes, as a uint32 +// (buffer.proto, Buffer.max_request_bytes), whose largest is 4294967295. +const LargestRequestLimit = math.MaxUint32 - GRPCPrefixBytes + type Log struct { StatusFrom int64 SamplePercent int diff --git a/internal/protofiles/protofiles.go b/internal/protofiles/protofiles.go index 36e6d6d..a0f5324 100644 --- a/internal/protofiles/protofiles.go +++ b/internal/protofiles/protofiles.go @@ -1,5 +1,5 @@ // Package protofiles reads a gateway's RPC methods from .proto files: it compiles them in memory and returns each -// method that carries a method option named by its full name, with that option's action and reports. +// method that carries a method option named by its full name, with that option's action, reports and request limit. package protofiles import ( @@ -281,9 +281,12 @@ func withImports(files linker.Files) linker.Files { } // routed returns each method of the compiled services that carries the option, sorted by path, or the problems of the -// methods whose action or report holds a control character other than tab. Those are refused here, at the method, as -// the reader refuses one in any key or value of a file (model.Problems.RefuseControl), because the action and the -// reports are read from the .proto files and never pass through that reader. +// methods whose action or report holds a control character other than tab, or whose request limit is past the largest. +// Those are refused here, as the reader refuses them in a file, because the action, the reports and the limit are read +// from the .proto files and never pass through that reader or the format check: a control character at the method +// (model.Problems.RefuseControl), and a limit at the option key, beside the other problems of the option's message, +// naming the method and its value, because the key is in the proxyfile and the value in a .proto file. Its range starts +// at 0, where the format's starts at 1, because a method that leaves the field out reads as 0, which is no limit. func routed(sources map[string]*source, files linker.Files, s Source) ([]rpc.Method, []model.Problem) { types := withImports(files).AsResolver() route, err := option(types, s.Option) @@ -318,6 +321,25 @@ func routed(sources map[string]*source, files linker.Files, s Source) ([]rpc.Met problems.RefuseControl(pos, "the report", report) } } + if route.maxRequestBytes != nil { + // option checked that the field holds one uint32. + limit := value.Get(route.maxRequestBytes).Uint() + if limit > model.LargestRequestLimit { + problems.Add(s.OptionPos, "the field max_request_bytes of the option's message %s must be a whole number "+ + "from 0 to %d; %s/%s sets %d", route.option.Message().FullName(), model.LargestRequestLimit, + found.Service, found.Method, limit) + } + // Envoy's buffer filter holds a request until it ends (Envoy 1.40.2, buffer_filter.cc lines 69 to + // 79), so on a method that takes a stream of requests the limit would count the whole stream, and + // the service would read no message until the client ends it. A methods file does not say which + // methods stream, so docs/limits.md says it for that file. + if limit > 0 && m.IsStreamingClient() { + problems.Add(pos, "the field max_request_bytes of the option's message %s must be 0 on %s/%s, "+ + "which takes a stream of requests; it sets %d", route.option.Message().FullName(), + found.Service, found.Method, limit) + } + found.MaxRequestBytes = uint32(limit) + } methods = append(methods, found) } } @@ -335,9 +357,10 @@ func routed(sources map[string]*source, files linker.Files, s Source) ([]rpc.Met // route is the option and the fields of its message a routed method's values are read from. type route struct { - option protoreflect.FieldDescriptor - action protoreflect.FieldDescriptor - reports protoreflect.FieldDescriptor // nil when the message has no field reports + option protoreflect.FieldDescriptor + action protoreflect.FieldDescriptor + reports protoreflect.FieldDescriptor // nil when the message has no field reports + maxRequestBytes protoreflect.FieldDescriptor // nil when the message has no field max_request_bytes } // valueIn returns the option's message in a method's options, or nil when the method does not carry it. protocompile @@ -359,8 +382,9 @@ func (r route) valueIn(options proto.Message, types linker.Resolver) (protorefle } // option finds the option by its full name among the compiled files and what they import, and checks its form: it -// extends google.protobuf.MethodOptions and holds one message, whose field action holds one string and whose field -// reports, when it has one, holds a list of strings. Every other field of the message is left alone. +// extends google.protobuf.MethodOptions and holds one message, whose field action holds one string, whose field +// reports, when it has one, holds a list of strings, and whose field max_request_bytes, when it has one, holds one +// uint32, as the methods file's key holds a whole number. Every other field of the message is left alone. func option(types linker.Resolver, name string) (route, error) { found, err := types.FindExtensionByName(protoreflect.FullName(name)) if err != nil { @@ -394,7 +418,11 @@ func option(types linker.Resolver, name string) (route, error) { if reports != nil && (reports.Kind() != protoreflect.StringKind || !reports.IsList()) { return route{}, fmt.Errorf("the field reports of the option's message %s is not a list of strings", message.FullName()) } - return route{option: extension, action: action, reports: reports}, nil + limit := message.Fields().ByName("max_request_bytes") + if limit != nil && (limit.Kind() != protoreflect.Uint32Kind || limit.IsList()) { + return route{}, fmt.Errorf("the field max_request_bytes of the option's message %s is not one uint32", message.FullName()) + } + return route{option: extension, action: action, reports: reports, maxRequestBytes: limit}, nil } // kindOf names what a full name that is not an extension names, with its article. diff --git a/internal/protofiles/protofiles_test.go b/internal/protofiles/protofiles_test.go index 8fb26e6..7f3a8c8 100644 --- a/internal/protofiles/protofiles_test.go +++ b/internal/protofiles/protofiles_test.go @@ -1,6 +1,7 @@ package protofiles import ( + "encoding/json" "fmt" "os" "path/filepath" @@ -10,6 +11,7 @@ import ( "testing" "github.com/kitecorp/proxyfile/v2/internal/model" + "github.com/kitecorp/proxyfile/v2/internal/rpc" "github.com/kitecorp/proxyfile/v2/internal/testsupport" ) @@ -139,6 +141,68 @@ func TestMethods(t *testing.T) { } } +// A method's request limit is the field max_request_bytes of the option's message, read as the reports are: from a +// message that has the field, on a method that sets it, and 0 on a method that leaves it out. The field must hold one +// uint32, as the methods file's key holds a whole number, so a message whose field holds anything else is refused at +// the option key, where the option's form is checked. The root is written at g.yaml:8:23 and the option at +// g.yaml:8:39, as in TestMethods. +func TestProtoOptionLimit(t *testing.T) { + cases := []struct { + name, root string + path string // the method whose limit the row reads + // want is the method's limit, as "max_request_bytes N", or the problems. + want []string + }{ + {name: "a method that sets the limit", root: "testdata/limit", path: "/shop.v1.CartService/AddItem", + want: []string{"max_request_bytes 2048"}}, + {name: "a method that leaves it out", root: "testdata/limit", path: "/shop.v1.CartService/GetCart", + want: []string{"max_request_bytes 0"}}, + {name: "a field that holds a string", root: "testdata/limittext", path: "/shop.v1.CartService/AddItem", want: []string{ + "g.yaml:8:39: the field max_request_bytes of the option's message shop.v1.Route is not one uint32", + }}, + // The buffer filter holds a request until it ends, so on a method that takes a stream of requests the limit + // would count the whole stream, and the service would read no message until the client ends it. Such a method + // is refused at its own line when it sets the limit; one that streams its answers is read as a unary one. + {name: "a client-streaming method that sets the limit", root: "testdata/limitclientstream", path: "/shop.v1.CartService/AddItem", + want: []string{"testdata/limitclientstream/shop/v1/cart.proto:21:3: the field max_request_bytes of the option's message " + + "shop.v1.Route must be 0 on shop.v1.CartService/Upload, which takes a stream of requests; it sets 2048"}}, + {name: "a server-streaming method that sets the limit", root: "testdata/limitstreams", path: "/shop.v1.CartService/Watch", + want: []string{"max_request_bytes 2048"}}, + {name: "a client-streaming method that leaves it out", root: "testdata/limitstreams", path: "/shop.v1.CartService/Sync", + want: []string{"max_request_bytes 0"}}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + methods, _, problems := Methods(Source{Roots: []Root{{Dir: c.root, Pos: model.Pos{File: "g.yaml", Line: 8, Column: 23}}}, + Option: "shop.v1.route", OptionPos: model.Pos{File: "g.yaml", Line: 8, Column: 39}}) + if methods != nil && problems != nil { + t.Errorf("Methods returned methods %v next to problems", methods) + } + got := testsupport.ProblemStrings(problems) + for _, m := range methods { + if "/"+m.Service+"/"+m.Method == c.path { + got = append(got, fmt.Sprintf("max_request_bytes %d", limitOf(t, m))) + } + } + if !slices.Equal(got, c.want) { + t.Errorf("the limit or the problems = %q, want %q", got, c.want) + } + }) + } +} + +// limitOf is m's request limit as the RPC table writes it for m's route, or 0 when the table writes none: a limit read +// from a .proto option is the one the routes carry, and the table is where a route's limit is written out. +func limitOf(t *testing.T, m rpc.Method) uint64 { + t.Helper() + var rows []map[string]any + if err := json.Unmarshal(rpc.Table([]rpc.Route{{Method: m}}), &rows); err != nil || len(rows) != 1 { + t.Fatalf("the RPC table of %s/%s does not read back as one row: %v", m.Service, m.Method, err) + } + limit, _ := rows[0]["max_request_bytes"].(float64) + return uint64(limit) +} + // A root that is a symbolic link whose target is missing cannot be read, as a missing directory cannot: the proxyfile's // reader compares it with the other roots by the text of its path and leaves it to this problem. func TestMethodsRootLinkToNothing(t *testing.T) { diff --git a/internal/protofiles/testdata/limit/shop/v1/cart.proto b/internal/protofiles/testdata/limit/shop/v1/cart.proto new file mode 100644 index 0000000..7d62101 --- /dev/null +++ b/internal/protofiles/testdata/limit/shop/v1/cart.proto @@ -0,0 +1,26 @@ +syntax = "proto3"; + +package shop.v1; + +import "google/protobuf/descriptor.proto"; + +// The route option's message with a request limit beside the action: AddItem sets the limit, GetCart leaves it out. +message Route { + string action = 1; + uint32 max_request_bytes = 3; +} + +extend google.protobuf.MethodOptions { + Route route = 50000; +} + +service CartService { + rpc AddItem(Empty) returns (Empty) { + option (shop.v1.route) = {action: "use", max_request_bytes: 2048}; + } + rpc GetCart(Empty) returns (Empty) { + option (shop.v1.route) = {action: "use"}; + } +} + +message Empty {} diff --git a/internal/protofiles/testdata/limitclientstream/shop/v1/cart.proto b/internal/protofiles/testdata/limitclientstream/shop/v1/cart.proto new file mode 100644 index 0000000..3455e8d --- /dev/null +++ b/internal/protofiles/testdata/limitclientstream/shop/v1/cart.proto @@ -0,0 +1,26 @@ +syntax = "proto3"; + +package shop.v1; + +import "google/protobuf/descriptor.proto"; + +// Upload takes a stream of requests and sets a request limit; AddItem, a unary method, sets one too. +message Route { + string action = 1; + uint32 max_request_bytes = 3; +} + +extend google.protobuf.MethodOptions { + Route route = 50000; +} + +service CartService { + rpc AddItem(Empty) returns (Empty) { + option (shop.v1.route) = {action: "use", max_request_bytes: 2048}; + } + rpc Upload(stream Empty) returns (Empty) { + option (shop.v1.route) = {action: "use", max_request_bytes: 2048}; + } +} + +message Empty {} diff --git a/internal/protofiles/testdata/limitlargest/shop/v1/cart.proto b/internal/protofiles/testdata/limitlargest/shop/v1/cart.proto new file mode 100644 index 0000000..2ca3822 --- /dev/null +++ b/internal/protofiles/testdata/limitlargest/shop/v1/cart.proto @@ -0,0 +1,24 @@ +syntax = "proto3"; + +package shop.v1; + +import "google/protobuf/descriptor.proto"; + +// AddItem sets the largest request limit a method may set: 4294967290, which with the 5 bytes of the gRPC prefix is +// 4294967295, the largest uint32. +message Route { + string action = 1; + uint32 max_request_bytes = 3; +} + +extend google.protobuf.MethodOptions { + Route route = 50000; +} + +service CartService { + rpc AddItem(Empty) returns (Empty) { + option (shop.v1.route) = {action: "use", max_request_bytes: 4294967290}; + } +} + +message Empty {} diff --git a/internal/protofiles/testdata/limitover/shop/v1/cart.proto b/internal/protofiles/testdata/limitover/shop/v1/cart.proto new file mode 100644 index 0000000..b0ecfc2 --- /dev/null +++ b/internal/protofiles/testdata/limitover/shop/v1/cart.proto @@ -0,0 +1,24 @@ +syntax = "proto3"; + +package shop.v1; + +import "google/protobuf/descriptor.proto"; + +// AddItem sets a request limit one above the largest a method may set: 4294967291, which with the 5 bytes of the gRPC +// prefix is 4294967296, one past the largest uint32. +message Route { + string action = 1; + uint32 max_request_bytes = 3; +} + +extend google.protobuf.MethodOptions { + Route route = 50000; +} + +service CartService { + rpc AddItem(Empty) returns (Empty) { + option (shop.v1.route) = {action: "use", max_request_bytes: 4294967291}; + } +} + +message Empty {} diff --git a/internal/protofiles/testdata/limitstreams/shop/v1/cart.proto b/internal/protofiles/testdata/limitstreams/shop/v1/cart.proto new file mode 100644 index 0000000..0c493f9 --- /dev/null +++ b/internal/protofiles/testdata/limitstreams/shop/v1/cart.proto @@ -0,0 +1,27 @@ +syntax = "proto3"; + +package shop.v1; + +import "google/protobuf/descriptor.proto"; + +// Watch streams its answers and sets a request limit, which counts its one request; Sync takes a stream of requests +// and sets none. +message Route { + string action = 1; + uint32 max_request_bytes = 3; +} + +extend google.protobuf.MethodOptions { + Route route = 50000; +} + +service CartService { + rpc Watch(Empty) returns (stream Empty) { + option (shop.v1.route) = {action: "use", max_request_bytes: 2048}; + } + rpc Sync(stream Empty) returns (Empty) { + option (shop.v1.route) = {action: "use"}; + } +} + +message Empty {} diff --git a/internal/protofiles/testdata/limittext/shop/v1/cart.proto b/internal/protofiles/testdata/limittext/shop/v1/cart.proto new file mode 100644 index 0000000..8406280 --- /dev/null +++ b/internal/protofiles/testdata/limittext/shop/v1/cart.proto @@ -0,0 +1,23 @@ +syntax = "proto3"; + +package shop.v1; + +import "google/protobuf/descriptor.proto"; + +// The route option's message whose max_request_bytes holds text, which is no request limit. +message Route { + string action = 1; + string max_request_bytes = 3; +} + +extend google.protobuf.MethodOptions { + Route route = 50000; +} + +service CartService { + rpc AddItem(Empty) returns (Empty) { + option (shop.v1.route) = {action: "use", max_request_bytes: "2048"}; + } +} + +message Empty {} diff --git a/internal/render/render_test.go b/internal/render/render_test.go index 9b71b35..e71e51b 100644 --- a/internal/render/render_test.go +++ b/internal/render/render_test.go @@ -916,8 +916,9 @@ func TestRetryPolicy(t *testing.T) { retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}` - // 0 the refusal, 1 accounts-events, 2 to 4 the RPC routes (accounts, then shop's two), 5 accounts-webhooks, 6 - // catalog, 7 shop. + // 0 the refusal, 1 accounts-events, 2 to 9 the RPC routes (accounts, then the routes that refuse a GET, a query and, + // three of them, a compressed call to AddItem, whose max_request_bytes they serve, then shop's two), 10 + // accounts-webhooks, 11 catalog, 12 shop. routes := []any{"static_resources", "listeners", 0, "filter_chains", 0, "filters", 0, "typed_config", "route_config", "virtual_hosts", 0, "routes"} cases := []struct { @@ -925,13 +926,13 @@ func TestRetryPolicy(t *testing.T) { route int want string // the route's action }{ - {name: "a route's retries, to a service with two backends", route: 7, + {name: "a route's retries, to a service with two backends", route: 12, want: "{cluster: shop_http, timeout: 0s, idle_timeout: 90s, retry_policy: " + policy + "}"}, - {name: "the rpc entry's retries, to a service with two backends", route: 4, + {name: "the rpc entry's retries, to a service with two backends", route: 9, want: "{cluster: shop_grpc, timeout: 0s, idle_timeout: 90s, retry_policy: " + policy + "}"}, {name: "the rpc entry's retries, to a service with one backend", route: 2, want: `{cluster: accounts_grpc, host_rewrite_literal: "127.0.0.1:7070", timeout: 0s, idle_timeout: 90s, retry_policy: ` + policy + "}"}, - {name: "a route without retries", route: 6, want: "{cluster: catalog_http, timeout: 0s, idle_timeout: 90s}"}, + {name: "a route without retries", route: 11, want: "{cluster: catalog_http, timeout: 0s, idle_timeout: 90s}"}, } files, problems := render(requestFor(t, "full/yaml", "envoy.yaml")) if problems != nil { diff --git a/internal/render/request_limit_test.go b/internal/render/request_limit_test.go new file mode 100644 index 0000000..1f6cb86 --- /dev/null +++ b/internal/render/request_limit_test.go @@ -0,0 +1,548 @@ +package render + +import ( + "bytes" + "fmt" + "path/filepath" + "regexp" + "slices" + "strings" + "testing" + + "github.com/kitecorp/proxyfile/v2/internal/testsupport" +) + +// A method may limit the request a caller sends it, rpc.methods[].max_request_bytes, or the field of that name of the +// .proto option's message: the largest message, in bytes as serialized, the gateway passes to the method. The Envoy +// output turns on Envoy's buffer filter on the method's route with the limit plus the 5 bytes of the gRPC prefix, +// answers 405 to a GET on the method's path and 400 to a request whose path carries a query, because the Connect +// bridge reads a message from the query, where the filter counts nothing, and answers 415 to a compressed request +// there, because the filter counts the bytes it receives and a compressed message is inflated past them only in the +// service. These tests hold the file's parts; what Envoy answers with them (a message of exactly the limit served, one +// byte more refused, a GET, a query and a compressed request refused) is the conformance battery's scenario "a method's +// request limit" (conformance/scenarios_test.go), run on Envoy 1.40.2. + +// A file that writes no max_request_bytes renders the bytes v2.3.1 rendered for it: examples/full's YAML form as it was +// at v2.3.1, every key but a few, and the Envoy file v2.3.1 wrote for it (go run ./cmd/proxyfile render at the tag). +// -update never rewrites these two files, where it rewrites examples/full once the example takes the key. +func TestFilesWithoutTheLimitRenderAs231Did(t *testing.T) { + dir := t.TempDir() + files, problems := render(Request{Proxyfile: filepath.Join("testdata", "full-before-max-request-bytes.yaml"), + Out: filepath.Join(dir, "envoy.yaml")}) + if problems != nil { + t.Fatalf("render problems = %q, want none", testsupport.ProblemStrings(problems)) + } + want := testsupport.ReadFile(t, filepath.Join("testdata", "full-before-max-request-bytes.envoy.yaml")) + if !bytes.Equal(files[0].Bytes, want) { + line, before, now := testsupport.FirstDifferentLine(want, files[0].Bytes) + t.Errorf("envoy.yaml differs first on line %d:\n v2.3.1: %s\n rendered: %s", line, before, now) + } +} + +// nginx and HAProxy cannot carry a method's request limit in this version, so each refuses a file whose method writes +// it, by the key and where it is written, as docs/portability.md requires of a key a target cannot carry, and writes no +// file: a limit dropped without a word would let through what the method refuses on Envoy. A limit read from a .proto +// option is refused as one written in rpc.methods, at the method's line in the .proto file, and only on the method +// that sets it: testdata/limit's GetCart, which sets none, is routed. +func TestRequestLimitRefusedByNginxAndHAProxy(t *testing.T) { + throughOption, protoRoot := throughProto(t, "limit") + cases := []struct { + name, proxyfile string + at string // where the refusal names the key + }{ + {name: "in rpc.methods", proxyfile: inMethods("2048"), at: "g.yaml:10:68"}, + {name: "through rpc.proto", proxyfile: throughOption, at: protoRoot + "/shop/v1/cart.proto:18:3"}, + } + for _, target := range []struct{ name, generator string }{{"nginx", "nginx"}, {"haproxy", "HAProxy"}} { + for _, c := range cases { + t.Run(target.name+"/"+c.name, func(t *testing.T) { + dir := t.TempDir() + testsupport.WriteFile(t, filepath.Join(dir, "g.yaml"), c.proxyfile) + files, problems := render(Request{Proxyfile: filepath.Join(dir, "g.yaml"), Out: filepath.Join(dir, "out"), + Target: target.name}) + if files != nil { + t.Errorf("render returned files %q, want none", paths(files)) + } + want := []string{c.at + `: "rpc.methods[].max_request_bytes" is refused by --target ` + target.name + + ": not written by this version's " + target.generator + " generator; leave max_request_bytes out, or render it for envoy"} + if got := testsupport.ProblemStringsIn(dir, problems); !slices.Equal(got, want) { + t.Errorf("problems = %q, want %q", got, want) + } + }) + } + } +} + +// The buffer filter is listed once, turned off, right before the Connect bridge, the place where Envoy 1.40.2 was +// measured to refuse a Connect body and a gRPC frame one byte past a method's limit. Envoy refuses the entry without +// max_request_bytes (measured on Envoy 1.40.2), so it holds the smallest of the routes' values, here RemoveItem's 512 +// and the prefix's 5: no route the filter is off on reads it, and none it is on on admits more. +func TestRequestLimitListsTheBufferFilterRightBeforeTheBridge(t *testing.T) { + filters := listAt(t, renderedTree(t, limitProxyfile(true, true)), filtersAt...) + want := []string{"envoy.filters.http.lua", bufferFilter, "envoy.filters.http.connect_grpc_bridge", "envoy.filters.http.router"} + got := filterNames(filters) + if len(got) < len(want) || !slices.Equal(got[len(got)-len(want):], want) || strings.Count(strings.Join(got, " "), bufferFilter) != 1 { + t.Errorf("the filters are %q, want them to end with %q and to hold %s once", got, want, bufferFilter) + } + i := slices.IndexFunc(filters, func(f any) bool { return valueAt(f, "name") == bufferFilter }) + if i < 0 { + t.Fatalf("no filter is %s", bufferFilter) + } + entry := ` +name: envoy.filters.http.buffer +disabled: true +typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.buffer.v3.Buffer + max_request_bytes: 517 +` + if d := firstDifference(decode(t, []byte(entry)), filters[i], ""); d != "" { + t.Error(d) + } +} + +// Each method with a limit turns the filter on for its own route, with its limit and the 5 bytes of the gRPC prefix, +// which a Connect call's body gains in the bridge and a gRPC call's frame carries: a message of exactly the limit is +// served and one byte more refused (measured on Envoy 1.40.2). A method without one leaves the filter off. +func TestRequestLimitTurnsTheFilterOnPerRoute(t *testing.T) { + want := ` +- path: /shop.v1.CartService/AddItem + buffer: {"@type": type.googleapis.com/envoy.extensions.filters.http.buffer.v3.BufferPerRoute, buffer: {max_request_bytes: 2053}} +- path: /shop.v1.CartService/RemoveItem + buffer: {"@type": type.googleapis.com/envoy.extensions.filters.http.buffer.v3.BufferPerRoute, buffer: {max_request_bytes: 517}} +` + for _, host := range listAt(t, renderedTree(t, limitProxyfile(true, true)), hostsAt...) { + if d := firstDifference(decode(t, []byte(want)), limitedRoutes(t, host), ""); d != "" { + t.Errorf("virtual host %v: %s", valueAt(host, "name"), d) + } + } +} + +// limitedRoutes is each route of a virtual host that carries the buffer filter's entry, in the routes' order, as its +// path and the entry. +func limitedRoutes(t *testing.T, host any) []any { + t.Helper() + var limited []any + for _, route := range listAt(t, host, "routes") { + if entry := valueAt(route, "typed_per_filter_config", bufferFilter); entry != nil { + limited = append(limited, map[string]any{"path": valueAt(route, "match", "path"), "buffer": entry}) + } + } + return limited +} + +// The largest limit a method may set is 4294967290: the route's value adds the 5 bytes of the gRPC prefix, and Envoy +// reads that value as a uint32, whose largest is 4294967295. The largest renders from either source: the RPC table +// carries it as written, and the route's value decodes as the whole number 4294967295, so a value that wrapped past the +// uint32 or was written as a float such as 4.294967295e+09 fails. +func TestRequestLimitLargestValueRenders(t *testing.T) { + throughOption, _ := throughProto(t, "limitlargest") + cases := []struct{ name, proxyfile string }{ + {name: "in rpc.methods", proxyfile: inMethods("4294967290")}, + {name: "through rpc.proto", proxyfile: throughOption}, + } + table := testsupport.Document{ + `[`, + ` {"service": "shop.v1.CartService", "method": "AddItem", "action": "use", "reports": [], "max_request_bytes": 4294967290, "cluster": "cart_grpc"}`, + `]`, + }.String() + routes := ` +- path: /shop.v1.CartService/AddItem + buffer: {"@type": type.googleapis.com/envoy.extensions.filters.http.buffer.v3.BufferPerRoute, buffer: {max_request_bytes: 4294967295}} +` + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + dir := t.TempDir() + testsupport.WriteFile(t, filepath.Join(dir, "g.yaml"), c.proxyfile) + req := Request{Proxyfile: filepath.Join(dir, "g.yaml"), Out: filepath.Join(dir, "envoy.yaml"), + RPCTable: filepath.Join(dir, "rpc.json")} + files, problems := render(req) + if problems != nil { + t.Fatalf("render problems = %q, want none", testsupport.ProblemStringsIn(dir, problems)) + } + if got, want := paths(files), outputs(req); !slices.Equal(got, want) { + t.Fatalf("render returned files %q, want %q", got, want) + } + if got := string(files[1].Bytes); got != table { + t.Errorf("the RPC table = %q, want %q", got, table) + } + hosts := listAt(t, decode(t, files[0].Bytes), hostsAt...) + if len(hosts) == 0 { + t.Fatal("envoy.yaml has no virtual host") + } + for _, host := range hosts { + if d := firstDifference(decode(t, []byte(routes)), limitedRoutes(t, host), ""); d != "" { + t.Errorf("virtual host %v: %s", valueAt(host, "name"), d) + } + } + }) + } +} + +// One above the largest is refused from either source, as a value outside the range, and no target writes a file: the +// route's value would be 4294967296, past the largest uint32. In rpc.methods the format check refuses it at the value, +// in its own words. A .proto file is outside the format, so the option's limit is refused at the option key, in the +// form of the package's other problems of the option's message, with the format check's words and bound, naming the +// method and its value because the option key is in the proxyfile and the value in a .proto file. The option's range +// starts at 0, because a method that leaves the field out reads as 0, which is no limit. +func TestRequestLimitOverTheLargestIsRefused(t *testing.T) { + throughOption, _ := throughProto(t, "limitover") + cases := []struct{ name, proxyfile, want string }{ + {name: "in rpc.methods", proxyfile: inMethods("4294967291"), + want: `g.yaml:10:87: "max_request_bytes" must be a whole number from 1 to 4294967290`}, + {name: "through rpc.proto", proxyfile: throughOption, + want: "g.yaml:9:11: the field max_request_bytes of the option's message shop.v1.Route must be a whole number " + + "from 0 to 4294967290; shop.v1.CartService/AddItem sets 4294967291"}, + } + for _, target := range Targets { + for _, c := range cases { + t.Run(target.Name+"/"+c.name, func(t *testing.T) { + dir := t.TempDir() + testsupport.WriteFile(t, filepath.Join(dir, "g.yaml"), c.proxyfile) + files, problems := render(Request{Proxyfile: filepath.Join(dir, "g.yaml"), Out: filepath.Join(dir, "out"), + Target: target.Name}) + if files != nil { + t.Errorf("render returned files %q, want none", paths(files)) + } + if got, want := testsupport.ProblemStringsIn(dir, problems), []string{c.want}; !slices.Equal(got, want) { + t.Errorf("problems = %q, want %q", got, want) + } + }) + } + } +} + +// sentToCart sends the package shop.v1 to the service cart; inMethods and throughProto give it its methods. +const sentToCart = "listen: 8000\nservices:\n cart: {grpc: 5001}\norigins:\n all: {hosts: [localhost]}\n" + + "routes:\n - rpc: {to: {\"shop.v1.*\": cart}}\n" + +// inMethods is sentToCart with one method in rpc.methods, shop.v1.CartService/AddItem, whose max_request_bytes is +// limit: the key on line 10 at column 68, its value at column 87. +func inMethods(limit string) string { + return sentToCart + "rpc:\n methods:\n" + + " - {service: shop.v1.CartService, method: AddItem, action: use, max_request_bytes: " + limit + "}\n" +} + +// throughProto is sentToCart with its methods read through rpc.proto, the option key on line 9 at column 11, from the +// .proto files under the tree of internal/protofiles/testdata called name. It returns the tree's absolute path too, +// which a problem in one of its files names. +func throughProto(t *testing.T, name string) (proxyfile, root string) { + t.Helper() + root, err := filepath.Abs(filepath.Join("..", "protofiles", "testdata", name)) + if err != nil { + t.Fatal(err) + } + return sentToCart + "rpc:\n proto: {option: shop.v1.route, roots: [" + root + "]}\n", root +} + +// A method with a limit takes its message in a request body only, so five routes on its path come before its own route. +// The first answers 405 to a GET, with allow: POST as HTTP requires of a 405 (RFC 9110, 15.5.6): the Connect bridge +// makes a gRPC call of a Connect GET whose message is in the query, and the buffer filter counts no byte of a request +// without a body. It matches the method GET exactly, never "not POST", so a browser's preflight OPTIONS still reaches the +// route the CORS filter answers for. The second answers 400 to a request of any other method whose path carries a +// query string, ? in :path, which the route's own path match leaves out: the bridge reads a message from the query of +// any request that ends with its headers, a POST, PUT or DELETE with no body as well (measured on Envoy 1.40.2), and no +// gRPC or Connect call with a body carries a query. The other three answer 415 to a compressed request before any +// filter reads its body: the filter counts the bytes it receives, so a compressed message under the limit could inflate +// far past it in the service. There is one for each header a caller compresses a request by, grpc-encoding for gRPC, +// content-encoding for a Connect unary call and connect-content-encoding for the Connect streaming form, each when the +// header is present and is not identity in that case. A method without a limit keeps its one route, so a GET, a query +// or a compressed call to it is served as before. +func TestRequestLimitRefusesAGetAQueryAndCompressedRequests(t *testing.T) { + refusal := func(header string) string { + return fmt.Sprintf(` +- name: cart-rpc + match: + path: /shop.v1.CartService/AddItem + headers: + - {name: %s, string_match: {safe_regex: {regex: %q}}} + direct_response: {status: 415}`, header, notIdentity) + } + get := ` +- name: cart-rpc + match: + path: /shop.v1.CartService/AddItem + headers: + - {name: ":method", string_match: {exact: GET}} + direct_response: {status: 405} + response_headers_to_add: + - header: {key: allow, value: POST}` + query := ` +- name: cart-rpc + match: + path: /shop.v1.CartService/AddItem + headers: + - {name: ":path", string_match: {contains: "?"}} + direct_response: {status: 400}` + cases := []struct{ path, want string }{ + {path: "/shop.v1.CartService/AddItem", want: get + query + refusal("grpc-encoding") + refusal("content-encoding") + + refusal("connect-content-encoding") + ` +- name: cart-rpc + match: {path: /shop.v1.CartService/AddItem} +`}, + {path: "/shop.v1.CartService/GetCart", want: ` +- name: cart-rpc + match: {path: /shop.v1.CartService/GetCart} +`}, + } + // Without the bridge the routes are the same: the 415 on grpc-encoding is then all that keeps a compressed gRPC call + // from being inflated in the service. + for _, bridge := range []bool{true, false} { + hosts := listAt(t, renderedTree(t, limitProxyfile(true, bridge)), hostsAt...) + for _, c := range cases { + t.Run(fmt.Sprintf("bridge %t%s", bridge, c.path), func(t *testing.T) { + for _, host := range hosts { + // Each route on the path, in the routes' order, as its name, its match, its direct answer and the + // headers it adds to its answer. + var got []any + for _, route := range listAt(t, host, "routes") { + if valueAt(route, "match", "path") == c.path { + got = append(got, only(route, []string{"name", "match", "direct_response", "response_headers_to_add"})) + } + } + if d := firstDifference(decode(t, []byte(c.want)), got, ""); d != "" { + t.Errorf("virtual host %v: %s", valueAt(host, "name"), d) + } + } + }) + } + } +} + +// notIdentity is the one matcher of each 415 route: it takes every value of the header but exactly identity, an empty +// value included. Envoy 1.40.2 matches each value of a header written more than once on its own, and an inverted exact +// match fails as soon as one value is identity, so a request that wrote identity and gzip went past it to the method's +// route; one expression that no value but identity matches refuses such a request on its gzip whichever line comes +// first (measured on Envoy 1.40.2). +const notIdentity = "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$" + +// The expression each 415 route renders, compiled as RE2 (Go's regexp reads the syntax Envoy's safe_regex does), takes +// every value but identity: the other case, a value one letter short or long, and a list that holds identity beside +// another name are all refused. +func TestRequestLimitCompressionMatcherTakesAllButIdentity(t *testing.T) { + values := []struct { + value string + taken bool + }{ + {"identity", false}, + {"", true}, {"gzip", true}, {"br", true}, {"deflate", true}, + {"identit", true}, {"identityx", true}, {"xidentity", true}, {"Identity", true}, {"IDENTITY", true}, + {"identity,gzip", true}, {"gzip,identity", true}, {"identity, identity", true}, + {"identitys", true}, {strings.Repeat("y", 40), true}, + } + host := listAt(t, renderedTree(t, limitProxyfile(true, true)), hostsAt...)[0] + for _, header := range []string{"grpc-encoding", "content-encoding", "connect-content-encoding"} { + t.Run(header, func(t *testing.T) { + var expression string + for _, route := range listAt(t, host, "routes") { + if valueAt(route, "match", "path") == "/shop.v1.CartService/AddItem" && valueAt(route, "match", "headers", 0, "name") == header { + expression, _ = valueAt(route, "match", "headers", 0, "string_match", "safe_regex", "regex").(string) + } + } + if expression == "" { + t.Fatalf("no route on /shop.v1.CartService/AddItem matches %s with a safe_regex", header) + } + matcher := regexp.MustCompile(expression) + for _, v := range values { + if got := matcher.MatchString(v.value); got != v.taken { + t.Errorf("%s %q: taken = %t, want %t", header, v.value, got, v.taken) + } + } + }) + } +} + +// Each of the five routes before a limited method's own carries what the method's route carries for the filters before +// the router, and nothing for the filters after the answer is known: the same metadata, so the request is counted in the +// rpc entry's rate limit and the check is told the method's action as for the method's own call, and the same +// header_mutation entry, which writes the question for the check; no buffer, bridge or lua entry. Only the answer +// differs. A file with neither auth nor a rate limit writes neither key on any of them. +func TestRequestLimitRefusalsCarryTheMethodsRouteData(t *testing.T) { + const checked = `listen: 8000 +services: + cart: {http: 5000, grpc: 5001} +auth: {ask: cart /check, timeout: 1s, enabled: true, when_unavailable: deny} +origins: + all: {hosts: [localhost]} +routes: + - rpc: {to: {"shop.v1.*": cart}, rate_limit: {requests: 40, per: 1s, by: all}} +rpc: + methods: + - {service: shop.v1.CartService, method: AddItem, action: use, reports: [browse], max_request_bytes: 2048} +envoy: {namespace: edge, connect_bridge: %t} +` + const carried = ` +metadata: {filter_metadata: {edge: {action: use}, edge.rate_limit: {all: rpc}}} +typed_per_filter_config: + envoy.filters.http.header_mutation: + "@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute + mutations: + request_mutations: + - {append: {header: {key: x-gateway-action, value: use}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}} + - {append: {header: {key: x-gateway-reports, value: browse}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}} +` + cases := []struct { + name, proxyfile string + want string // each refusal route's metadata and typed_per_filter_config + }{ + {name: "auth and a rate limit, the bridge on", proxyfile: fmt.Sprintf(checked, true), want: carried}, + {name: "auth and a rate limit, the bridge off", proxyfile: fmt.Sprintf(checked, false), want: carried}, + {name: "neither", proxyfile: limitProxyfile(true, true), want: "{}"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + for _, host := range listAt(t, renderedTree(t, c.proxyfile), hostsAt...) { + var got []any + for _, route := range listAt(t, host, "routes") { + if valueAt(route, "match", "path") == "/shop.v1.CartService/AddItem" && valueAt(route, "direct_response") != nil { + got = append(got, only(route, []string{"metadata", "typed_per_filter_config"})) + } + } + entry := decode(t, []byte(c.want)) + if d := firstDifference([]any{entry, entry, entry, entry, entry}, got, ""); d != "" { + t.Errorf("virtual host %v: %s", valueAt(host, "name"), d) + } + } + }) + } +} + +// Without the Connect bridge, the buffer filter takes the bridge's place, right before the router. +func TestRequestLimitWithoutTheBridgeSitsRightBeforeTheRouter(t *testing.T) { + got := filterNames(listAt(t, renderedTree(t, limitProxyfile(true, false)), filtersAt...)) + want := []string{bufferFilter, "envoy.filters.http.router"} + if len(got) < len(want) || !slices.Equal(got[len(got)-len(want):], want) || strings.Count(strings.Join(got, " "), bufferFilter) != 1 { + t.Errorf("the filters are %q, want them to end with %q and to hold %s once", got, want, bufferFilter) + } +} + +// A method's limit holds on its own route only, so a route written before the rpc entry that takes the method's path +// would serve every call to it with no limit: Envoy picks the first route that matches. Such a file is refused, by the +// route, naming the method, whatever the route's other conditions and wherever the limit is written; a method without +// a limit is not named. A route before the entry that takes no limited path, and the same route after the entry, are +// not refused. +func TestRequestLimitRefusesARouteBeforeTheEntryThatTakesItsPath(t *testing.T) { + const head = "listen: 8000\nservices:\n cart: {http: 5000, grpc: 5001}\norigins:\n all: {hosts: [localhost]}\nroutes:\n" + const entry = " - rpc: {to: {\"shop.v1.*\": cart}}\n" + const methods = "rpc:\n methods:\n - {service: shop.v1.CartService, method: AddItem, max_request_bytes: 2048}\n" + + " - {service: shop.v1.CartService, method: GetCart}\n" + const covering = " - {name: cart, prefix: /shop.v1.CartService/, to: cart}\n" + // The route on line 7, the first of routes. + const refusal = `g.yaml:7:5: route "cart" is written before the rpc entry and takes the path of shop.v1.CartService/AddItem, ` + + "so that method's max_request_bytes would not apply; write the route after the rpc entry" + protoRoot, err := filepath.Abs(filepath.Join("..", "protofiles", "testdata", "limit")) + if err != nil { + t.Fatal(err) + } + cases := []struct { + name, proxyfile string + methodsFile string // written to m.json and given as --rpc-methods when not empty + want []string + }{ + {name: "a prefix of the service", proxyfile: head + covering + entry + methods, want: []string{refusal}}, + {name: "the prefix /", proxyfile: head + " - {name: cart, prefix: /, to: cart}\n" + entry + methods, want: []string{refusal}}, + {name: "the method's path", proxyfile: head + " - {name: cart, path: /shop.v1.CartService/AddItem, to: cart}\n" + entry + methods, + want: []string{refusal}}, + {name: "a pattern", proxyfile: head + " - {name: cart, pattern: \"/shop[.]v1[.]CartService/[A-Za-z]+\", to: cart}\n" + entry + methods, + want: []string{refusal}}, + {name: "a prefix of the service with a method", proxyfile: head + " - {name: cart, prefix: /shop.v1.CartService/, method: POST, to: cart}\n" + + entry + methods, want: []string{refusal}}, + {name: "the limit in a methods file", proxyfile: head + covering + entry, + methodsFile: `[{"service": "shop.v1.CartService", "method": "AddItem", "max_request_bytes": 2048}, {"service": "shop.v1.CartService", "method": "GetCart"}]`, + want: []string{refusal}}, + {name: "the limit in a .proto option", proxyfile: head + covering + entry + + "rpc:\n proto: {option: shop.v1.route, roots: [" + protoRoot + "]}\n", want: []string{refusal}}, + {name: "a route before the entry that takes no method's path", proxyfile: head + " - {name: static, prefix: /static/, to: cart}\n" + + entry + methods}, + {name: "the same route after the entry", proxyfile: head + entry + covering + methods}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + dir := t.TempDir() + req := Request{Proxyfile: filepath.Join(dir, "g.yaml"), Out: filepath.Join(dir, "envoy.yaml")} + testsupport.WriteFile(t, req.Proxyfile, c.proxyfile) + if c.methodsFile != "" { + req.RPCMethods = filepath.Join(dir, "m.json") + testsupport.WriteFile(t, req.RPCMethods, c.methodsFile) + } + files, problems := render(req) + if got := testsupport.ProblemStringsIn(dir, problems); !slices.Equal(got, c.want) { + t.Errorf("problems = %q, want %q", got, c.want) + } + if wantFiles := c.want == nil; (files != nil) != wantFiles { + t.Errorf("render returned files %q, want files: %t", paths(files), wantFiles) + } + }) + } +} + +// A route before an rpc entry none of whose methods writes a limit is not refused, and the file renders the bytes it +// rendered before the rule: testdata/route-before-rpc-entry.envoy.yaml, written by go run ./cmd/proxyfile render from +// testdata/route-before-rpc-entry.yaml at the commit before the rule, 940904a. +func TestARouteBeforeAnEntryWithoutALimitRendersAsBefore(t *testing.T) { + dir := t.TempDir() + files, problems := render(Request{Proxyfile: filepath.Join("testdata", "route-before-rpc-entry.yaml"), Out: filepath.Join(dir, "envoy.yaml")}) + if problems != nil { + t.Fatalf("render problems = %q, want none", testsupport.ProblemStrings(problems)) + } + want := testsupport.ReadFile(t, filepath.Join("testdata", "route-before-rpc-entry.envoy.yaml")) + if !bytes.Equal(files[0].Bytes, want) { + line, before, now := testsupport.FirstDifferentLine(want, files[0].Bytes) + t.Errorf("envoy.yaml differs first on line %d:\n before: %s\n rendered: %s", line, before, now) + } +} + +// A file whose methods write no limit writes no buffer filter at all, neither on the listener nor on a route: its +// filters are those it had before the key, the bridge and its Lua filter last before the router. +func TestNoLimitNoBufferFilter(t *testing.T) { + envoy := renderedEnvoy(t, limitProxyfile(false, true)) + want := []string{"envoy.filters.http.lua", "envoy.filters.http.connect_grpc_bridge", "envoy.filters.http.router"} + if got := filterNames(listAt(t, decode(t, envoy), filtersAt...)); len(got) < len(want) || !slices.Equal(got[len(got)-len(want):], want) { + t.Fatalf("the filters are %q, want them to end with %q", got, want) + } + for _, text := range []string{bufferFilter, "envoy.extensions.filters.http.buffer."} { + if n := bytes.Count(envoy, []byte(text)); n != 0 { + t.Errorf("envoy.yaml holds %s %d times, want none", text, n) + } + } +} + +// bufferFilter is the name of Envoy's buffer filter, under which the listener lists it and a route turns it on. +const bufferFilter = "envoy.filters.http.buffer" + +// filtersAt is the path of the HTTP filters of an Envoy tree, and hostsAt that of its virtual hosts. +var ( + filtersAt = []any{"static_resources", "listeners", 0, "filter_chains", 0, "filters", 0, "typed_config", "http_filters"} + hostsAt = []any{"static_resources", "listeners", 0, "filter_chains", 0, "filters", 0, "typed_config", "route_config", "virtual_hosts"} +) + +// filterNames is the name of each HTTP filter, in the listener's order. +func filterNames(filters []any) []string { + var found []string + for _, f := range filters { + name, _ := valueAt(f, "name").(string) + found = append(found, name) + } + return found +} + +// limitProxyfile is a gateway whose one service, cart, answers the package shop.v1 over gRPC, with three methods: +// AddItem, which writes max_request_bytes 2048 with limits, RemoveItem, 512 with limits, and GetCart, which writes +// none. bridge is the file's envoy.connect_bridge. +func limitProxyfile(limits, bridge bool) string { + limit := func(n int) string { + if !limits { + return "" + } + return fmt.Sprintf(", max_request_bytes: %d", n) + } + var b strings.Builder + b.WriteString("listen: 8000\nservices:\n cart: {grpc: 5001}\n") + b.WriteString("origins:\n all: {hosts: [localhost], origins: [\"http://localhost:3000\"]}\n") + b.WriteString("routes:\n - rpc: {to: {\"shop.v1.*\": cart}}\n") + b.WriteString("rpc:\n methods:\n") + fmt.Fprintf(&b, " - {service: shop.v1.CartService, method: AddItem, action: use%s}\n", limit(2048)) + fmt.Fprintf(&b, " - {service: shop.v1.CartService, method: RemoveItem%s}\n", limit(512)) + b.WriteString(" - {service: shop.v1.CartService, method: GetCart}\n") + fmt.Fprintf(&b, "envoy: {connect_bridge: %t}\n", bridge) + return b.String() +} diff --git a/internal/render/testdata/full-before-max-request-bytes.envoy.yaml b/internal/render/testdata/full-before-max-request-bytes.envoy.yaml new file mode 100644 index 0000000..78cfca5 --- /dev/null +++ b/internal/render/testdata/full-before-max-request-bytes.envoy.yaml @@ -0,0 +1,657 @@ +# Generated by proxyfile. Do not edit: change the proxyfile beside it and run proxyfile render; proxyfile check fails on a hand edit. +admin: + address: {socket_address: {address: 127.0.0.1, port_value: 9901}} + allow_paths: [{exact: /ready}, {exact: /stats}, {exact: /server_info}] +overload_manager: + refresh_interval: 0.25s + resource_monitors: + - name: envoy.resource_monitors.fixed_heap + typed_config: + "@type": type.googleapis.com/envoy.extensions.resource_monitors.fixed_heap.v3.FixedHeapConfig + max_heap_size_bytes: 268435456 + - name: envoy.resource_monitors.global_downstream_max_connections + typed_config: + "@type": type.googleapis.com/envoy.extensions.resource_monitors.downstream_connections.v3.DownstreamConnectionsConfig + max_active_downstream_connections: 4096 + actions: + - name: envoy.overload_actions.shrink_heap + triggers: [{name: envoy.resource_monitors.fixed_heap, threshold: {value: 0.90}}] + - name: envoy.overload_actions.stop_accepting_requests + triggers: [{name: envoy.resource_monitors.fixed_heap, threshold: {value: 0.98}}] +static_resources: + listeners: + - name: public + address: {socket_address: {address: 0.0.0.0, port_value: 10000}} + filter_chains: + - filters: + - name: envoy.filters.network.http_connection_manager + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager + stat_prefix: public + use_remote_address: true + always_set_request_id_in_response: true + request_id_extension: + typed_config: + "@type": type.googleapis.com/envoy.extensions.request_id.uuid.v3.UuidRequestIdConfig + pack_trace_reason: false + tracing: + client_sampling: {value: 0} + random_sampling: {value: 10} + custom_tags: + - tag: "environment" + environment: {name: "APP_ENVIRONMENT", default_value: "local"} + - tag: "request_id" + request_header: {name: "x-request-id"} + provider: + name: envoy.tracers.opentelemetry + typed_config: + "@type": type.googleapis.com/envoy.config.trace.v3.OpenTelemetryConfig + grpc_service: + envoy_grpc: {cluster_name: "otel_collector"} + service_name: "example-gateway" + server_header_transformation: PASS_THROUGH + max_request_headers_kb: 96 + common_http_protocol_options: {max_headers_count: 150} + normalize_path: true + merge_slashes: true + path_with_escaped_slashes_action: UNESCAPE_AND_FORWARD + upgrade_configs: [{upgrade_type: websocket}] + local_reply_config: + mappers: + - filter: {response_flag_filter: {flags: [UF, UH, UC, URX]}} + status_code: 502 + body: {inline_string: ""} + - filter: + and_filter: + filters: + - status_code_filter: + comparison: {op: EQ, value: {default_value: 403, runtime_key: gateway.local_reply.origin_refused_status}} + - header_filter: + header: {name: origin, present_match: true} + body: {inline_string: "Invalid CORS request"} + - filter: + and_filter: + filters: + - response_flag_filter: {flags: [UAEX]} + - status_code_filter: {comparison: {op: GE, value: {default_value: 200}}} + - status_code_filter: {comparison: {op: LE, value: {default_value: 299}}} + status_code: 403 + - filter: {response_flag_filter: {flags: [UAEX]}} + - filter: + and_filter: + filters: + - status_code_filter: + comparison: {op: EQ, value: {default_value: 429, runtime_key: gateway.local_reply.rate_limited_status}} + - header_filter: + header: {name: connect-protocol-version, present_match: true} + body: {inline_string: '{"code":"resource_exhausted","message":"local_rate_limited"}'} + body_format_override: + text_format_source: {inline_string: "%LOCAL_REPLY_BODY%"} + content_type: application/json + access_log: + - name: envoy.access_loggers.stdout + filter: + or_filter: + filters: + - status_code_filter: + comparison: {op: GE, value: {default_value: 400, runtime_key: gateway.request_log.min_status}} + - response_flag_filter: {} + - runtime_filter: + runtime_key: gateway.request_log.sample + percent_sampled: {numerator: 1, denominator: HUNDRED} + typed_config: + "@type": type.googleapis.com/envoy.extensions.access_loggers.stream.v3.StdoutAccessLog + log_format: + json_format: + time: "%START_TIME%" + route: "%ROUTE_NAME%" + host: "%REQ(:AUTHORITY)%" + method: "%REQ(:METHOD)%" + protocol: "%PROTOCOL%" + status: "%RESPONSE_CODE%" + flags: "%RESPONSE_FLAGS%" + details: "%RESPONSE_CODE_DETAILS%" + duration_ms: "%DURATION%" + upstream_ms: "%RESPONSE_DURATION%" + bytes_in: "%BYTES_RECEIVED%" + bytes_out: "%BYTES_SENT%" + upstream: "%UPSTREAM_CLUSTER%" + request_id: "%REQ(X-REQUEST-ID)%" + authz_us: "%FILTER_STATE(envoy.filters.http.ext_authz:FIELD:latency_us)%" + - name: envoy.access_loggers.stdout + filter: + response_flag_filter: {flags: [UH, UF, UO, UC, UT, URX, UPE]} + typed_config: + "@type": type.googleapis.com/envoy.extensions.access_loggers.stream.v3.StdoutAccessLog + log_format: + json_format: + event: gateway_upstream_failure + route: "%ROUTE_NAME%" + status: "%RESPONSE_CODE%" + flags: "%RESPONSE_FLAGS%" + upstream: "%UPSTREAM_CLUSTER%" + - name: envoy.access_loggers.stdout + filter: + and_filter: + filters: + - header_filter: + header: {name: x-envoy-auth-failure-mode-allowed, present_match: true} + - metadata_filter: + matcher: {filter: "example.gateway", path: [{key: filtered}], value: {bool_match: true}} + match_if_key_not_found: false + typed_config: + "@type": type.googleapis.com/envoy.extensions.access_loggers.stream.v3.StdoutAccessLog + log_format: + json_format: + event: gateway_auth_unavailable + route: "%ROUTE_NAME%" + action: "%METADATA(ROUTE:example.gateway:action)%" + status: "%RESPONSE_CODE%" + failure_mode_allowed: "%REQ(x-envoy-auth-failure-mode-allowed)%" + request_id: "%REQ(X-REQUEST-ID)%" + early_header_mutation_extensions: + - name: envoy.http.early_header_mutation.header_mutation + typed_config: + "@type": type.googleapis.com/envoy.extensions.http.early_header_mutation.header_mutation.v3.HeaderMutation + mutations: + - remove_on_match: {key_matcher: {prefix: "x-user-"}} + - remove_on_match: {key_matcher: {prefix: "x-client-"}} + - remove_on_match: {key_matcher: {prefix: "x-tier-"}} + - remove_on_match: {key_matcher: {prefix: "x-gateway-"}} + - remove: "x-subject" + - remove: "x-roles" + - remove: x-envoy-auth-failure-mode-allowed + - remove: x-envoy-downstream-service-cluster + - remove: x-envoy-downstream-service-node + - remove: x-envoy-decorator-operation + http_filters: + - name: envoy.filters.http.set_metadata + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.set_metadata.v3.Config + metadata: + - metadata_namespace: "example.gateway" + value: {filtered: true} + - name: envoy.filters.http.header_mutation + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutation + mutations: + response_mutations: + - append: + header: {key: vary, value: Origin} + append_action: APPEND_IF_EXISTS_OR_ADD + - remove: x-envoy-upstream-service-time + - name: envoy.filters.http.rbac + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.rbac.v3.RBAC + - name: envoy.filters.http.cors + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.cors.v3.Cors + - name: envoy.filters.http.local_ratelimit + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.local_ratelimit.v3.LocalRateLimit + stat_prefix: rate_limit + filter_enabled: + default_value: + numerator: 100 + denominator: HUNDRED + filter_enforced: + default_value: + numerator: 100 + denominator: HUNDRED + rate_limited_as_resource_exhausted: true + always_consume_default_token_bucket: false + max_dynamic_descriptors: 65536 + rate_limits: + - actions: + - metadata: {descriptor_key: bucket, metadata_key: {key: "example.gateway.rate_limit", path: [{key: all}]}, source: ROUTE_ENTRY} + - actions: + - metadata: {descriptor_key: bucket, metadata_key: {key: "example.gateway.rate_limit", path: [{key: client}]}, source: ROUTE_ENTRY} + - remote_address: {} + descriptors: + - entries: [{key: bucket, value: "rpc"}] + token_bucket: {max_tokens: 100, tokens_per_fill: 100, fill_interval: 1s} + - entries: [{key: bucket, value: "catalog"}, {key: remote_address}] + token_bucket: {max_tokens: 30, tokens_per_fill: 20, fill_interval: 1s} + - name: envoy.filters.http.jwt_authn + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.JwtAuthentication + providers: + jwt: + issuer: "https://login.example.com" + audiences: ["api.example.com", "admin.example.com"] + require_expiration: true + remote_jwks: + http_uri: {uri: "https://login.example.com/.well-known/jwks.json", cluster: jwks, timeout: 2s} + retry_policy: {num_retries: 1} + forward: true + from_headers: [{name: "x-access-token"}] + claim_to_headers: [{header_name: "x-subject", claim_name: "sub"}, {header_name: "x-roles", claim_name: "realm.roles"}] + rules: + - match: {prefix: "/"} + requires: + requires_any: + requirements: [{provider_name: jwt}, {allow_missing: {}}] + - name: envoy.filters.http.ext_authz + typed_config: + "@type": type.googleapis.com/envoy.extensions.common.matching.v3.ExtensionWithMatcher + extension_config: + name: envoy.filters.http.ext_authz + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthz + http_service: + server_uri: {uri: "http://127.0.0.1:7070/auth/check", cluster: "accounts_http", timeout: 1.5s} + path_override: "/auth/check" + authorization_request: + headers_to_add: [{key: x-gateway-timeout-ms, value: "1500"}, {key: x-forwarded-uri, value: "%REQ(:PATH)%"}, {key: x-forwarded-method, value: "%REQ(:METHOD)%"}, {key: x-forwarded-proto, value: "https"}, {key: x-forwarded-host, value: "%REQ(:AUTHORITY)%"}] + authorization_response: + allowed_upstream_headers: + patterns: + - prefix: "x-user-" + - prefix: "x-tier-" + failure_mode_allow: true + failure_mode_allow_header_add: true + allowed_headers: + patterns: + - exact: "authorization" + - exact: "x-country" + - exact: x-gateway-action + - exact: x-gateway-reports + emit_filter_state_stats: true + filter_enabled: + default_value: {numerator: 100, denominator: HUNDRED} + runtime_key: gateway.ext_authz.enabled + xds_matcher: + matcher_list: + matchers: + - predicate: + not_matcher: + single_predicate: + input: + name: "authorization" + typed_config: + "@type": type.googleapis.com/envoy.type.matcher.v3.HttpRequestHeaderMatchInput + header_name: "authorization" + value_match: {safe_regex: {google_re2: {}, regex: ".+"}} + on_match: + action: + name: skip + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.common.matcher.action.v3.SkipFilter + - name: envoy.filters.http.lua + disabled: true + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua + default_source_code: + inline_string: | + -- Connect's status today for each code whose status the bridge writes from the old table. + local CONNECT_STATUS = { + canceled = "499", + deadline_exceeded = "504", + failed_precondition = "400", + unimplemented = "501", + } + local OLD_STATUS = {["404"] = true, ["408"] = true, ["412"] = true} + + function envoy_on_response(response_handle) + local headers = response_handle:headers() + if not OLD_STATUS[headers:get(":status")] or headers:get("content-type") ~= "application/json" then + return + end + local body = response_handle:body() + if body == nil then + return + end + -- The bridge writes the error with protobuf's JSON printer: its keys come in no fixed order + -- (message before code, as measured), and a quote inside a string is always escaped, so the + -- only "code":"..." pair in the body is the error's own. + local code = body:getBytes(0, body:length()):match('"code"%s*:%s*"([%l_]+)"') + local status = CONNECT_STATUS[code] + if status ~= nil then + -- Asked for again: the header object from before body() died while the body was awaited. + response_handle:headers():replace(":status", status) + end + end + - name: envoy.filters.http.connect_grpc_bridge + disabled: true + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.connect_grpc_bridge.v3.FilterConfig + - name: envoy.filters.http.router + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router + suppress_envoy_headers: true + route_config: + name: public + request_headers_to_remove: [x-gateway-action, x-gateway-reports] + ignore_port_in_host_matching: true + virtual_hosts: + - name: "live" + domains: ["api.example.com", "api.example.org"] + typed_per_filter_config: + envoy.filters.http.rbac: + "@type": type.googleapis.com/envoy.extensions.filters.http.rbac.v3.RBACPerRoute + rbac: + rules: + action: ALLOW + policies: + browser-origins: + permissions: [{any: true}] + principals: + - {not_id: {header: {name: origin, present_match: true}}} + - {header: {name: origin, string_match: {safe_regex: {regex: "^https?://api\\.example\\.com(:[0-9]+)?$"}}}} + - {header: {name: origin, string_match: {safe_regex: {regex: "^https?://api\\.example\\.org(:[0-9]+)?$"}}}} + - {header: {name: origin, string_match: {exact: "https://example.com", ignore_case: true}}} + - {header: {name: origin, string_match: {exact: "https://www.example.com", ignore_case: true}}} + - {header: {name: origin, string_match: {safe_regex: {regex: "^https://.*\\.example\\.com$"}}}} + envoy.filters.http.cors: + "@type": type.googleapis.com/envoy.extensions.filters.http.cors.v3.CorsPolicy + allow_origin_string_match: + - {exact: "https://example.com", ignore_case: true} + - {exact: "https://www.example.com", ignore_case: true} + - {safe_regex: {regex: "^https://.*\\.example\\.com$"}} + allow_methods: "*" + allow_headers: "*" + expose_headers: "Content-Disposition,X-Request-Id" + max_age: "600" + forward_not_matching_preflights: false + routes: + - name: "refused:dot-segment-with-parameter" + match: {safe_regex: {regex: ".*/\\.\\.?(?:;|%3[Bb]).*"}} + direct_response: {status: 400} + - name: "accounts-events" + match: {safe_regex: {regex: "^/events/[a-z0-9-]+$"}} + decorator: {operation: "accounts-events", propagate: false} + route: {cluster: "accounts_http", host_rewrite_literal: "127.0.0.1:7070", timeout: 0s, idle_timeout: 90s} + typed_per_filter_config: + envoy.filters.http.jwt_authn: + "@type": type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.PerRouteConfig + disabled: true + envoy.filters.http.ext_authz: + "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute + disabled: true + - {name: "accounts-rpc", match: {path: "/example.accounts.v1.ProfileService/GetProfile"}, metadata: {filter_metadata: {"example.gateway": {action: ""}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "accounts-rpc", propagate: false}, typed_per_filter_config: {envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "accounts_grpc", host_rewrite_literal: "127.0.0.1:7070", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem"}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/GetCart"}, metadata: {filter_metadata: {"example.gateway": {action: "browse"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - name: "accounts-webhooks" + match: {path: "/api/webhooks", headers: [{name: ":method", string_match: {exact: "POST"}}]} + decorator: {operation: "accounts-webhooks", propagate: false} + route: {cluster: "accounts_http", host_rewrite_literal: "127.0.0.1:7070", prefix_rewrite: "/hooks/payments", timeout: 0s, idle_timeout: 90s} + typed_per_filter_config: + envoy.filters.http.jwt_authn: + "@type": type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.PerRouteConfig + disabled: true + envoy.filters.http.ext_authz: + "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute + disabled: true + - name: "catalog" + match: {prefix: "/catalog/"} + metadata: {filter_metadata: {"example.gateway": {action: ""}, "example.gateway.rate_limit": {client: "catalog"}}} + decorator: {operation: "catalog", propagate: false} + route: {cluster: "catalog_http", timeout: 0s, idle_timeout: 90s} + - name: "shop" + match: {prefix: "/"} + metadata: {filter_metadata: {"example.gateway": {action: ""}}} + decorator: {operation: "shop", propagate: false} + route: {cluster: "shop_http", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}} + - name: "test" + domains: ["api.test.example.com"] + typed_per_filter_config: + envoy.filters.http.rbac: + "@type": type.googleapis.com/envoy.extensions.filters.http.rbac.v3.RBACPerRoute + rbac: + rules: + action: ALLOW + policies: + browser-origins: + permissions: [{any: true}] + principals: + - {not_id: {header: {name: origin, present_match: true}}} + - {header: {name: origin, string_match: {safe_regex: {regex: "^https?://api\\.test\\.example\\.com(:[0-9]+)?$"}}}} + - {header: {name: origin, string_match: {exact: "http://localhost:3000", ignore_case: true}}} + - {header: {name: origin, string_match: {exact: "https://test.example.com", ignore_case: true}}} + - {header: {name: origin, string_match: {safe_regex: {regex: "^https://.*\\.test\\.example\\.com$"}}}} + envoy.filters.http.cors: + "@type": type.googleapis.com/envoy.extensions.filters.http.cors.v3.CorsPolicy + allow_origin_string_match: + - {exact: "http://localhost:3000", ignore_case: true} + - {exact: "https://test.example.com", ignore_case: true} + - {safe_regex: {regex: "^https://.*\\.test\\.example\\.com$"}} + allow_methods: "*" + allow_headers: "*" + expose_headers: "Content-Disposition,X-Request-Id" + max_age: "600" + forward_not_matching_preflights: false + routes: + - name: "refused:dot-segment-with-parameter" + match: {safe_regex: {regex: ".*/\\.\\.?(?:;|%3[Bb]).*"}} + direct_response: {status: 400} + - name: "accounts-events" + match: {safe_regex: {regex: "^/events/[a-z0-9-]+$"}} + decorator: {operation: "accounts-events", propagate: false} + route: {cluster: "accounts_http", host_rewrite_literal: "127.0.0.1:7070", timeout: 0s, idle_timeout: 90s} + typed_per_filter_config: + envoy.filters.http.jwt_authn: + "@type": type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.PerRouteConfig + disabled: true + envoy.filters.http.ext_authz: + "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute + disabled: true + - {name: "accounts-rpc", match: {path: "/example.accounts.v1.ProfileService/GetProfile"}, metadata: {filter_metadata: {"example.gateway": {action: ""}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "accounts-rpc", propagate: false}, typed_per_filter_config: {envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "accounts_grpc", host_rewrite_literal: "127.0.0.1:7070", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem"}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/GetCart"}, metadata: {filter_metadata: {"example.gateway": {action: "browse"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - name: "accounts-webhooks" + match: {path: "/api/webhooks", headers: [{name: ":method", string_match: {exact: "POST"}}]} + decorator: {operation: "accounts-webhooks", propagate: false} + route: {cluster: "accounts_http", host_rewrite_literal: "127.0.0.1:7070", prefix_rewrite: "/hooks/payments", timeout: 0s, idle_timeout: 90s} + typed_per_filter_config: + envoy.filters.http.jwt_authn: + "@type": type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.PerRouteConfig + disabled: true + envoy.filters.http.ext_authz: + "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute + disabled: true + - name: "catalog" + match: {prefix: "/catalog/"} + metadata: {filter_metadata: {"example.gateway": {action: ""}, "example.gateway.rate_limit": {client: "catalog"}}} + decorator: {operation: "catalog", propagate: false} + route: {cluster: "catalog_http", timeout: 0s, idle_timeout: 90s} + - name: "shop" + match: {prefix: "/"} + metadata: {filter_metadata: {"example.gateway": {action: ""}}} + decorator: {operation: "shop", propagate: false} + route: {cluster: "shop_http", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}} + - name: "local" + domains: ["127.0.0.1", "localhost"] + typed_per_filter_config: + envoy.filters.http.rbac: + "@type": type.googleapis.com/envoy.extensions.filters.http.rbac.v3.RBACPerRoute + rbac: + rules: + action: ALLOW + policies: + browser-origins: + permissions: [{any: true}] + principals: + - {not_id: {header: {name: origin, present_match: true}}} + - {header: {name: origin, string_match: {safe_regex: {regex: "^https?://127\\.0\\.0\\.1(:[0-9]+)?$"}}}} + - {header: {name: origin, string_match: {safe_regex: {regex: "^https?://localhost(:[0-9]+)?$"}}}} + - {header: {name: origin, string_match: {safe_regex: {regex: "^http://.*\\.example\\.com:.*$"}}}} + - {header: {name: origin, string_match: {safe_regex: {regex: "^http://localhost:.*$"}}}} + envoy.filters.http.cors: + "@type": type.googleapis.com/envoy.extensions.filters.http.cors.v3.CorsPolicy + allow_origin_string_match: + - {safe_regex: {regex: "^http://.*\\.example\\.com:.*$"}} + - {safe_regex: {regex: "^http://localhost:.*$"}} + allow_methods: "*" + allow_headers: "*" + expose_headers: "Content-Disposition,X-Request-Id" + max_age: "600" + forward_not_matching_preflights: false + routes: + - name: "refused:dot-segment-with-parameter" + match: {safe_regex: {regex: ".*/\\.\\.?(?:;|%3[Bb]).*"}} + direct_response: {status: 400} + - name: "accounts-events" + match: {safe_regex: {regex: "^/events/[a-z0-9-]+$"}} + decorator: {operation: "accounts-events", propagate: false} + route: {cluster: "accounts_http", host_rewrite_literal: "127.0.0.1:7070", timeout: 0s, idle_timeout: 90s} + typed_per_filter_config: + envoy.filters.http.jwt_authn: + "@type": type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.PerRouteConfig + disabled: true + envoy.filters.http.ext_authz: + "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute + disabled: true + - {name: "accounts-rpc", match: {path: "/example.accounts.v1.ProfileService/GetProfile"}, metadata: {filter_metadata: {"example.gateway": {action: ""}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "accounts-rpc", propagate: false}, typed_per_filter_config: {envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "accounts_grpc", host_rewrite_literal: "127.0.0.1:7070", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem"}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/GetCart"}, metadata: {filter_metadata: {"example.gateway": {action: "browse"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - name: "accounts-webhooks" + match: {path: "/api/webhooks", headers: [{name: ":method", string_match: {exact: "POST"}}]} + decorator: {operation: "accounts-webhooks", propagate: false} + route: {cluster: "accounts_http", host_rewrite_literal: "127.0.0.1:7070", prefix_rewrite: "/hooks/payments", timeout: 0s, idle_timeout: 90s} + typed_per_filter_config: + envoy.filters.http.jwt_authn: + "@type": type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.PerRouteConfig + disabled: true + envoy.filters.http.ext_authz: + "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute + disabled: true + - name: "catalog" + match: {prefix: "/catalog/"} + metadata: {filter_metadata: {"example.gateway": {action: ""}, "example.gateway.rate_limit": {client: "catalog"}}} + decorator: {operation: "catalog", propagate: false} + route: {cluster: "catalog_http", timeout: 0s, idle_timeout: 90s} + - name: "shop" + match: {prefix: "/"} + metadata: {filter_metadata: {"example.gateway": {action: ""}}} + decorator: {operation: "shop", propagate: false} + route: {cluster: "shop_http", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}} + transport_socket: + name: envoy.transport_sockets.tls + typed_config: + "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.DownstreamTlsContext + common_tls_context: + alpn_protocols: [h2, http/1.1] + tls_certificates: [{certificate_chain: {filename: "/etc/gateway/tls/certificate.pem"}, private_key: {filename: "/etc/gateway/tls/key.pem"}}] + validation_context: {trusted_ca: {filename: "/etc/gateway/tls/clients-ca.pem"}} + require_client_certificate: true + clusters: + - name: "shop_http" + type: STATIC + lb_policy: LEAST_REQUEST + load_assignment: + cluster_name: "shop_http" + endpoints: [{lb_endpoints: [{endpoint: {address: {socket_address: {address: "10.0.1.11", port_value: 8080}}}}, {endpoint: {address: {socket_address: {address: "10.0.1.12", port_value: 8080}}}}]}] + health_checks: + - timeout: 1s + interval: 10s + no_traffic_interval: 10s + healthy_threshold: 2 + unhealthy_threshold: 3 + http_health_check: {path: "/healthz", expected_statuses: [{start: 200, end: 300}], retriable_statuses: [{start: 100, end: 600}]} + common_lb_config: {healthy_panic_threshold: {value: 0}} + circuit_breakers: {thresholds: [{max_connections: 4096, max_pending_requests: 4096, max_requests: 4096}]} + typed_extension_protocol_options: + envoy.extensions.upstreams.http.v3.HttpProtocolOptions: + "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions + common_http_protocol_options: {idle_timeout: 45s} + explicit_http_config: {http_protocol_options: {}} + - name: "shop_grpc" + type: STATIC + lb_policy: LEAST_REQUEST + load_assignment: + cluster_name: "shop_grpc" + endpoints: [{lb_endpoints: [{endpoint: {address: {socket_address: {address: "10.0.1.11", port_value: 8081}}}}, {endpoint: {address: {socket_address: {address: "10.0.1.12", port_value: 8081}}}}]}] + health_checks: + - timeout: 1s + interval: 10s + no_traffic_interval: 10s + healthy_threshold: 2 + unhealthy_threshold: 3 + grpc_health_check: {} + common_lb_config: {healthy_panic_threshold: {value: 0}} + circuit_breakers: {thresholds: [{max_connections: 4096, max_pending_requests: 4096, max_requests: 4096}]} + typed_extension_protocol_options: + envoy.extensions.upstreams.http.v3.HttpProtocolOptions: + "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions + common_http_protocol_options: {idle_timeout: 45s} + explicit_http_config: {http2_protocol_options: {}} + - name: "accounts_grpc" + type: STATIC + load_assignment: + cluster_name: "accounts_grpc" + endpoints: [{lb_endpoints: [{endpoint: {address: {socket_address: {address: "127.0.0.1", port_value: 7070}}}}]}] + circuit_breakers: {thresholds: [{max_connections: 4096, max_pending_requests: 4096, max_requests: 4096}]} + typed_extension_protocol_options: + envoy.extensions.upstreams.http.v3.HttpProtocolOptions: + "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions + common_http_protocol_options: {idle_timeout: 45s} + explicit_http_config: {http2_protocol_options: {}} + - name: "accounts_http" + type: STATIC + load_assignment: + cluster_name: "accounts_http" + endpoints: [{lb_endpoints: [{endpoint: {address: {socket_address: {address: "127.0.0.1", port_value: 7070}}}}]}] + circuit_breakers: {thresholds: [{max_connections: 4096, max_pending_requests: 4096, max_requests: 4096}]} + typed_extension_protocol_options: + envoy.extensions.upstreams.http.v3.HttpProtocolOptions: + "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions + common_http_protocol_options: {idle_timeout: 45s} + explicit_http_config: {http_protocol_options: {}} + - name: "catalog_http" + cluster_type: + name: envoy.cluster.dns + typed_config: + "@type": type.googleapis.com/envoy.extensions.clusters.dns.v3.DnsCluster + dns_lookup_family: ALL + typed_dns_resolver_config: + name: envoy.network.dns_resolver.cares + typed_config: + "@type": type.googleapis.com/envoy.extensions.network.dns_resolver.cares.v3.CaresDnsResolverConfig + resolvers: [{socket_address: {address: "10.0.0.2", port_value: 53}}] + lb_policy: RING_HASH + load_assignment: + cluster_name: "catalog_http" + endpoints: [{lb_endpoints: [{endpoint: {address: {socket_address: {address: "catalog.internal.example", port_value: 8090}}}}]}] + circuit_breakers: {thresholds: [{max_connections: 4096, max_pending_requests: 4096, max_requests: 4096}]} + typed_extension_protocol_options: + envoy.extensions.upstreams.http.v3.HttpProtocolOptions: + "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions + hash_policy: [{header: {header_name: "x-session-id"}}] + common_http_protocol_options: {idle_timeout: 45s} + explicit_http_config: {http_protocol_options: {}} + - name: "otel_collector" + type: STATIC + load_assignment: + cluster_name: "otel_collector" + endpoints: [{lb_endpoints: [{endpoint: {address: {socket_address: {address: "10.0.3.40", port_value: 4317}}}}]}] + typed_extension_protocol_options: + envoy.extensions.upstreams.http.v3.HttpProtocolOptions: + "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions + explicit_http_config: {http2_protocol_options: {}} + - name: "jwks" + cluster_type: + name: envoy.cluster.dns + typed_config: + "@type": type.googleapis.com/envoy.extensions.clusters.dns.v3.DnsCluster + dns_lookup_family: ALL + typed_dns_resolver_config: + name: envoy.network.dns_resolver.cares + typed_config: + "@type": type.googleapis.com/envoy.extensions.network.dns_resolver.cares.v3.CaresDnsResolverConfig + resolvers: [{socket_address: {address: "10.0.0.2", port_value: 53}}] + load_assignment: + cluster_name: "jwks" + endpoints: [{lb_endpoints: [{endpoint: {address: {socket_address: {address: "login.example.com", port_value: 443}}}}]}] + transport_socket: + name: envoy.transport_sockets.tls + typed_config: + "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext + sni: "login.example.com" + common_tls_context: + validation_context: + trusted_ca: {filename: "/etc/gateway/jwt/ca.pem"} + match_typed_subject_alt_names: [{san_type: DNS, matcher: {exact: "login.example.com"}}] + typed_extension_protocol_options: + envoy.extensions.upstreams.http.v3.HttpProtocolOptions: + "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions + explicit_http_config: {http_protocol_options: {}} diff --git a/internal/render/testdata/full-before-max-request-bytes.yaml b/internal/render/testdata/full-before-max-request-bytes.yaml new file mode 100644 index 0000000..0f240c6 --- /dev/null +++ b/internal/render/testdata/full-before-max-request-bytes.yaml @@ -0,0 +1,95 @@ +# yaml-language-server: $schema=../../../schema/proxyfile.schema.json +# examples/full/yaml/proxyfile.yaml as it was at v2.3.1, before rpc.methods[].max_request_bytes, kept here because the +# example itself takes the key: the file every key but a few writes, none of its methods limiting its request. +# full-before-max-request-bytes.envoy.yaml is the Envoy file v2.3.1 wrote for it. +listen: 10000 +admin: 9901 +tls: + certificate: /etc/gateway/tls/certificate.pem + key: /etc/gateway/tls/key.pem + clients: {ca: /etc/gateway/tls/clients-ca.pem} +client_address: connection +limits: + connections: 4096 + request_headers: {size: 96KiB, count: 150} +timeouts: + request: none + idle: 90s + upstream_idle: 45s +services: + shop: + http: 8080 + grpc: 8081 + addresses: ["10.0.1.11", "10.0.1.12"] + balance: least_requests + health: {path: /healthz, grpc: true, interval: 10s, timeout: 1s, healthy: 2, unhealthy: 3} + accounts: {grpc: 7070, http: 7070, host_header: "127.0.0.1:7070"} + catalog: {http: 8090, address: catalog.internal.example, balance: hash, hash: {header: x-session-id}} +dns: {resolver: "10.0.0.2:53"} +auth: + ask: accounts /auth/check + timeout: 1500ms + enabled: true + when_unavailable: allow + only_with_header: authorization + send: [authorization, x-country] + accept: [x-user-*, x-tier-*] + send_request: true + jwt: + issuer: https://login.example.com + audiences: [api.example.com, admin.example.com] + keys: https://login.example.com/.well-known/jwks.json + ca: /etc/gateway/jwt/ca.pem + header: x-access-token + optional: true + claims: {x-subject: sub, x-roles: realm.roles} +remove_from_clients: [x-user-*, x-client-*, x-tier-*, x-gateway-*] +cors: + allow_methods: "*" + allow_headers: "*" + expose_headers: "Content-Disposition,X-Request-Id" + max_age: "600" +origins: + live: + hosts: [api.example.com, api.example.org] + origins: ["https://example.com", "https://www.example.com"] + patterns: ["https://*.example.com"] + test: + hosts: [api.test.example.com] + origins: ["http://localhost:3000", "https://test.example.com"] + patterns: ["https://*.test.example.com"] + local: + hosts: [127.0.0.1, localhost] + origins: [] + patterns: ["http://*.example.com:*", "http://localhost:*"] +routes: + - {name: accounts-events, pattern: "^/events/[a-z0-9-]+$", to: accounts, auth: off} + - rpc: + retries: 1 + rate_limit: {requests: 100, per: 1s, by: all} + to: + example.shop.*: {service: shop, name: shop} + "*": accounts + - {name: accounts-webhooks, path: /api/webhooks, method: POST, to: accounts, rewrite: /hooks/payments, auth: off} + - {name: catalog, prefix: /catalog/, to: catalog, rate_limit: {requests: 20, per: 1s, burst: 10, by: client}} + - {name: shop, prefix: /, to: shop, retries: 1} +rpc: + methods: + - {service: example.shop.v1.CartService, method: GetCart, action: browse} + - {service: example.accounts.v1.ProfileService, method: GetProfile} + - {service: example.shop.v1.CartService, method: AddItem, action: buy, reports: [browse]} +log: {status_from: 400, sample: 1%} +tracing: + provider: + otel: + endpoint: 10.0.3.40:4317 + service: example-gateway + sample: {rate: 10%} + tags: + environment: {env: APP_ENVIRONMENT, default: local} + request_id: {header: x-request-id} + path_in_url: true +envoy: + namespace: example.gateway + heap: 256MiB + connect_bridge: true diff --git a/internal/render/testdata/full.expected.yaml b/internal/render/testdata/full.expected.yaml index 03cdfb0..c0a2f65 100644 --- a/internal/render/testdata/full.expected.yaml +++ b/internal/render/testdata/full.expected.yaml @@ -306,6 +306,11 @@ static_resources: response_handle:headers():replace(":status", status) end end + - name: envoy.filters.http.buffer + disabled: true + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.buffer.v3.Buffer + max_request_bytes: 2053 - name: envoy.filters.http.connect_grpc_bridge disabled: true typed_config: @@ -364,7 +369,12 @@ static_resources: "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute disabled: true - {name: "accounts-rpc", match: {path: "/example.accounts.v1.ProfileService/GetProfile"}, metadata: {filter_metadata: {"example.gateway": {action: ""}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "accounts-rpc", propagate: false}, typed_per_filter_config: {envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "accounts_grpc", host_rewrite_literal: "127.0.0.1:7070", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem"}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: ":method", string_match: {exact: "GET"}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 405}, response_headers_to_add: [{header: {key: "allow", value: "POST"}}]} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: ":path", string_match: {contains: "?"}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 400}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "grpc-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "content-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "connect-content-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem"}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.buffer: {"@type": type.googleapis.com/envoy.extensions.filters.http.buffer.v3.BufferPerRoute, buffer: {max_request_bytes: 2053}}, envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - {name: "shop", match: {path: "/example.shop.v1.CartService/GetCart"}, metadata: {filter_metadata: {"example.gateway": {action: "browse"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - name: "accounts-webhooks" match: {path: "/api/webhooks", headers: [{name: ":method", string_match: {exact: "POST"}}]} @@ -431,7 +441,12 @@ static_resources: "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute disabled: true - {name: "accounts-rpc", match: {path: "/example.accounts.v1.ProfileService/GetProfile"}, metadata: {filter_metadata: {"example.gateway": {action: ""}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "accounts-rpc", propagate: false}, typed_per_filter_config: {envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "accounts_grpc", host_rewrite_literal: "127.0.0.1:7070", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem"}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: ":method", string_match: {exact: "GET"}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 405}, response_headers_to_add: [{header: {key: "allow", value: "POST"}}]} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: ":path", string_match: {contains: "?"}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 400}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "grpc-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "content-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "connect-content-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem"}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.buffer: {"@type": type.googleapis.com/envoy.extensions.filters.http.buffer.v3.BufferPerRoute, buffer: {max_request_bytes: 2053}}, envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - {name: "shop", match: {path: "/example.shop.v1.CartService/GetCart"}, metadata: {filter_metadata: {"example.gateway": {action: "browse"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - name: "accounts-webhooks" match: {path: "/api/webhooks", headers: [{name: ":method", string_match: {exact: "POST"}}]} @@ -497,7 +512,12 @@ static_resources: "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute disabled: true - {name: "accounts-rpc", match: {path: "/example.accounts.v1.ProfileService/GetProfile"}, metadata: {filter_metadata: {"example.gateway": {action: ""}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "accounts-rpc", propagate: false}, typed_per_filter_config: {envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "accounts_grpc", host_rewrite_literal: "127.0.0.1:7070", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem"}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: ":method", string_match: {exact: "GET"}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 405}, response_headers_to_add: [{header: {key: "allow", value: "POST"}}]} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: ":path", string_match: {contains: "?"}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 400}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "grpc-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "content-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem", headers: [{name: "connect-content-encoding", string_match: {safe_regex: {regex: "^(?s:.{0,7}|.{9,}|[^i].{7}|i[^d].{6}|id[^e].{5}|ide[^n].{4}|iden[^t].{3}|ident[^i].{2}|identi[^t].|identit[^y])$"}}}]}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}}, direct_response: {status: 415}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem"}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.buffer: {"@type": type.googleapis.com/envoy.extensions.filters.http.buffer.v3.BufferPerRoute, buffer: {max_request_bytes: 2053}}, envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - {name: "shop", match: {path: "/example.shop.v1.CartService/GetCart"}, metadata: {filter_metadata: {"example.gateway": {action: "browse"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} - name: "accounts-webhooks" match: {path: "/api/webhooks", headers: [{name: ":method", string_match: {exact: "POST"}}]} diff --git a/internal/render/testdata/route-before-rpc-entry.envoy.yaml b/internal/render/testdata/route-before-rpc-entry.envoy.yaml new file mode 100644 index 0000000..01bb82c --- /dev/null +++ b/internal/render/testdata/route-before-rpc-entry.envoy.yaml @@ -0,0 +1,170 @@ +# Generated by proxyfile. Do not edit: change the proxyfile beside it and run proxyfile render; proxyfile check fails on a hand edit. +static_resources: + listeners: + - name: public + address: {socket_address: {address: 0.0.0.0, port_value: 8000}} + filter_chains: + - filters: + - name: envoy.filters.network.http_connection_manager + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager + stat_prefix: public + use_remote_address: false + always_set_request_id_in_response: true + server_header_transformation: PASS_THROUGH + normalize_path: true + merge_slashes: true + path_with_escaped_slashes_action: UNESCAPE_AND_FORWARD + upgrade_configs: [{upgrade_type: websocket}] + local_reply_config: + mappers: + - filter: {response_flag_filter: {flags: [UF, UH, UC, URX]}} + status_code: 502 + body: {inline_string: ""} + - filter: + and_filter: + filters: + - status_code_filter: + comparison: {op: EQ, value: {default_value: 403, runtime_key: gateway.local_reply.origin_refused_status}} + - header_filter: + header: {name: origin, present_match: true} + body: {inline_string: "Invalid CORS request"} + access_log: + - name: envoy.access_loggers.stdout + typed_config: + "@type": type.googleapis.com/envoy.extensions.access_loggers.stream.v3.StdoutAccessLog + log_format: + json_format: + time: "%START_TIME%" + route: "%ROUTE_NAME%" + host: "%REQ(:AUTHORITY)%" + method: "%REQ(:METHOD)%" + protocol: "%PROTOCOL%" + status: "%RESPONSE_CODE%" + flags: "%RESPONSE_FLAGS%" + details: "%RESPONSE_CODE_DETAILS%" + duration_ms: "%DURATION%" + upstream_ms: "%RESPONSE_DURATION%" + bytes_in: "%BYTES_RECEIVED%" + bytes_out: "%BYTES_SENT%" + upstream: "%UPSTREAM_CLUSTER%" + request_id: "%REQ(X-REQUEST-ID)%" + - name: envoy.access_loggers.stdout + filter: + response_flag_filter: {flags: [UH, UF, UO, UC, UT, URX, UPE]} + typed_config: + "@type": type.googleapis.com/envoy.extensions.access_loggers.stream.v3.StdoutAccessLog + log_format: + json_format: + event: gateway_upstream_failure + route: "%ROUTE_NAME%" + status: "%RESPONSE_CODE%" + flags: "%RESPONSE_FLAGS%" + upstream: "%UPSTREAM_CLUSTER%" + http_filters: + - name: envoy.filters.http.header_mutation + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutation + mutations: + response_mutations: + - append: + header: {key: vary, value: Origin} + append_action: APPEND_IF_EXISTS_OR_ADD + - name: envoy.filters.http.rbac + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.rbac.v3.RBAC + - name: envoy.filters.http.cors + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.cors.v3.Cors + - name: envoy.filters.http.lua + disabled: true + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua + default_source_code: + inline_string: | + -- Connect's status today for each code whose status the bridge writes from the old table. + local CONNECT_STATUS = { + canceled = "499", + deadline_exceeded = "504", + failed_precondition = "400", + unimplemented = "501", + } + local OLD_STATUS = {["404"] = true, ["408"] = true, ["412"] = true} + + function envoy_on_response(response_handle) + local headers = response_handle:headers() + if not OLD_STATUS[headers:get(":status")] or headers:get("content-type") ~= "application/json" then + return + end + local body = response_handle:body() + if body == nil then + return + end + -- The bridge writes the error with protobuf's JSON printer: its keys come in no fixed order + -- (message before code, as measured), and a quote inside a string is always escaped, so the + -- only "code":"..." pair in the body is the error's own. + local code = body:getBytes(0, body:length()):match('"code"%s*:%s*"([%l_]+)"') + local status = CONNECT_STATUS[code] + if status ~= nil then + -- Asked for again: the header object from before body() died while the body was awaited. + response_handle:headers():replace(":status", status) + end + end + - name: envoy.filters.http.connect_grpc_bridge + disabled: true + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.connect_grpc_bridge.v3.FilterConfig + - name: envoy.filters.http.router + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router + suppress_envoy_headers: true + route_config: + name: public + ignore_port_in_host_matching: true + virtual_hosts: + - name: "all" + domains: ["localhost"] + typed_per_filter_config: + envoy.filters.http.rbac: + "@type": type.googleapis.com/envoy.extensions.filters.http.rbac.v3.RBACPerRoute + rbac: + rules: + action: ALLOW + policies: + browser-origins: + permissions: [{any: true}] + principals: + - {not_id: {header: {name: origin, present_match: true}}} + - {header: {name: origin, string_match: {safe_regex: {regex: "^https?://localhost(:[0-9]+)?$"}}}} + envoy.filters.http.cors: + "@type": type.googleapis.com/envoy.extensions.filters.http.cors.v3.CorsPolicy + allow_origin_string_match: [] + forward_not_matching_preflights: false + routes: + - name: "refused:dot-segment-with-parameter" + match: {safe_regex: {regex: ".*/\\.\\.?(?:;|%3[Bb]).*"}} + direct_response: {status: 400} + - name: "cart" + match: {prefix: "/shop.v1.CartService/"} + route: {cluster: "cart_http"} + - {name: "cart-rpc", match: {path: "/shop.v1.CartService/AddItem"}, typed_per_filter_config: {envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "cart_grpc"}} + - {name: "cart-rpc", match: {path: "/shop.v1.CartService/GetCart"}, typed_per_filter_config: {envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "cart_grpc"}} + clusters: + - name: "cart_http" + type: STATIC + load_assignment: + cluster_name: "cart_http" + endpoints: [{lb_endpoints: [{endpoint: {address: {socket_address: {address: "127.0.0.1", port_value: 5000}}}}]}] + typed_extension_protocol_options: + envoy.extensions.upstreams.http.v3.HttpProtocolOptions: + "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions + explicit_http_config: {http_protocol_options: {}} + - name: "cart_grpc" + type: STATIC + load_assignment: + cluster_name: "cart_grpc" + endpoints: [{lb_endpoints: [{endpoint: {address: {socket_address: {address: "127.0.0.1", port_value: 5001}}}}]}] + typed_extension_protocol_options: + envoy.extensions.upstreams.http.v3.HttpProtocolOptions: + "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions + explicit_http_config: {http2_protocol_options: {}} diff --git a/internal/render/testdata/route-before-rpc-entry.yaml b/internal/render/testdata/route-before-rpc-entry.yaml new file mode 100644 index 0000000..9150e21 --- /dev/null +++ b/internal/render/testdata/route-before-rpc-entry.yaml @@ -0,0 +1,14 @@ +# A route before the rpc entry that takes every path of shop.v1.CartService, and methods that write no +# max_request_bytes: such a file is not refused, and renders as it did before a route there was checked. +listen: 8000 +services: + cart: {http: 5000, grpc: 5001} +origins: + all: {hosts: [localhost]} +routes: + - {name: cart, prefix: /shop.v1.CartService/, to: cart} + - rpc: {to: {"shop.v1.*": cart}} +rpc: + methods: + - {service: shop.v1.CartService, method: AddItem, action: use} + - {service: shop.v1.CartService, method: GetCart} diff --git a/internal/rpc/rpc.go b/internal/rpc/rpc.go index a062f5a..08d87b6 100644 --- a/internal/rpc/rpc.go +++ b/internal/rpc/rpc.go @@ -4,7 +4,9 @@ package rpc import ( "fmt" + "regexp" "slices" + "strconv" "strings" "github.com/kitecorp/proxyfile/v2/internal/format" @@ -18,6 +20,7 @@ import ( type Method struct { Service, Method, Action string // Action is "" when not written Reports []string // nil when not written, and when written as [] + MaxRequestBytes uint32 // 0 when not written: the method has no request limit Pos model.Pos // the entry's mapping } @@ -61,12 +64,26 @@ func MethodsOf(list *tree.Node) []Method { Method: item.Get("method").Text, Action: item.GetText("action"), Reports: texts(item.Get("reports")), - Pos: item.Pos, + // The check admitted a whole number from 1 to model.LargestRequestLimit, which fits a uint32, so the + // error is never set; a key that was not written is 0. + MaxRequestBytes: requestLimit(item.Get("max_request_bytes")), + Pos: item.Pos, }) } return methods } +// requestLimit reads a method's max_request_bytes the format check accepted, 0 for a key that was not written. It is a +// copy of number in internal/read/decode.go, narrowed to the uint32 a limit fits in, because this package cannot +// import that one: internal/read imports rpc to read rpc.methods. +func requestLimit(n *tree.Node) uint32 { + if n == nil { + return 0 + } + limit, _ := strconv.ParseUint(n.Text, 10, 32) + return uint32(limit) +} + // texts is nil for a list that was not written and for an empty one, so a reader sees no difference between the two. func texts(list *tree.Node) []string { if list == nil { @@ -84,7 +101,8 @@ func texts(list *tree.Node) []string { // different patterns that both match a service never have the same length, so the written order never matters. // // g is a gateway read.Proxyfile returned, whose rules have made every target name a declared service with a gRPC -// port. Resolve returns either the routes, sorted by path, or every problem it finds, sorted. +// port. Resolve returns either the routes, sorted by path, or every problem it finds, sorted; a route written before +// the rpc entry is checked against the routes once they are found (limitsTaken). func Resolve(g *model.Gateway, methods []Method) ([]Route, []model.Problem) { var problems model.Problems entry := g.RPCEntry() @@ -126,9 +144,48 @@ func Resolve(g *model.Gateway, methods []Method) ([]Route, []model.Problem) { } // No two routes share a path, because a method listed twice is refused above. slices.SortFunc(routes, func(a, b Route) int { return strings.Compare(a.Path(), b.Path()) }) + if problems := limitsTaken(g, entry, routes); problems != nil { + return nil, problems + } return routes, nil } +// limitsTaken refuses each route written before the rpc entry that takes the path of a method with a request limit. +// The limit is held by the method's own route alone, and a proxy tries the routes in the order written and uses the +// first that matches (Envoy 1.40.2, route_components.proto, VirtualHost.routes), so such a route would serve every call +// to the method with no limit. A route's other conditions, its method among them, are not read: a call can meet them. +// Each route is named once, with the first such method by path. +func limitsTaken(g *model.Gateway, entry *model.Route, routes []Route) []model.Problem { + var problems model.Problems + for i := range g.Routes { + route := &g.Routes[i] + if route == entry { + break + } + j := slices.IndexFunc(routes, func(r Route) bool { return r.MaxRequestBytes > 0 && takes(route, r.Path()) }) + if j >= 0 { + problems.Add(route.Pos, "route %q is written before the rpc entry and takes the path of %s/%s, so that "+ + "method's max_request_bytes would not apply; write the route after the rpc entry", + route.Name.Value, routes[j].Service, routes[j].Method.Method) + } + } + return problems.Sorted() +} + +// takes reports whether route matches path as Envoy matches it (route_components.proto, RouteMatch): a prefix the path +// starts with, a path equal to it, or a pattern that matches the whole path. read's rules refused a pattern that does +// not compile. +func takes(route *model.Route, path string) bool { + switch route.Match { + case model.Prefix: + return strings.HasPrefix(path, route.Value.Value) + case model.Path: + return path == route.Value.Value + default: + return regexp.MustCompile(`^(?:` + route.Value.Value + `)$`).MatchString(path) + } +} + // targetOf tries the targets in the written order and keeps the best that matches service, or returns nil. func targetOf(targets []model.RPCTarget, service string) *model.RPCTarget { var best *model.RPCTarget @@ -164,7 +221,8 @@ func better(a, b string) bool { // Table writes the routes, in the order given, as a JSON array with one object per line, so a diff of two tables // shows one line for each route that changed. Resolve sorts the routes by path, so the table's order does not depend -// on the order the methods are written in. +// on the order the methods are written in. max_request_bytes is written, between reports and cluster, only for a +// method with a limit, so a table whose methods set none holds the bytes it held before the key. // // Each string is written by quote.JSON, whose result equals what Jackson's writeValueAsString writes for any text // with no control character and no U+2028 or U+2029: Go escapes those two always and writes \u00XX in lower case, @@ -179,17 +237,22 @@ func Table(routes []Route) []byte { for j, report := range route.Reports { reports[j] = quote.JSON(report) } - lines[i] = fmt.Sprintf(` {"service": %s, "method": %s, "action": %s, "reports": [%s], "cluster": %s}`, + var limit string + if route.MaxRequestBytes > 0 { + limit = fmt.Sprintf(`, "max_request_bytes": %d`, route.MaxRequestBytes) + } + lines[i] = fmt.Sprintf(` {"service": %s, "method": %s, "action": %s, "reports": [%s]%s, "cluster": %s}`, quote.JSON(route.Service), quote.JSON(route.Method.Method), quote.JSON(route.Action), - strings.Join(reports, ", "), quote.JSON(route.Cluster)) + strings.Join(reports, ", "), limit, quote.JSON(route.Cluster)) } return []byte("[\n" + strings.Join(lines, ",\n") + "\n]\n") } // Tree is methods as the tree a methods file of the same methods reads as: a list of maps, one per method, with -// service and method, action only when not "", and reports only when not nil, every key and value at the method's -// position. Methods read from .proto options are in no file of the format, and format.Refusals reads a tree, so -// render.Read refuses through it the keys its target refuses among them. +// service and method, action only when not "", reports only when not nil, and max_request_bytes only when not 0, +// every key and value at the method's position. Methods read from .proto options are in no file of the format, and +// format.Refusals reads a tree, so render.Read refuses through it the keys its target refuses among them: a target +// that cannot carry a request limit refuses one read from a .proto option, as it refuses one in a methods file. func Tree(methods []Method) *tree.Node { list := &tree.Node{Kind: tree.List} for _, m := range methods { @@ -210,6 +273,9 @@ func Tree(methods []Method) *tree.Node { } add("reports", reports) } + if m.MaxRequestBytes > 0 { + add("max_request_bytes", &tree.Node{Kind: tree.Scalar, Text: strconv.FormatUint(uint64(m.MaxRequestBytes), 10)}) + } list.Items = append(list.Items, item) } return list diff --git a/internal/rpc/rpc_test.go b/internal/rpc/rpc_test.go index 7f4b672..559f58c 100644 --- a/internal/rpc/rpc_test.go +++ b/internal/rpc/rpc_test.go @@ -170,8 +170,12 @@ func TestResolve(t *testing.T) { {name: "methods file keys", example: "../../examples/full/yaml/proxyfile.yaml", methods: `[{"service": "a.B", "methd": "M"}]`, want: []string{ `m.json:1:2: "method" is required here`, - `m.json:1:21: unknown key "methd"; known here: action, method, reports, service`, + `m.json:1:21: unknown key "methd"; known here: action, max_request_bytes, method, reports, service`, }}, + // A method's request limit is at least one byte; one left out is no limit, so 0 has no meaning of its own. + {name: "a request limit of 0", example: "../../examples/full/yaml/proxyfile.yaml", + methods: `[{"service": "a.B", "method": "M", "max_request_bytes": 0}]`, + want: []string{`m.json:1:57: "max_request_bytes" must be a whole number from 1 to 4294967290`}}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { @@ -277,6 +281,55 @@ func TestTable(t *testing.T) { } } +// cart sends the package shop.v1 to the service cart, whose gRPC cluster is cart_grpc. +var cart = testsupport.Document{ + "listen: 8000", + "services:", + " cart: {grpc: 5001}", + "origins: origins.json", + "routes:", + " - rpc:", + " to:", + " shop.v1.*: cart", +} + +// A method's max_request_bytes reaches the RPC table between reports and cluster, and only on a method that writes it, +// so a table whose methods write none holds the bytes it held before the key. The methods are read from a methods +// file, so the limit in the table is the one ReadMethods read. +func TestTableWritesTheLimitOnlyWhereAMethodHasOne(t *testing.T) { + dir := t.TempDir() + proxyfile := filepath.Join(dir, "g.yaml") + testsupport.WriteFile(t, proxyfile, cart.String()) + file, problems := read.Proxyfile(proxyfile) + if problems != nil { + t.Fatalf("read.Proxyfile problems = %q, want none", testsupport.ProblemStringsIn(dir, problems)) + } + methodsFile := filepath.Join(dir, "m.json") + testsupport.WriteFile(t, methodsFile, testsupport.Document{ + `[`, + ` {"service": "shop.v1.CartService", "method": "AddItem", "action": "use", "max_request_bytes": 2048},`, + ` {"service": "shop.v1.CartService", "method": "GetCart"}`, + `]`, + }.String()) + methods, _, problems := rpc.ReadMethods(methodsFile) + if problems != nil { + t.Fatalf("ReadMethods problems = %q, want none", testsupport.ProblemStringsIn(dir, problems)) + } + routes, problems := rpc.Resolve(file.Gateway, methods) + if problems != nil { + t.Fatalf("Resolve problems = %q, want none", testsupport.ProblemStringsIn(dir, problems)) + } + want := testsupport.Document{ + `[`, + ` {"service": "shop.v1.CartService", "method": "AddItem", "action": "use", "reports": [], "max_request_bytes": 2048, "cluster": "cart_grpc"},`, + ` {"service": "shop.v1.CartService", "method": "GetCart", "action": "", "reports": [], "cluster": "cart_grpc"}`, + `]`, + }.String() + if got := string(rpc.Table(routes)); got != want { + t.Errorf("Table() = %q, want %q", got, want) + } +} + // A method read from a .proto option writes action and reports only when it sets them, as a methods file does when it // leaves them out, and every key sits at the method's position. func TestTree(t *testing.T) { diff --git a/schema/proxyfile.schema.json b/schema/proxyfile.schema.json index e58a2d9..6f8c385 100644 --- a/schema/proxyfile.schema.json +++ b/schema/proxyfile.schema.json @@ -764,6 +764,12 @@ "description": "The action the check is told for this method.", "type": "string" }, + "max_request_bytes": { + "description": "The largest request message, in bytes as serialized, the gateway passes to this method.", + "maximum": 4294967290, + "minimum": 1, + "type": "integer" + }, "method": { "description": "The method's name.", "pattern": "^[A-Za-z_][A-Za-z0-9_]*$",