diff --git a/README.md b/README.md index bcc6547..b39762f 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.4.0/proxyfile-linux-amd64 -curl -fsSLO https://github.com/kitecorp/proxyfile/releases/download/v2.4.0/checksums.txt +curl -fsSLO https://github.com/kitecorp/proxyfile/releases/download/v2.5.0/proxyfile-linux-amd64 +curl -fsSLO https://github.com/kitecorp/proxyfile/releases/download/v2.5.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.4.0 /proxyfile /usr/local/bin/proxyfile +COPY --from=ghcr.io/kitecorp/proxyfile:2.5.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.4.0 +go install github.com/kitecorp/proxyfile/v2/cmd/proxyfile@v2.5.0 ``` ## Commands diff --git a/conformance/battery_test.go b/conformance/battery_test.go index 143219a..98aa392 100644 --- a/conformance/battery_test.go +++ b/conformance/battery_test.go @@ -133,7 +133,8 @@ func runFile(t *testing.T, tg target, f file, config string, lock func(*testing. if err != nil { t.Fatal(err) } - w := startWorld(t, tg, mounted, !slices.Contains(written, "tls"), bytes.Contains(source, []byte(holdAddress)), f.collector) + w := startWorld(t, tg, mounted, !slices.Contains(written, "tls"), bytes.Contains(source, []byte(holdAddress)), f.collector, + bytes.Contains(source, []byte(keysURL))) keys := fileKeys{label: f.label, keys: written, scenarios: f.scenarios, mainRows: tg.mainRows} limited := slices.Contains(written, "routes[].rate_limit") // In order and never in parallel, but for the rows that overlap: a scenario's quiet and burst count on nothing else diff --git a/conformance/certificates_test.go b/conformance/certificates_test.go index 68e87b4..d991d3f 100644 --- a/conformance/certificates_test.go +++ b/conformance/certificates_test.go @@ -19,17 +19,19 @@ import ( // paths the full example's tls keys and auth.jwt.ca name. client, otherCA and expired are the clients' certificates // with their keys, kept in memory because the proxy never reads them: client is signed by the clients CA, otherCA by // a second CA that carries the clients CA's name, so only a proxy that checks the signature refuses it, and expired by -// the clients CA with a validity that ended, so only a proxy that checks the dates refuses it. +// the clients CA with a validity that ended, so only a proxy that checks the dates refuses it. token is the run's +// token, whose keys jwt/jwks.json holds (signedToken). type tlsFiles struct { tls, jwt string client, otherCA, expired tls.Certificate + token string } // certificates makes throwaway TLS files for one run under dir: a self-signed server certificate for localhost and // 127.0.0.1 with its key, a clients CA, and a copy of the server certificate as the CA bundle auth.jwt.ca names. // Folders are 0755 and files 0644 whatever the umask, because the proxy runs as an unprivileged user in its image and // must read the mounted files; the keys are made for this run alone and removed with dir. It also makes the three -// client certificates, which stay in memory. +// client certificates, which stay in memory, and the run's token with its key set (signedToken). func certificates(t testing.TB, dir string) tlsFiles { files := tlsFiles{tls: filepath.Join(dir, "tls"), jwt: filepath.Join(dir, "jwt")} for _, folder := range []string{files.tls, files.jwt} { @@ -59,6 +61,7 @@ func certificates(t testing.TB, dir string) tlsFiles { files.expired = clientCertificate(t, caCertificate, caKey, time.Now().Add(-48*time.Hour), time.Now().Add(-24*time.Hour)) otherCertificate, otherKey, _ := clientsCA(t) files.otherCA = clientCertificate(t, otherCertificate, otherKey) + files.token = signedToken(t, files.jwt) for path, data := range map[string][]byte{ filepath.Join(files.tls, "certificate.pem"): serverPEM, filepath.Join(files.tls, "key.pem"): keyPEM(t, serverKey), diff --git a/conformance/client_test.go b/conformance/client_test.go index af84dc1..f5ec64c 100644 --- a/conformance/client_test.go +++ b/conformance/client_test.go @@ -28,6 +28,7 @@ type echo struct { Headers, HeaderBytes map[string]string Body string Trailers map[string]string + BodyBytes int64 // shop's gRPC stub's count of the body bytes it read, when asked } // result is what came back for one request. @@ -134,8 +135,9 @@ func clientTLS(t testing.TB, files tlsFiles, certificate *tls.Certificate) *tls. } // send sends r to the proxy's listener and reads the whole answer, trailers included: by hand when r is raw (sendRaw), -// and otherwise through the client for its protocol. +// and otherwise through the client for its protocol. A header value that holds withToken carries the run's token there. func (w *world) send(r request) result { + r = w.tokened(r) if r.raw { if r.noCertificate || r.otherCA || r.expired || r.forgedMark || r.proto == "grpc" { panic(fmt.Sprintf("the battery sends a raw request with the client certificate and no forged mark over http/1.1 or h2, not %+v", r)) diff --git a/conformance/scenario_test.go b/conformance/scenario_test.go index 48944ef..9b755d1 100644 --- a/conformance/scenario_test.go +++ b/conformance/scenario_test.go @@ -203,6 +203,9 @@ type answer struct { // proxy makes anew on an answer no stub wrote, such as the request id of its own 404. made map[string]*regexp.Regexp body string // the body the stub received; "" is not compared + // bodyBytes, on a gRPC call sent with x-stub-count-body, is how many bytes of body shop's gRPC stub must have read, + // its frames whole; 0 is not compared. + bodyBytes int64 // ownBody is the body of an answer the proxy wrote itself, such as its refusal of a browser origin; "" is not // compared. A stub's echo is never that body, so a row that wants one also fails when a stub answered. ownBody string @@ -232,9 +235,9 @@ type answer struct { // expression matches: the request log line of a target whose line is its own and no JSON object, which logged // cannot read (sendRepeated reads it, as it reads counted). lineAfter *regexp.Regexp - // asked, on a row sent in sequence, is how many questions the stub's origin check, the check - // conformance/testdata/unlisted-origins.yaml's ask_unlisted names, must receive while the row's requests are sent - // and answered (sendRepeated reads it); nil is not compared. The answer cannot show it for an origin RBAC admits + // asked, on a row sent in sequence, is how many questions the stub's origin check, the check the ask_unlisted of + // conformance/testdata/unlisted-origins.yaml and request-limit.yaml names, must receive while the row's requests are + // sent and answered (sendRepeated reads it); nil is not compared. The answer cannot show it for an origin RBAC admits // whether or not the check was asked. asked *int // receivedForms holds headers the stub must have received with a value the regular expression matches, which the @@ -379,6 +382,9 @@ func compare(want answer, got result, mark string) []string { if want.body != "" && e.Body != want.body { differ("received body: got %q, want %q", e.Body, want.body) } + if want.bodyBytes != 0 && e.BodyBytes != want.bodyBytes { + differ("received body bytes: got %d, want %d", e.BodyBytes, want.bodyBytes) + } if want.noTrailers && len(e.Trailers) != 0 { differ("received trailers: got %q, want none", e.Trailers) } diff --git a/conformance/scenarios_test.go b/conformance/scenarios_test.go index c460dcd..3fadf73 100644 --- a/conformance/scenarios_test.go +++ b/conformance/scenarios_test.go @@ -17,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, requestLimit, paths, asWritten, offRoute, clientKeys, hash, tracing, tracingRetried, rateLimit, cost, backendLimits, traffic} +var scenarios = []scenario{routing, mutualTLS, cors, unlisted, auth, toldScheme, timeout, retry, gRPC, requestLimit, routeLimit, 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 { @@ -2448,6 +2448,33 @@ var gRPC = scenario{name: "gRPC", // 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. +// +// The rows after those send a request a filter of the proxy holds while it waits for an answer before it passes the +// request on: the auth check, on request-limit.yaml and examples/full, asked of a request with an authorization header; +// the check of an origin no list holds, on request-limit.yaml; and the token filter while it fetches its keys, on +// conformance/testdata/request-limit-keys.yaml, the same limit with auth.jwt and its keys at a URL. Each of the stub's +// answers comes 200 ms after it is asked (stub/check.go, stub/keys.go), well under the time the proxy waits for it. A +// request within the limit is served whole, and a gRPC frame one byte over and one of 64 KiB are answered grpc-status 2 +// before the check or the token filter is asked, and reach no service. While one of the three filters holds a Connect +// call the bridge converts, the call is counted without the 5-byte prefix, as a call the bridge leaves as it is: the +// rows named for the documented bound show, for each filter, that a body of the limit and 5 bytes reaches the service +// whole and one of the limit and 6 bytes is answered 413 and reaches no service. The origin check's count of its +// questions (answer.asked) shows that an origin it admits is not put to it when the call is past that bound, and a +// preflight from the origin request-limit.yaml lists, which carries no body, is answered with the origin allowed both +// on the limited method and on GetCart, which writes no limit, and is never put to the check. In request-limit.yaml the +// buffer filter comes before the CORS filter, so a 413 to the listed origin carries no access-control-allow-origin; the +// scenario of a route's request limit shows the other order. +// +// The token filter holds a call only while it fetches its keys, and Envoy 1.40.2's token filter keeps the keys it +// fetched for each worker thread, so the rows on request-limit-keys.yaml rely on their order on the proxy the battery +// starts for the file. The first row with a token is over the limit and is refused before the token filter reads it, so +// the next row, the call of the limit and 5 bytes, is the first call the token filter reads, on whichever worker takes +// it, and that worker holds it while it fetches the keys. A later call may reach a worker that holds the keys or one +// that does not, so the row for a call after the keys are held sends its two calls on one connection, which one worker +// reads: the first, within the limit, is verified with the keys, and the second, one byte over, is counted with the +// prefix and answered 413. On examples/full, whose token filter reads its token from x-access-token with keys at a host +// the battery's world does not serve, the token in authorization is read by no filter but the auth check, which denies +// it. 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), @@ -2456,7 +2483,7 @@ var requestLimit = scenario{name: "a method's request limit", 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), + send: grpcOverHTTP1(2049, nil), 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}}, @@ -2494,12 +2521,204 @@ var requestLimit = scenario{name: "a method's request limit", 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)}}, + send: unframedCall(2053, nil), 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), + send: unframedCall(2054, 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 one byte over the limit, whose check answers after 200 ms, is answered grpc-status 2 and reaches no service", + keys: checkedLimitKeys, send: grpcOverHTTP1(2049, slowCheck), want: overLimitGRPC}, + {name: "a gRPC call over HTTP/1.1 with a message of 64 KiB, whose check answers after 200 ms, is answered grpc-status 2 and reaches no service", + keys: checkedLimitKeys, send: grpcOverHTTP1(64<<10, slowCheck), want: overLimitGRPC}, + {name: "the documented bound while the auth check holds a call: a Connect call the bridge converts whose body is the limit and 5 bytes is served", + keys: checkedLimitKeys, send: connectCall(2053, joined(slowCheck, countBody)), want: convertedServed}, + {name: "the documented bound while the auth check holds a call: a Connect call the bridge converts whose body is the limit and 6 bytes is answered 413 in plain text and reaches no service", + keys: checkedLimitKeys, send: connectCall(2054, slowCheck), want: overLimitConnect}, + {name: "a Connect body without connect-protocol-version of the limit, whose check answers after 200 ms, is served whole", + keys: checkedLimitKeys, send: unframedCall(2048, slowCheck), + want: answer{status: 200, service: "shop", path: limitedPath, body: strings.Repeat("x", 2048)}}, + {name: "a gRPC call over HTTP/1.1 one byte over the limit, from an origin the origin check admits after 200 ms, is answered grpc-status 2, reaches no service and is not put to the check", + keys: slowOriginKeys, send: grpcOverHTTP1(2049, fromSlowOrigin), + want: answer{status: 200, grpcStatus: "2", headers: map[string]string{"grpc-message": "Payload Too Large"}, asked: new(0)}}, + {name: "a Connect body without connect-protocol-version of the limit, from an origin the origin check admits after 200 ms, is served whole", + keys: slowOriginKeys, send: unframedCall(2048, fromSlowOrigin), + want: answer{status: 200, service: "shop", path: limitedPath, body: strings.Repeat("x", 2048), asked: new(1)}}, + {name: "the documented bound while the origin check holds a call: a Connect call the bridge converts whose body is the limit and 5 bytes is served", + keys: slowOriginKeys, send: connectCall(2053, joined(fromSlowOrigin, countBody)), want: withAsked(convertedServed, 1)}, + {name: "the documented bound while the origin check holds a call: a Connect call the bridge converts whose body is the limit and 6 bytes is answered 413 in plain text, reaches no service and is not put to the check", + keys: slowOriginKeys, send: connectCall(2054, fromSlowOrigin), want: withAsked(overLimitConnect, 0)}, + {name: "a preflight of a call to the limited method from a listed origin is answered 200 with the origin allowed", + keys: listedOriginLimitKeys, send: limitPreflight(limitedPath), + want: answer{status: 200, headers: map[string]string{"access-control-allow-origin": limitListedOrigin}, asked: new(0)}}, + {name: "a preflight of a call to a method without a limit from a listed origin is answered 200 with the origin allowed", + keys: listedOriginLimitKeys, send: limitPreflight("/example.shop.v1.CartService/GetCart"), + want: answer{status: 200, headers: map[string]string{"access-control-allow-origin": limitListedOrigin}, asked: new(0)}}, + {name: "a Connect call 6 bytes over the limit from a listed origin is answered 413 without access-control-allow-origin, as the buffer filter comes before the CORS filter in a file with ask_unlisted", + keys: listedOriginLimitKeys, send: connectCall(2054, fromListedOrigin), + want: answer{status: 413, headers: map[string]string{"content-type": "text/plain", "access-control-allow-origin": ""}, + ownBody: "Payload Too Large", asked: new(0)}}, + {name: "a gRPC call over HTTP/1.1 one byte over the limit, with a token, before the token filter has fetched its keys, is answered grpc-status 2 and reaches no service", + keys: tokenLimitKeys, send: grpcOverHTTP1(2049, bearerToken), want: overLimitGRPC}, + {name: "the documented bound while the token filter fetches its keys: a Connect call the bridge converts whose body is the limit and 5 bytes, the first call the token filter reads, is served", + keys: tokenLimitKeys, send: connectCall(2053, joined(bearerToken, countBody)), want: convertedServed, + on: map[string]literal{"full": {want: answer{status: 401, ownBody: "denied by the check"}}}}, + {name: "the documented bound while the token filter fetches its keys: a Connect call the bridge converts whose body is the limit and 6 bytes is answered 413 in plain text and reaches no service", + keys: tokenLimitKeys, send: connectCall(2054, bearerToken), want: overLimitConnect}, + {name: "a Connect body without connect-protocol-version of the limit, with a token the fetched keys verify, is served whole", + keys: tokenLimitKeys, send: unframedCall(2048, bearerToken), + want: answer{status: 200, service: "shop", path: limitedPath, body: strings.Repeat("x", 2048)}, + on: map[string]literal{"full": {want: answer{status: 401, ownBody: "denied by the check"}}}}, + {name: "once the token filter holds its keys, a Connect call the bridge converts whose body is one byte over the limit, sent on the connection of a call the keys verified, is answered 413 in plain text", + keys: tokenLimitKeys, send: convertedTwice(2048, 2049, bearerToken), want: withFirst(overLimitConnect, 200), + on: map[string]literal{"full": {want: answer{status: 401, first: 401, ownBody: "denied by the check"}}}}, }} +// overLimitGRPC is the answer to a gRPC call over HTTP/1.1 whose message is over its method's limit, as the proxy writes +// it and no stub, and overLimitConnect the answer to a Connect call whose body is. +var ( + overLimitGRPC = answer{status: 200, grpcStatus: "2", headers: map[string]string{"grpc-message": "Payload Too Large"}} + overLimitConnect = answer{status: 413, headers: map[string]string{"content-type": "text/plain"}, ownBody: "Payload Too Large"} + // convertedServed is the answer to a Connect call the bridge converts, of the limit and 5 bytes, sent with + // countBody: shop receives it whole, the 5-byte prefix the bridge writes and the 2,053 bytes of the body. + convertedServed = answer{status: 200, service: "shop", port: "8081", proto: "HTTP/2.0", path: limitedPath, bodyBytes: 2058} +) + +// countBody is the header that asks shop's gRPC stub to count the bytes of body it read in its echo (stub/grpc.go). +var countBody = map[string]string{"x-stub-count-body": "1"} + +// joined is the headers of each of parts in one map, a later part's value of a name in place of an earlier one's. +func joined(parts ...map[string]string) map[string]string { + headers := map[string]string{} + for _, part := range parts { + maps.Copy(headers, part) + } + return headers +} + +// withAsked is a with the origin check's count of questions asked set to n. +func withAsked(a answer, n int) answer { + a.asked = &n + return a +} + +// withFirst is a with the status of the first of two requests on one connection set to status (request.then). +func withFirst(a answer, status int) answer { + a.first = status + return a +} + +// convertedTwice is two Connect unary calls to limitedPath the bridge converts, written by hand on one HTTP/1.1 +// connection, so one worker of the proxy reads both: the first with a body of first bytes, the second, written right +// after it (request.then), with a body of second bytes, each framed by its length and with the headers in more. +func convertedTwice(first, second int, more map[string]string) request { + headers := map[string]string{"content-type": "application/proto", "connect-protocol-version": "1"} + maps.Copy(headers, more) + var then strings.Builder + then.WriteString("POST " + limitedPath + " HTTP/1.1\r\nHost: localhost\r\n") + for _, name := range slices.Sorted(maps.Keys(headers)) { + then.WriteString(name + ": " + headers[name] + "\r\n") + } + fmt.Fprintf(&then, "content-length: %d\r\n\r\n%s", second, strings.Repeat("x", second)) + headers["content-length"] = strconv.Itoa(first) + return request{proto: "http/1.1", method: "POST", host: "localhost", path: limitedPath, headers: headers, raw: true, + unframed: true, body: strings.Repeat("x", first), then: then.String()} +} + +// The keys the rows of a method's request limit with a filter that waits depend on: the limit and the auth check; +// the limit and the check of an origin no list holds; the limit, that check, which a preflight from a listed origin is +// never put to, and the list; and the limit and the token filter's keys at a URL. +var ( + checkedLimitKeys = slices.Concat(requestLimitKeys, []string{"auth.ask"}) + slowOriginKeys = slices.Concat(requestLimitKeys, unlistedKeys) + listedOriginLimitKeys = slices.Concat(requestLimitKeys, unlistedKeys, []string{"origins..origins"}) + tokenLimitKeys = slices.Concat(requestLimitKeys, []string{"auth.jwt.keys"}) +) + +// slowCheck is the header that has the stub's auth check answer 200 after 200 ms, fromSlowOrigin the Origin the stub's +// origin check admits after 200 ms (stub/check.go), and bearerToken the authorization header that carries the run's +// token (withToken). +var ( + slowCheck = map[string]string{"authorization": "Bearer allow-after-200ms"} + fromSlowOrigin = map[string]string{"origin": "https://slow.acme.example"} + bearerToken = map[string]string{"authorization": "Bearer " + withToken} +) + +// fromListedOrigin is the Origin header of limitListedOrigin. +var fromListedOrigin = map[string]string{"origin": limitListedOrigin} + +// limitListedOrigin is the origin the local environments of request-limit.yaml and route-limit.yaml list. +// examples/full's local environment does not list it, and its pattern http://*.example.com:* covers it. +const limitListedOrigin = "http://shop.example.com:8080" + +// limitPreflight is a browser's preflight of a POST to path on localhost from limitListedOrigin. +func limitPreflight(path string) request { + return request{proto: "http/1.1", method: "OPTIONS", host: "localhost", path: path, + headers: map[string]string{"origin": limitListedOrigin, "access-control-request-method": "POST"}} +} + +// routeLimit: a route's request limit, routes[].max_request_bytes, on conformance/testdata/route-limit.yaml and on +// examples/full, each of which limits its route accounts-webhooks, a POST to /api/webhooks that accounts receives at +// /hooks/payments, to 2,048 bytes. The limit counts the body as the proxy receives it: a body of exactly the limit +// reaches the service whole, and one byte more, framed by its length or chunked, is answered 413 in plain text with the +// body Payload Too Large and reaches no service; a body sent with content-encoding: gzip is counted as sent and reaches +// the service as sent, with its header, as the proxy decodes no body and refuses no form of one on a plain route. The +// first rows were written before the Envoy output wrote the key, so their literals are the answers Envoy 1.40.2 gave a +// method's route, whose 413 the same buffer filter and the same local reply write (a method's request limit), and a +// plain route's echo of a body. Only Envoy's entry runs the scenario, as the nginx and HAProxy generators refuse the +// key. +// +// route-limit.yaml asks the auth check of a request with an authorization header and writes no auth: off on its route, +// so the rows that carry a token show that the limit leaves the route's check on: a body within the limit the check +// denies is answered 403, one it allows is served whole, and a body over the limit with a token the check denies is +// answered 413, not 403, as the buffer filter comes before the check. On examples/full, whose accounts-webhooks writes +// auth: off, the check is not asked, and the denied token is served. Neither file writes ask_unlisted, so the CORS +// filter comes before the buffer filter, and a 413 to an origin the file admits carries access-control-allow-origin: +// route-limit.yaml lists http://shop.example.com:8080, and examples/full's local environment admits it by its pattern +// http://*.example.com:*. +var routeLimit = scenario{name: "a route's request limit", + exchanges: []exchange{ + {name: "a body of exactly the limit reaches the service whole", keys: routeLimitKeys, send: toWebhooks(2048, nil), + want: answer{status: 200, service: "accounts", path: "/hooks/payments", body: strings.Repeat("x", 2048)}}, + {name: "a body one byte over the limit is answered 413 in plain text and reaches no service", keys: routeLimitKeys, + send: toWebhooks(2049, nil), want: overLimitConnect}, + {name: "a chunked body one byte over the limit is answered 413 in plain text and reaches no service", keys: routeLimitKeys, + send: request{proto: "http/1.1", method: "POST", host: "localhost", path: "/api/webhooks", raw: true, body: strings.Repeat("x", 2049)}, + want: overLimitConnect}, + {name: "a body sent with content-encoding gzip, of the limit as sent, reaches the service as sent", keys: routeLimitKeys, + send: toWebhooks(2048, map[string]string{"content-encoding": "gzip"}), + want: answer{status: 200, service: "accounts", path: "/hooks/payments", body: strings.Repeat("x", 2048), + received: map[string]string{"content-encoding": "gzip"}}}, + {name: "a body within the limit that the route's auth check denies is answered 403: the limit leaves the check on", + keys: checkedRouteLimitKeys, send: toWebhooks(2048, map[string]string{"authorization": "Bearer deny-403"}), + want: answer{status: 403, service: ""}, + on: map[string]literal{"full": {want: answer{status: 200, service: "accounts", path: "/hooks/payments"}}}}, + {name: "a body of exactly the limit that the route's auth check allows reaches the service whole", keys: checkedRouteLimitKeys, + send: toWebhooks(2048, map[string]string{"authorization": "Bearer allow"}), + want: answer{status: 200, service: "accounts", path: "/hooks/payments", body: strings.Repeat("x", 2048)}}, + {name: "a body one byte over the limit, with a token the route's auth check denies, is answered 413, not the check's 403, and reaches no service", + keys: checkedRouteLimitKeys, send: toWebhooks(2049, map[string]string{"authorization": "Bearer deny-403"}), + want: overLimitConnect}, + {name: "a body one byte over the limit from a listed origin is answered 413 with the origin allowed, as the CORS filter comes before the buffer filter in a file without ask_unlisted", + keys: listedOriginRouteLimitKeys, send: toWebhooks(2049, fromListedOrigin), + want: answer{status: 413, headers: map[string]string{"content-type": "text/plain", "access-control-allow-origin": limitListedOrigin}, + ownBody: "Payload Too Large"}}, + }} + +// routeLimitKeys are what the rows of a route's request limit depend on: the limit the route writes; +// checkedRouteLimitKeys the limit and the auth check, which the route leaves on; and listedOriginRouteLimitKeys the +// limit and the list of origins that holds the origin a row sends. +var ( + routeLimitKeys = []string{"routes[].max_request_bytes"} + checkedRouteLimitKeys = slices.Concat(routeLimitKeys, []string{"auth.ask"}) + listedOriginRouteLimitKeys = slices.Concat(routeLimitKeys, []string{"origins..origins"}) +) + +// toWebhooks is a POST to /api/webhooks on localhost over HTTP/1.1, a body of size bytes framed by its length, with the +// headers in more. +func toWebhooks(size int, more map[string]string) request { + return request{proto: "http/1.1", method: "POST", host: "localhost", path: "/api/webhooks", headers: maps.Clone(more), + body: strings.Repeat("x", size)} +} + // 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 { @@ -2533,11 +2752,14 @@ func connectRaw(more map[string]string) request { 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)} +// unframedCall is a Connect unary call to limitedPath over HTTP/1.1 without Connect-Protocol-Version, with the headers +// in more: 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, and the stub's echo carries it whole. +func unframedCall(size int, more map[string]string) request { + headers := map[string]string{"content-type": "application/proto"} + maps.Copy(headers, more) + return request{proto: "http/1.1", method: "POST", host: "localhost", path: limitedPath, headers: headers, + body: strings.Repeat("x", size)} } // requestLimitKeys are what the rows of a method's request limit depend on: the limit the method writes. @@ -2558,10 +2780,12 @@ func connectCall(size int, more map[string]string) request { } // 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))} +// 5-byte prefix, framed by its length, with the headers in more. +func grpcOverHTTP1(size int, 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, + 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 diff --git a/conformance/stub/backend.go b/conformance/stub/backend.go index 79d87c6..02778b9 100644 --- a/conformance/stub/backend.go +++ b/conformance/stub/backend.go @@ -199,6 +199,10 @@ type echo struct { // Pad is as many bytes as the request's x-stub-pad asks for, so a scenario gets an answer of that size: HAProxy // reads the first part of an answer into one buffer, and the lines it adds to an answer must fit beside it. Pad string `json:"pad,omitempty"` + // BodyBytes is how many bytes of body a gRPC call that carries x-stub-count-body sent, its frames as read (grpc.go): + // the count and not the bytes, as a Connect call the bridge converts gets its answer through the same buffer limit + // as its request, and an echo of the bytes would be refused there. + BodyBytes int64 `json:"bodybytes,omitempty"` } func (b *backend) describe(r *http.Request, attempt int) echo { diff --git a/conformance/stub/check.go b/conformance/stub/check.go index cf44c64..c7ed4e3 100644 --- a/conformance/stub/check.go +++ b/conformance/stub/check.go @@ -102,6 +102,12 @@ func (b *backend) check(w http.ResponseWriter, r *http.Request) { case "hang": time.Sleep(b.hang) w.WriteHeader(http.StatusOK) + case "allow-after-200ms": + // An allowing answer that takes 200 ms, a fixed sleep well under the 1500 ms auth.timeout of request-limit.yaml + // and examples/full, so the proxy waits for it and lets the request through: the rows of a method's request + // limit show what a request within and over the limit gets while the proxy waits for a check. + time.Sleep(200 * time.Millisecond) + w.WriteHeader(http.StatusOK) default: w.WriteHeader(http.StatusUnauthorized) io.WriteString(w, "denied by the check") @@ -123,8 +129,17 @@ func (b *backend) check(w http.ResponseWriter, r *http.Request) { // Two origins stand for a check that fails, which must admit no origin either: https://down.example gets 503, and // https://late.example gets 200 only after hang, past the 1 s the gateway waits for this check. Each answer carries // x-origin-check too, so a row also fails when the proxy passes on a header of the failed check's. +// +// https://slow.acme.example is admitted as those three are, asked browser-origin with no authorization header, but +// after 200 ms, a fixed sleep well under that 1 s, so the proxy waits for the answer and admits the origin: the rows of +// a method's request limit on request-limit.yaml show what a request within and over the limit gets while the proxy +// waits for this check. func originCheck(w http.ResponseWriter, r *http.Request, hang time.Duration) { switch origin := r.Header.Get("origin"); { + case origin == "https://slow.acme.example" && r.Header.Get("x-gateway-question") == "browser-origin" && + r.Header.Values("authorization") == nil: + time.Sleep(200 * time.Millisecond) + w.WriteHeader(http.StatusOK) case origin == "https://down.example": w.Header().Set("content-type", "application/json") w.Header().Set("x-origin-check", "down") diff --git a/conformance/stub/grpc.go b/conformance/stub/grpc.go index 7a14ead..9d70620 100644 --- a/conformance/stub/grpc.go +++ b/conformance/stub/grpc.go @@ -12,8 +12,9 @@ import ( // grpc-status trailer. func (b *backend) grpc(w http.ResponseWriter, r *http.Request) { // The answer depends only on the path and the headers, but the call is read to its end before the answer - // begins, as a gRPC server reads it. - io.Copy(io.Discard, r.Body) + // begins, as a gRPC server reads it. A call that carries x-stub-count-body gets the number of bytes it sent in + // the echo (echo.BodyBytes), so a row shows that a call the Connect bridge converted reached the service whole. + sent, _ := io.Copy(io.Discard, r.Body) attempt, ok := b.firstTry(w, r) if !ok { return @@ -22,7 +23,11 @@ func (b *backend) grpc(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/grpc.health.v1.Health/Check" { message = []byte{0x08, 0x01} // HealthCheckResponse: field 1, status, is 1, SERVING. } else { - body, _ := json.Marshal(b.describe(r, attempt)) + e := b.describe(r, attempt) + if r.Header.Get("x-stub-count-body") != "" { + e.BodyBytes = sent + } + body, _ := json.Marshal(e) // Field 1 as a string: the tag 0x0a, the length as a varint, then the echo's JSON. message = append([]byte{0x0a}, binary.AppendUvarint(nil, uint64(len(body)))...) message = append(message, body...) diff --git a/conformance/stub/keys.go b/conformance/stub/keys.go new file mode 100644 index 0000000..0eae994 --- /dev/null +++ b/conformance/stub/keys.go @@ -0,0 +1,66 @@ +package main + +import ( + "crypto/tls" + "flag" + "fmt" + "net" + "net/http" + "os" + "time" +) + +// keysDelay is how long the keys server waits before it answers a fetch, a fixed sleep well under the 2 s the Envoy +// output gives the token filter's fetch of its keys (filter-jwt-authn.yaml), so the fetch succeeds: the rows of a +// method's request limit on request-limit-keys.yaml show what a request within and over the limit gets while the proxy +// waits for the keys. +const keysDelay = 200 * time.Millisecond + +// keys serves the signing keys of the battery's tokens, a JSON Web Key Set the battery writes for each run, over +// HTTPS at /jwks.json, for a file whose auth.jwt.keys is a URL (conformance/testdata/request-limit-keys.yaml). It runs +// in the proxy's network namespace, at the URL's 127.0.0.1, with the server certificate the battery makes, which names +// 127.0.0.1 and is the CA bundle auth.jwt.ca names. Every answer comes keysDelay after the request. It says it is +// listening only once its port is open, so the battery waits for that line before the rows that need the keys. +func keys(args []string) { + flags := flag.NewFlagSet("keys", flag.ExitOnError) + listen := flags.String("listen", "", "the TCP address to answer on") + certificate := flags.String("certificate", "", "the PEM file of the server certificate") + key := flags.String("key", "", "the PEM file of the certificate's key") + set := flags.String("set", "", "the JSON Web Key Set file to serve") + flags.Parse(args) + if *listen == "" || *certificate == "" || *key == "" || *set == "" || flags.NArg() > 0 { + usageError("keys needs -listen, -certificate, -key and -set, and nothing after them") + } + pair, err := tls.LoadX509KeyPair(*certificate, *key) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + listener, err := net.Listen("tcp", *listen) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + fmt.Fprintf(os.Stderr, "stub keys on %s\n", *listen) + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/jwks.json" { + http.NotFound(w, r) + return + } + if !wait(r, keysDelay) { + return + } + data, err := os.ReadFile(*set) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("content-type", "application/json") + w.Write(data) + }) + server := &http.Server{Handler: handler} + if err := server.Serve(tls.NewListener(listener, &tls.Config{Certificates: []tls.Certificate{pair}})); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} diff --git a/conformance/stub/main.go b/conformance/stub/main.go index 899ef36..b58697e 100644 --- a/conformance/stub/main.go +++ b/conformance/stub/main.go @@ -1,6 +1,6 @@ -// Stub plays every backend of examples/full, its auth check, its DNS resolver and its tracing collector for the -// conformance battery. It uses the standard library only, so the battery adds nothing to go.mod and nothing to the -// released program. +// Stub plays every backend of examples/full, its auth check, its DNS resolver and its tracing collector, and the keys +// server of the battery's tokens, for the conformance battery. It uses the standard library only, so the battery adds +// nothing to go.mod and nothing to the released program. package main import ( @@ -20,6 +20,7 @@ const usage = `usage: stub serve -service -instance -ports [,< stub hold -port stub dns -listen =... stub collector + stub keys -listen -certificate -key -set stub fetch ` func main() { @@ -35,6 +36,8 @@ func main() { dns(os.Args[2:]) case "collector": collector(os.Args[2:]) + case "keys": + keys(os.Args[2:]) case "fetch": fetch(os.Args[2:]) default: diff --git a/conformance/targets_test.go b/conformance/targets_test.go index 586d2c0..98d35a8 100644 --- a/conformance/targets_test.go +++ b/conformance/targets_test.go @@ -67,8 +67,14 @@ var ( // 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}} + // and HAProxy generators refuse the key; it runs the rows of that scenario alone. requestLimitKeysFile is the same + // limit with the token filter and its keys at a URL, and runs the same scenario alone. + requestLimitFile = file{label: "request-limit", proxyfile: "testdata/request-limit.yaml", scenarios: []string{requestLimit.name}} + requestLimitKeysFile = file{label: "request-limit-keys", proxyfile: "testdata/request-limit-keys.yaml", + scenarios: []string{requestLimit.name}} + // routeLimitFile is the battery's file with a route'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. + routeLimitFile = file{label: "route-limit", proxyfile: "testdata/route-limit.yaml", scenarios: []string{routeLimit.name}} ) // haproxyLimitsFile is the battery's file for HAProxy's connection limit, which Envoy's entry and each HAProxy entry @@ -119,6 +125,8 @@ func targets(t testing.TB) []target { connectionFile, unlistedFile, requestLimitFile, + requestLimitKeysFile, + routeLimitFile, }, 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-keys.yaml b/conformance/testdata/request-limit-keys.yaml new file mode 100644 index 0000000..9a2ea53 --- /dev/null +++ b/conformance/testdata/request-limit-keys.yaml @@ -0,0 +1,33 @@ +# yaml-language-server: $schema=../../schema/proxyfile.schema.json +# The conformance battery's file for a method's request limit with the token filter (auth.jwt) and its keys at a URL: +# request-limit.yaml's shop, routes and AddItem, limited to 2,048 bytes, with the Connect bridge on, and a token in the +# authorization header verified against the keys the stub's keys server serves at https://127.0.0.1:8443/jwks.json, in +# the proxy's own network namespace, with the battery's server certificate, which the CA bundle at +# /etc/gateway/jwt/ca.pem is. The keys server answers 200 ms after each fetch, and each worker of the proxy fetches the +# keys for the first request with a token it reads, so the rows show what a request within and over the limit gets while +# the proxy waits for the keys, and once it holds them. The battery signs a token for each run with iss +# https://login.example.com and aud api.example.com. optional lets a request with no token through, so every row that +# sends none is answered as on request-limit.yaml. 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"] +auth: + jwt: + issuer: https://login.example.com + audiences: [api.example.com] + keys: https://127.0.0.1:8443/jwks.json + ca: /etc/gateway/jwt/ca.pem + optional: true +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/conformance/testdata/request-limit.yaml b/conformance/testdata/request-limit.yaml index 0ae5916..0fdfa4e 100644 --- a/conformance/testdata/request-limit.yaml +++ b/conformance/testdata/request-limit.yaml @@ -1,20 +1,37 @@ # 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. +# 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; GetCart, which writes no limit, is routed beside it. The auth +# check asks accounts at /auth/check of a request with an authorization header, and the local environment, which admits +# http://shop.example.com:8080 by its list, puts any other origin to the stub's origin check at /auth/origin, so the +# rows show what a request within and over the limit gets while the proxy waits for either check: the stub's check +# answers the token allow-after-200ms and admits https://slow.acme.example, each after 200 ms. A row that sends neither +# an authorization header nor an Origin, as every row before the checks were added does, is answered as without them. 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"] + accounts: {http: 7070} +auth: + ask: accounts /auth/check + timeout: 1500ms + enabled: true + when_unavailable: deny + only_with_header: authorization origins: - local: {hosts: [127.0.0.1, localhost]} + local: + hosts: [127.0.0.1, localhost] + origins: ["http://shop.example.com:8080"] + ask_unlisted: accounts /auth/origin + question: browser-origin routes: - rpc: {to: {"example.shop.*": shop}} rpc: methods: + - {service: example.shop.v1.CartService, method: GetCart} - {service: example.shop.v1.CartService, method: AddItem, max_request_bytes: 2048} envoy: {connect_bridge: true} diff --git a/conformance/testdata/route-limit.yaml b/conformance/testdata/route-limit.yaml new file mode 100644 index 0000000..448e89d --- /dev/null +++ b/conformance/testdata/route-limit.yaml @@ -0,0 +1,25 @@ +# yaml-language-server: $schema=../../schema/proxyfile.schema.json +# The conformance battery's file for a route's request limit (routes[].max_request_bytes): examples/full's route +# accounts-webhooks, a POST to /api/webhooks sent to accounts at /hooks/payments, limited to 2,048 bytes, as +# examples/full limits it, but without auth: off, so the auth check, which asks accounts at /auth/check of a request with +# an authorization header, stays on for the route. The local environment lists the origin http://shop.example.com:8080. +# A row that sends neither an authorization header nor an Origin is answered as without them. The file writes no +# ask_unlisted, so its CORS filter comes before the buffer filter. It runs the scenario of a route'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: + accounts: {http: 7070} +auth: + ask: accounts /auth/check + timeout: 1500ms + enabled: true + when_unavailable: deny + only_with_header: authorization +origins: + local: + hosts: [127.0.0.1, localhost] + origins: ["http://shop.example.com:8080"] +routes: + - {name: accounts-webhooks, path: /api/webhooks, method: POST, to: accounts, rewrite: /hooks/payments, max_request_bytes: 2048} diff --git a/conformance/tokens_test.go b/conformance/tokens_test.go new file mode 100644 index 0000000..40d785d --- /dev/null +++ b/conformance/tokens_test.go @@ -0,0 +1,78 @@ +package conformance + +import ( + "crypto" + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "maps" + "math/big" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// The battery's tokens, for a file whose auth.jwt verifies them with keys at a URL +// (conformance/testdata/request-limit-keys.yaml): tokenIssuer and tokenAudience are the iss and aud that file accepts, +// and keysURL the URL it fetches the keys from, which the stub's keys server answers in the proxy's network namespace +// (stub keys) on keysPort. A row writes withToken in a header's value where the run's token goes. +const ( + tokenIssuer = "https://login.example.com" + tokenAudience = "api.example.com" + keysPort = "8443" + keysURL = "https://127.0.0.1:" + keysPort + "/jwks.json" + withToken = "{token}" +) + +// signedToken makes a signing key for one run, writes its public half as a JSON Web Key Set to jwks.json in dir, the +// folder mounted at /etc/gateway/jwt, which the keys server serves, and returns a token the key signs with RS256 for +// tokenIssuer and tokenAudience. The token expires a day after the run starts, so a clock in the container's virtual +// machine a little behind the host's still accepts it. The key is made for this run alone and removed with dir. +func signedToken(t testing.TB, dir string) string { + key := newKey(t) + encode := base64.RawURLEncoding.EncodeToString + set, err := json.Marshal(map[string]any{"keys": []map[string]string{{"kty": "RSA", "kid": "battery", "alg": "RS256", + "use": "sig", "n": encode(key.N.Bytes()), "e": encode(big.NewInt(int64(key.E)).Bytes())}}}) + if err != nil { + t.Fatal(err) + } + path := filepath.Join(dir, "jwks.json") + if err := os.WriteFile(path, set, 0o644); err != nil { + t.Fatal(err) + } + if err := os.Chmod(path, 0o644); err != nil { + t.Fatal(err) + } + claims, err := json.Marshal(map[string]any{"iss": tokenIssuer, "aud": tokenAudience, "sub": "battery", + "exp": time.Now().Add(24 * time.Hour).Unix()}) + if err != nil { + t.Fatal(err) + } + signed := encode([]byte(`{"alg":"RS256","kid":"battery","typ":"JWT"}`)) + "." + encode(claims) + sum := sha256.Sum256([]byte(signed)) + signature, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, sum[:]) + if err != nil { + t.Fatal(err) + } + return signed + "." + encode(signature) +} + +// tokened returns r with the world's token in place of withToken in each header value and in the second request a +// raw request writes on its connection (request.then), or r itself when none holds it. +func (w *world) tokened(r request) request { + r.then = strings.ReplaceAll(r.then, withToken, w.files.token) + for _, value := range r.headers { + if strings.Contains(value, withToken) { + r.headers = maps.Clone(r.headers) + for name, value := range r.headers { + r.headers[name] = strings.ReplaceAll(value, withToken, w.files.token) + } + return r + } + } + return r +} diff --git a/conformance/world_test.go b/conformance/world_test.go index 7b1029e..304c0e3 100644 --- a/conformance/world_test.go +++ b/conformance/world_test.go @@ -35,7 +35,7 @@ const ( // proxy while accounts still shares its network namespace succeeds, and accounts runs on until it is removed too. var containers = []string{accounts, proxy, "proxyfile-conformance-shop-1", "proxyfile-conformance-shop-2", "proxyfile-conformance-catalog", "proxyfile-conformance-check-1", "proxyfile-conformance-check-2", - "proxyfile-conformance-resolver", hold, hold2, collector} + "proxyfile-conformance-resolver", hold, hold2, collector, keysServer} // hold and hold2 are the backends that take no connection (stub hold), at holdAddress:8095 and hold2Address:8095, the // addresses nginx-plain's hold service and its held service name: a client's connect to either waits until the @@ -45,6 +45,12 @@ const ( hold2, hold2Address = "proxyfile-conformance-hold-2", "10.0.2.31" ) +// keysServer is the stub's keys server (stub keys), in the proxy's own network namespace as accounts is, at keysURL, +// which conformance/testdata/request-limit-keys.yaml fetches its keys from. The world starts it for a file that names +// keysURL, after the proxy, whose namespace it joins: the proxy fetches the keys only for a request that carries a +// token, never at its start. +const keysServer = "proxyfile-conformance-keys" + // collector is the stub's collector (stub collector) at collectorAddress, the address nginx-tracing.yaml and // examples/full send their spans to, on port 4317, and the address the world's resolver gives collectorName, the name // nginx-tracing-by-name.yaml sends them to. The world starts it for a file whose entry asks (file.collector), and the @@ -131,11 +137,12 @@ func claimWorld(t *testing.T) { // send to them and the start of each waits for its queue to fill; and, for a file whose entry asks (collects), the // stub's collector at collectorAddress, which examples/full and nginx-tracing.yaml send their spans to, started before // the proxy so its first spans have somewhere to go; for every other file that address is left unreachable, and no -// request waits for it. 10.0.0.0/22 is the smallest block holding every one of them. The ports 10000 and 9901 and the +// request waits for it; and, for a file that names keysURL (keyed), the stub's keys server, started after the proxy. +// 10.0.0.0/22 is the smallest block holding every one of them. The ports 10000 and 9901 and the // folders /config, /etc/gateway/tls and /etc/gateway/jwt are the examples' listen, admin and tls keys and // examples/full's auth.jwt.ca, the same for every target, and the proxy runs with proxyEnvironment. plain says the // rendered file's listener speaks plain HTTP, so the clients do too. -func startWorld(t *testing.T, tg target, config string, plain, held, collects bool) *world { +func startWorld(t *testing.T, tg target, config string, plain, held, collects, keyed bool) *world { buildStub(t, filepath.Join(runFolder, "stub")) files := certificates(t, runFolder) if _, err := docker("network", "create", "--subnet", "10.0.0.0/22", network); err != nil { @@ -169,8 +176,8 @@ func startWorld(t *testing.T, tg target, config string, plain, held, collects bo mustDocker(t, "run", "-d", "--name", name, "--network", network, "--ip", ip, "--sysctl", "net.core.somaxconn=1", image, "hold", "-port", "8095") } - waitHeld(t, hold) - waitHeld(t, hold2) + waitLogged(t, hold, "stub holds") + waitLogged(t, hold2, "stub holds") } if collects { mustDocker(t, "run", "-d", "--name", collector, "--network", network, "--ip", collectorAddress, image, "collector") @@ -186,6 +193,12 @@ func startWorld(t *testing.T, tg target, config string, plain, held, collects bo mustDocker(t, append(append(run, tg.image), tg.args...)...) mustDocker(t, "run", "-d", "--name", accounts, "--network", "container:"+proxy, "-v", state, image, "serve", "-service", "accounts", "-instance", "accounts", "-ports", "7070") + if keyed { + mustDocker(t, "run", "-d", "--name", keysServer, "--network", "container:"+proxy, "-v", files.tls+":/etc/gateway/tls:ro", + "-v", files.jwt+":/etc/gateway/jwt:ro", image, "keys", "-listen", ":"+keysPort, + "-certificate", "/etc/gateway/tls/certificate.pem", "-key", "/etc/gateway/tls/key.pem", "-set", "/etc/gateway/jwt/jwks.json") + waitLogged(t, keysServer, "stub keys on") + } waitReady(t, tg.ready) listener := strings.TrimSpace(mustDocker(t, "port", proxy, "10000/tcp")) w := &world{listener: listener, ports: ports, files: files, mark: tg.mark, plain: plain, collector: collects} @@ -243,17 +256,18 @@ func waitPorts(t testing.TB, container, ports string, open bool) { } } -// waitHeld waits until the hold backend name says its queue is full, every 100 ms for 10 s at most: until then a -// connection to it is taken, and a row that wants none would read the proxy's answer to a connection that never answers. -func waitHeld(t testing.TB, name string) { +// waitLogged waits until the container name logs text, every 100 ms for 10 s at most: a hold backend says so once its +// queue is full, until when a connection to it is taken, and a row that wants none would read the proxy's answer to a +// connection that never answers; the keys server once its port is open, until when the proxy's fetch of the keys fails. +func waitLogged(t testing.TB, name, text string) { deadline := time.Now().Add(10 * time.Second) for { logs, err := docker("logs", name) - if err == nil && strings.Contains(logs, "stub holds") { + if err == nil && strings.Contains(logs, text) { return } if time.Now().After(deadline) { - t.Fatalf("%s did not fill its queue within 10s; its log:\n%s", name, logs) + t.Fatalf("%s did not log %q within 10s; its log:\n%s", name, text, logs) } time.Sleep(100 * time.Millisecond) } diff --git a/docs/conformance.md b/docs/conformance.md index dc8df7d..50f6604 100644 --- a/docs/conformance.md +++ b/docs/conformance.md @@ -27,8 +27,10 @@ connection` and no `tls`, [`conformance/testdata/connection.yaml`](../conformanc 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, 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`. +limit, [`conformance/testdata/request-limit.yaml`](../conformance/testdata/request-limit.yaml) and, with the token +filter and its keys at a URL, [`conformance/testdata/request-limit-keys.yaml`](../conformance/testdata/request-limit-keys.yaml), +and, with a route's request limit, [`conformance/testdata/route-limit.yaml`](../conformance/testdata/route-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 @@ -115,9 +117,23 @@ an origin no list holds alone, and Envoy's entry alone runs it, as the nginx and `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. +to it with the Connect bridge on, and two methods, `example.shop.v1.CartService/AddItem`, limited to 2,048 bytes by +`max_request_bytes`, as `examples/full` limits it, and `GetCart`, which writes no limit. It also writes the auth check, +asked of a request with an `authorization` header under `deny`, and a `local` environment that admits +`http://shop.example.com:8080` by its list and puts any other origin to the stub's origin check with `ask_unlisted` and +the question `browser-origin`, so its rows show what a call within and over the limit gets while the proxy waits for +either check; a row that sends neither an `authorization` header nor an `Origin` is answered as on a file without them. +`request-limit-keys.yaml` writes the same service, routes and limit with the token filter, `auth.jwt`, whose keys are at +`https://127.0.0.1:8443/jwks.json`, the stub's keys server in the proxy's own network namespace, and `optional: true`, +so a row that sends no token is answered as on `request-limit.yaml`; each worker of the proxy fetches the keys for the +first request with a token it reads. `route-limit.yaml` writes `accounts` and one plain route, `examples/full`'s +`accounts-webhooks`, a `POST` to `/api/webhooks` that `accounts` receives at `/hooks/payments`, limited to 2,048 bytes +by `max_request_bytes`, as `examples/full` limits it, but without `auth: off`: the auth check, asked of a request with +an `authorization` header, stays on for the route. Its `local` environment lists `http://shop.example.com:8080`, and it +writes no `ask_unlisted`, so its CORS filter comes before the buffer filter. A row that sends neither an `authorization` +header nor an `Origin` is answered as on a file without them. Each of the three runs the rows of its scenario alone, a +method's request limit or a route's, and Envoy's entry alone runs them, 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 @@ -184,17 +200,18 @@ 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 634 rows on `full`, 524 on `portable`, 350 on `nginx-file`, 259 on `nginx-plain`, 381 on +in this order: in Envoy's entry 652 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`, 20 on `unlisted-origins` and 18 on `request-limit`; in each nginx entry on the +HAProxy's own, 11 on `connection`, 20 on `unlisted-origins`, 30 on `request-limit`, 23 on `request-limit-keys` and 8 on +`route-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,231 rows in Envoy's entry, 2,065 in each +`haproxy-traffic`, 1 on `haproxy-limits` and 11 on `connection`. That is 4,292 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,321 in all, and each passes. The battery counts these rows, and those each scenario's line in the table below +11,382 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 @@ -241,7 +258,17 @@ request from `http://files.acme.example`, which runs on `unlisted-origins`. Befo 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`. 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: +limit, whose 18 rows run on it and on `full`, which limits the same method. Before the buffer filter was listed +before the filters that wait for an answer, and before a plain route could write a request limit, they ran 4,231, +2,065, 615 and 865: ten rows were added in the scenario a method's request limit, of which four run on `request-limit` +and `full`, four on `request-limit` alone and two on `request-limit-keys` and `full`; `request-limit-keys.yaml` was +added, on which the scenario's 18 earlier rows run too; and `route-limit.yaml` was added with the scenario a route's +request limit, whose 4 rows run on it and on `full`, which limits the same route. Before the rows of a Connect call's +bound while a filter holds it, of a limited route's own check and of the CORS header of a `413` they ran 4,273, 2,065, +615 and 865: seven rows were added in the scenario a method's request limit, of which one runs on `request-limit` and +`full`, three on `request-limit` alone and three on `request-limit-keys` and `full`; and four in the scenario a +route's request limit, which run on `route-limit` and `full`, for which `route-limit.yaml` gained the auth check and +a listed origin. In order: | Scenario | Keys | What its rows check | |---|---|---| @@ -254,7 +281,8 @@ limit, whose 18 rows run on it and on `full`, which limits the same method. In o | 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`. | +| a method's request limit | `rpc.methods[].max_request_bytes`, `auth.ask`, `auth.jwt.keys`, `origins..ask_unlisted`, `origins..question`, `origins..origins` | 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`. The buffer filter is listed before the filters that wait for an answer, and the rows that make one wait show what a call within and over the limit gets meanwhile. With an `authorization` header the auth check answers after 200 ms, on `request-limit` and `full`: a gRPC call over HTTP/1.1 a byte over the limit and one whose message is 64 KiB are each answered `grpc-status` 2; a Connect call the bridge converts whose body is the limit and 5 bytes reaches `shop` whole, all 2,058 bytes of its frame as `x-stub-count-body` counts them, and one of the limit and 6 bytes is answered `413` with `Payload Too Large`; and a Connect call without `connect-protocol-version` whose body is the limit is served whole. From `https://slow.acme.example`, an origin the stub's origin check admits after 200 ms, on `request-limit`: a gRPC call a byte over is answered `grpc-status` 2 and the check is never asked; a converted Connect call of the limit and 5 bytes reaches `shop` whole after one question, and one of the limit and 6 bytes is answered `413` with no question; and a call whose body is the limit is served whole after one question. A preflight from the origin `request-limit` lists, to `AddItem` and to `GetCart`, which writes no limit, is answered `200` with that origin allowed, and the check is not asked; a Connect call 6 bytes over from that origin is answered `413` with no `access-control-allow-origin`, as the buffer filter comes before the CORS filter in a file with `ask_unlisted`. With a token in `authorization`, on `request-limit-keys`, where each worker of the proxy fetches the keys from the stub's keys server, which answers after 200 ms, for the first call with a token it reads: a gRPC call a byte over, refused before the token filter reads it, is answered `grpc-status` 2; the next call, a converted Connect call of the limit and 5 bytes, is the first the token filter reads, is held while it fetches the keys, and reaches `shop` whole; one of the limit and 6 bytes is answered `413`; a call whose body is the limit is served whole once the keys verify the token; and on one connection a converted Connect call of the limit is served and the call after it, a byte over, is answered `413`, as the keys the worker then holds verify its token at once. On `full`, whose token filter reads another header, the calls over the buffer filter's value, the limit and 5 bytes, get the same answers and the others the auth check's `401`. Each refused row wants an answer no stub wrote; the battery reads no list of the calls a stub received, so a row that reaches no service wants no service's echo. In Envoy's entry: 28 rows on `full`, 30 on `request-limit` and 23 on `request-limit-keys`. | +| a route's request limit | `routes[].max_request_bytes`, `auth.ask`, `origins..origins` | On `route-limit` and `full`, each of which limits its route `accounts-webhooks`, a `POST` to `/api/webhooks` that `accounts` receives at `/hooks/payments`, to 2,048 bytes, sent over HTTP/1.1: a body of exactly the limit, framed by its length, reaches `accounts` whole; a body a byte longer, framed by its length or chunked, is answered `413` with `content-type: text/plain` and the body `Payload Too Large`, and reaches no service; and a body of the limit as sent with `content-encoding: gzip` reaches `accounts` as sent, with that header, as the proxy decodes no body and refuses no form of one on a plain route. `route-limit.yaml` keeps the route's auth check on: a body within the limit with a token the check denies is answered `403`, one with a token it allows reaches `accounts` whole, and a body a byte over with a denied token is answered `413`, not `403`, as the buffer filter comes before the check; on `full`, whose route writes `auth: off`, the denied token is served. A body a byte over from `http://shop.example.com:8080`, which `route-limit.yaml` lists and `full`'s pattern covers, is answered `413` with that origin in `access-control-allow-origin`, as neither file writes `ask_unlisted` and the CORS filter comes first. In Envoy's entry: 8 rows on `full` and `route-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`. | @@ -304,25 +332,28 @@ The battery starts every address the files name on one Docker network, so each r | `proxyfile-conformance-hold` | `10.0.2.30` | `hold` on 8095, which only `conformance/testdata/nginx-plain.yaml` names, so it starts only in a world on a file that names its address: a listener that never accepts a connection. It runs with `net.core.somaxconn` at 1, and fills its queue with two connections of its own at start, so the kernel drops the opening packet of every later connection and a client's connect waits until its own time runs out. | | `proxyfile-conformance-hold-2` | `10.0.2.31` | A second listener that never accepts a connection, on 8095, started with the first and as it is: `conformance/testdata/nginx-plain.yaml`'s `held` service has both addresses, so a call its rpc entry retries meets one that takes no connection on each try. | | `proxyfile-conformance-resolver` | `10.0.0.2`, port 53 | The resolver: `catalog.internal.example` is `10.0.2.21`, `collector.internal.example` is `10.0.3.40`, and any other name is NXDOMAIN. | -| `proxyfile-conformance-accounts` | `127.0.0.1:7070` in the proxy's own network namespace | `accounts`, HTTP/1.1 and gRPC on one port, the auth check `auth.ask` names, and at `/auth/origin` the origin check `unlisted-origins.yaml`'s `ask_unlisted` names, which counts the questions it receives and answers the count at `/stub/origin-asks`. | +| `proxyfile-conformance-accounts` | `127.0.0.1:7070` in the proxy's own network namespace | `accounts`, HTTP/1.1 and gRPC on one port, the auth check `auth.ask` names, and at `/auth/origin` the origin check the `ask_unlisted` of `unlisted-origins.yaml` and `request-limit.yaml` names, which counts the questions it receives and answers the count at `/stub/origin-asks`. | | `proxyfile-conformance-check-1`, `proxyfile-conformance-check-2` | `10.0.3.31`, `10.0.3.32` | `checks`, the check service of `conformance/testdata/two-checks.yaml` and `conformance/testdata/nginx-checks.yaml`, and the first of `conformance/testdata/connection.yaml`: the stub's `accounts` on 7070 at each address, so a row can make one of the two refuse connections. | | `proxyfile-conformance-collector` | `10.0.3.40`, port 4317 | The tracing collector `nginx-tracing.yaml` sends its spans to, and `nginx-tracing-by-name.yaml` by the name `collector.internal.example`, as OTLP over gRPC, started only in those files' worlds, before the proxy. `examples/full` names the same address, which its world leaves unreachable: no request waits for it. | +| `proxyfile-conformance-keys` | `127.0.0.1:8443` in the proxy's own network namespace | The keys server `request-limit-keys.yaml`'s `auth.jwt.keys` names: over HTTPS, with the run's server certificate, which the CA bundle at `/etc/gateway/jwt/ca.pem` is, it serves the run's key set at `/jwks.json`, each answer 200 ms after the request. It is started only in the world of a file that names its URL, after the proxy, and the battery waits until it says its port is open. | The network is `proxyfile-conformance` on `10.0.0.0/22`, the smallest block that holds every one of these addresses. Each file a run renders gets a world of its own: the battery removes the first file's before it starts the second's. One stub program, [`conformance/stub`](../conformance/stub), plays every backend, the auth check, the resolver, the -backend that takes no connection and the tracing collector. The collector keeps each span a proxy exports to it and +backend that takes no connection, the tracing collector and the keys server. The collector keeps each span a proxy exports to it and answers them all, with their ids, name, status and attributes and the type of each attribute's value, `twice` for a key a span carries twice, which fails the row that reads that span, on port 8080 inside its container, where the battery reads them; a row finds its span by the `x-request-id` its request carried. A backend answers each request with what it received: its service name, port, protocol, method, path, host and headers, so a row can say which service answered and what reached it. The check decides by the value of the `authorization` header (`Bearer allow`, `Bearer deny-401`, `Bearer deny-403`, `Bearer status-503` or -`Bearer hang`), so each row chooses the check's answer, and a row that asks the check sends `x-api-key` too, so +`Bearer hang`, or `Bearer allow-after-200ms`, which allows after 200 ms, under the 1500 ms `auth.timeout` of +`request-limit.yaml` and `examples/full`), so each row chooses the check's answer, and a row that asks the check sends `x-api-key` too, so `two-checks.yaml` and `nginx-checks.yaml` ask it; any other token, or none, is denied with `401`, so a row that wants the check not to be asked fails when the proxy asks it. The origin check at `/auth/origin` answers `200` to the origins -`https://files.acme.example`, `http://files.acme.example` and `https://api.example.com:8443` asked the question `browser-origin` alone, with no `authorization` header; `503` with a +`https://files.acme.example`, `http://files.acme.example` and `https://api.example.com:8443` asked the question `browser-origin` alone, with no `authorization` header, and to +`https://slow.acme.example` asked the same way only after 200 ms, under the 1 s the gateway waits; `503` with a JSON body and `x-origin-check: down` to `https://down.example`; `200` with `x-origin-check: late` to `https://late.example` only after the stub's hang of 3 s, past the 1 s the gateway waits; and `401` with a JSON body and an `x-origin-check` header to any other origin or question, or to a request that carries `authorization`, so a row @@ -352,7 +383,9 @@ row reads back that it was allowed. A backend answers with `X-Accel-Redirect` set to the value of the request's `x-stub-accel-redirect`, on HTTP and gRPC, so a row can check that the proxy passes the header on instead of following it, and with `Keep-Alive` set to the value of `x-stub-keep-alive`, so a row can check that the proxy removes it, and with as many bytes more as -`x-stub-pad` asks for, so a row gets an answer of 100 KB. A request the stub cannot read gets +`x-stub-pad` asks for, so a row gets an answer of 100 KB. `shop`'s gRPC backend adds to its echo how many bytes of +body it read when a call carries `x-stub-count-body`, the count and not the bytes, as a Connect call the bridge +converts gets its answer through the same buffer limit as its request. A request the stub cannot read gets the stub's own answer, the plain-text status line of Go's `net/http`, and no description of the request: a row that wants that answer says `unreadable`, and a row that wants no service fails on it. A backend holds its answer for the time `x-stub-delay` names, such as `3s`, and with `x-stub-trickle: x