From a68d941e0d0feaf3e23940ab70fe8c167db7b50f Mon Sep 17 00:00:00 2001 From: Tudor Pop Date: Wed, 2 Dec 2026 00:21:34 +0200 Subject: [PATCH] feat(origins): an origin the file does not list can be put to the check, for customers' own domains (Part of #75) An environment's origins file can name ask_unlisted, a service whose check is asked about a browser origin no list holds, with an optional question header. Envoy renders the question for such an origin only, never for one a list or a pattern covers, and never sends the check the client's authorization; a check that answers 503 or too late admits no origin, and every refused origin gets the body Invalid CORS request. nginx and HAProxy refuse the key, and a conformance scenario covers it. --- conformance/client_test.go | 4 +- conformance/raw_test.go | 1 + conformance/scenario_test.go | 10 +- conformance/scenarios_test.go | 116 +++- conformance/stub/backend.go | 2 + conformance/stub/check.go | 34 + conformance/stub/main.go | 6 +- conformance/targets_test.go | 5 + conformance/testdata/unlisted-origins.yaml | 38 + docs/auth.md | 13 + docs/conformance.md | 50 +- docs/defaults.md | 15 +- docs/format.md | 22 +- docs/origins.md | 74 +- docs/portability.md | 3 + docs/routes.md | 3 + examples/full/hocon/Proxyfile | 5 +- examples/full/yaml/proxyfile.yaml | 2 +- internal/envoy/fragments/filter-cors.yaml | 15 +- internal/envoy/fragments/filter-rbac.yaml | 7 +- .../fragments/filter-unlisted-origin.yaml | 39 ++ .../fragments/route-unlisted-origin.yaml | 45 ++ internal/envoy/fragments/virtual-host.yaml | 3 +- internal/envoy/generate.go | 171 ++++- internal/format/check_test.go | 2 +- internal/format/spec.go | 32 +- internal/format/support_haproxy.go | 6 + internal/format/support_nginx.go | 6 + internal/format/support_test.go | 5 +- internal/model/model.go | 12 + internal/origins/origins.go | 35 +- internal/origins/origins_test.go | 2 +- internal/read/decode.go | 3 +- internal/read/read.go | 13 +- internal/read/read_test.go | 30 + internal/read/rules.go | 14 + internal/render/render.go | 2 +- internal/render/render_test.go | 18 +- .../full-before-ask-unlisted.envoy.yaml | 657 ++++++++++++++++++ .../testdata/full-before-ask-unlisted.yaml | 95 +++ internal/render/unlisted_test.go | 368 ++++++++++ schema/proxyfile.schema.json | 15 + 42 files changed, 1878 insertions(+), 120 deletions(-) create mode 100644 conformance/testdata/unlisted-origins.yaml create mode 100644 internal/envoy/fragments/filter-unlisted-origin.yaml create mode 100644 internal/envoy/fragments/route-unlisted-origin.yaml create mode 100644 internal/render/testdata/full-before-ask-unlisted.envoy.yaml create mode 100644 internal/render/testdata/full-before-ask-unlisted.yaml create mode 100644 internal/render/unlisted_test.go diff --git a/conformance/client_test.go b/conformance/client_test.go index 6d20765..cd33c25 100644 --- a/conformance/client_test.go +++ b/conformance/client_test.go @@ -35,7 +35,8 @@ type result struct { status int err error // set when no answer came (a TLS refusal, a closed connection) header, trailer http.Header - echo *echo // nil when no stub wrote the answer + body string // the answer's body as read, which answer.ownBody compares + echo *echo // nil when no stub wrote the answer // stubError is set when the answer is a stub's own to a request its HTTP server could not read, which no handler // sees, so it carries no echo: Go's net/http server writes it with Content-Type: text/plain; charset=utf-8 and a // body that starts with the status code and its text, such as 400 Bad Request (conn.serve in net/http/server.go, @@ -200,6 +201,7 @@ func (w *world) sendOn(client *http.Client, r request) result { got.err = fmt.Errorf("reading the answer: %w", err) return got } + got.body = string(data) got.echo = readEcho(resp.Header.Get("content-type"), data) got.stubError = resp.Header.Get("content-type") == "text/plain; charset=utf-8" && strings.HasPrefix(string(data), fmt.Sprintf("%d %s", resp.StatusCode, http.StatusText(resp.StatusCode))) diff --git a/conformance/raw_test.go b/conformance/raw_test.go index 29d73df..e84be2e 100644 --- a/conformance/raw_test.go +++ b/conformance/raw_test.go @@ -141,6 +141,7 @@ func readAnswer(reader *bufio.Reader, start time.Time) result { got.err = fmt.Errorf("reading the answer: %w", err) return got } + got.body = string(data) got.echo = readEcho(resp.Header.Get("content-type"), data) got.stubError = resp.Header.Get("content-type") == "text/plain; charset=utf-8" && strings.HasPrefix(string(data), fmt.Sprintf("%d %s", resp.StatusCode, http.StatusText(resp.StatusCode))) diff --git a/conformance/scenario_test.go b/conformance/scenario_test.go index 18e4eea..d85a917 100644 --- a/conformance/scenario_test.go +++ b/conformance/scenario_test.go @@ -201,8 +201,11 @@ type answer struct { forms map[string]*regexp.Regexp // made holds response headers the answer must carry with a value the regular expression matches, for a value the // 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 + made map[string]*regexp.Regexp + body string // the body the stub received; "" is not compared + // 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 noTrailers bool // the stub must have received no trailer marked string // the value of the target's unchecked mark the stub must receive unmarked bool // the stub must not receive the target's unchecked mark @@ -321,6 +324,9 @@ func compare(want answer, got result, mark string) []string { differ("header %s: got %q, want a value %s matches", name, value, want.made[name]) } } + if want.ownBody != "" && got.body != want.ownBody { + differ("body: got %q, want %q", got.body, want.ownBody) + } if want.grpcStatus != "" { status := got.trailer.Get("grpc-status") if status == "" { diff --git a/conformance/scenarios_test.go b/conformance/scenarios_test.go index 8584a97..459a704 100644 --- a/conformance/scenarios_test.go +++ b/conformance/scenarios_test.go @@ -16,7 +16,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, auth, toldScheme, timeout, retry, gRPC, paths, asWritten, offRoute, clientKeys, hash, tracing, tracingRetried, rateLimit, cost, backendLimits, traffic} +var scenarios = []scenario{routing, mutualTLS, cors, unlisted, auth, toldScheme, timeout, retry, gRPC, 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 { @@ -1030,6 +1030,120 @@ func preflightFrom(origin string) request { // which does not list it, leaves it without access-control-allow-origin. var ownOriginKeys = []string{"origins..hosts", "origins..origins"} +// unlisted: a browser origin none of an environment's origins and patterns holds, which the environment puts to a +// check of its own, ask_unlisted, asking it the environment's question, on the live environment's host, +// api.example.com. The stub's origin check (stub/check.go, originCheck) admits checkAdmits alone, asked browser-origin, +// and answers any other origin or question 401 with a JSON body and an x-origin-check header. An origin it admits gets +// what a listed origin gets: its preflight answered with Access-Control-Allow-Origin, its request served with it, and +// the auth check still asked after it, while the origin check is never sent the client's authorization. An origin it +// refuses, or asked about which it answers 503 or not within the 1 s the gateway waits, gets the 403 Invalid CORS +// request a refused origin gets without the key, as text/plain with no header of the check's, never the check's own +// answer; a listed origin, an origin a pattern covers, an origin on one of the environment's own hosts, which is +// admitted without the key, and a request with no Origin are never put to the check, which would refuse them; and an +// environment that writes no ask_unlisted refuses an origin no list holds as before. +var unlisted = scenario{name: "an origin no list holds", + exchanges: []exchange{ + {name: "a preflight from an origin the check admits", keys: unlistedKeys, + send: request{proto: "http/1.1", method: "OPTIONS", host: "api.example.com", path: "/products/1", + headers: map[string]string{"origin": checkAdmits, "access-control-request-method": "GET"}}, + want: answer{status: 200, headers: map[string]string{"access-control-allow-origin": checkAdmits}}}, + {name: "a request from an origin the check admits", keys: unlistedKeys, + send: request{proto: "http/1.1", method: "GET", host: "api.example.com", path: "/products/1", + headers: map[string]string{"origin": checkAdmits}}, + want: answer{status: 200, service: "shop", headers: map[string]string{"access-control-allow-origin": checkAdmits}, + received: map[string]string{"origin": checkAdmits}}}, + {name: "a request over HTTP/2 from an origin the check admits", keys: unlistedKeys, + send: request{proto: "h2", method: "GET", host: "api.example.com", path: "/products/1", + headers: map[string]string{"origin": checkAdmits}}, + want: answer{status: 200, service: "shop", headers: map[string]string{"access-control-allow-origin": checkAdmits}}}, + {name: "a preflight from an origin the check refuses", keys: unlistedKeys, + send: request{proto: "http/1.1", method: "OPTIONS", host: "api.example.com", path: "/products/1", + headers: map[string]string{"origin": checkRefuses, "access-control-request-method": "GET"}}, + want: answer{status: 403, headers: refusedOrigin, ownBody: refusedOriginBody}}, + {name: "a request from an origin the check refuses", keys: unlistedKeys, + send: request{proto: "http/1.1", method: "GET", host: "api.example.com", path: "/products/1", + headers: map[string]string{"origin": checkRefuses}}, + want: answer{status: 403, headers: refusedOrigin, ownBody: refusedOriginBody}}, + // A check that fails admits no origin: a 5xx, and no answer within the 1 s the gateway waits, refuse the origin + // as the check's refusal does, with none of the failed check's headers. The late check would have answered 200, + // after the stub's hang of 3 s, so the answer comes at the gateway's 1 s, not at the check's. + {name: "a request from an origin whose check answers 503", keys: unlistedKeys, + send: request{proto: "http/1.1", method: "GET", host: "api.example.com", path: "/products/1", + headers: map[string]string{"origin": checkDown}}, + want: answer{status: 403, headers: refusedOrigin, ownBody: refusedOriginBody}}, + {name: "a request from an origin whose check answers after the gateway stops waiting", keys: unlistedKeys, + send: request{proto: "http/1.1", method: "GET", host: "api.example.com", path: "/products/1", + headers: map[string]string{"origin": checkLate}}, + want: answer{status: 403, headers: refusedOrigin, ownBody: refusedOriginBody, + atLeast: 950 * time.Millisecond, below: 2950 * time.Millisecond}}, + {name: "a preflight from a listed origin is not put to the check", + keys: slices.Concat(unlistedKeys, []string{"origins..origins"}), + send: request{proto: "http/1.1", method: "OPTIONS", host: "api.example.com", path: "/products/1", + headers: map[string]string{"origin": "https://www.example.com", "access-control-request-method": "GET"}}, + want: answer{status: 200, headers: map[string]string{"access-control-allow-origin": "https://www.example.com"}}}, + {name: "a request from a listed origin is not put to the check", + keys: slices.Concat(unlistedKeys, []string{"origins..origins"}), + send: request{proto: "http/1.1", method: "GET", host: "api.example.com", path: "/products/1", + headers: map[string]string{"origin": "https://www.example.com"}}, + want: answer{status: 200, service: "shop", headers: map[string]string{"access-control-allow-origin": "https://www.example.com"}}}, + // An origin the environment's pattern covers is admitted by that list, as a listed one is, so it is never put to + // the check, which would refuse it. + {name: "a request from an origin a pattern covers is not put to the check", + keys: slices.Concat(unlistedKeys, []string{"origins..patterns"}), + send: request{proto: "http/1.1", method: "GET", host: "api.example.com", path: "/products/1", + headers: map[string]string{"origin": "https://shop.partner.example"}}, + want: answer{status: 200, service: "shop", headers: map[string]string{"access-control-allow-origin": "https://shop.partner.example"}}}, + // An origin on one of the environment's own hosts is admitted without a list today, with no + // Access-Control-Allow-Origin, and stays so: only an origin refused without the key is put to the check, which + // would refuse this one. + {name: "an origin on the environment's own host is admitted as without the key, not put to the check", + keys: slices.Concat(unlistedKeys, []string{"origins..hosts"}), + send: request{proto: "http/1.1", method: "GET", host: "api.example.com", path: "/products/1", + headers: map[string]string{"origin": "https://api.example.com"}}, + want: answer{status: 200, service: "shop", headers: map[string]string{"access-control-allow-origin": ""}, + received: map[string]string{"origin": "https://api.example.com"}}}, + {name: "a request with no Origin is not put to the check", keys: unlistedKeys, + send: request{proto: "http/1.1", method: "GET", host: "api.example.com", path: "/products/1"}, + want: answer{status: 200, service: "shop", headers: map[string]string{"access-control-allow-origin": ""}}}, + {name: "the auth check still decides a request from an origin the check admits", + keys: slices.Concat(unlistedKeys, []string{"auth.ask", "auth.only_with_header"}), + send: request{proto: "http/1.1", method: "GET", host: "api.example.com", path: "/products/1", + headers: map[string]string{"origin": checkAdmits, "authorization": "Bearer deny-401"}}, + want: answer{status: 401, headers: map[string]string{"access-control-allow-origin": checkAdmits}}}, + // The origin check refuses a request that reaches it with an authorization header, so this row is served only + // when the client's credential, which the auth check reads, is kept from the origin check. + {name: "the origin check is not sent the client's authorization", + keys: slices.Concat(unlistedKeys, []string{"auth.ask", "auth.only_with_header"}), + send: request{proto: "http/1.1", method: "GET", host: "api.example.com", path: "/products/1", + headers: map[string]string{"origin": checkAdmits, "authorization": "Bearer allow"}}, + want: answer{status: 200, service: "shop", headers: map[string]string{"access-control-allow-origin": checkAdmits}}}, + {name: "an origin the check admits, to an environment that asks no check", + keys: slices.Concat(unlistedKeys, []string{"origins..hosts"}), + send: fromOrigin(checkAdmits), + want: answer{status: 403, headers: refusedOrigin, ownBody: refusedOriginBody}}, + }} + +// unlistedKeys are what the rows of an origin no list holds depend on: the check the environment puts it to, and the +// question that check is asked. +var unlistedKeys = []string{"origins..ask_unlisted", "origins..question"} + +// checkAdmits is the one origin the stub's origin check admits, checkRefuses one it refuses, checkDown one it answers +// 503, and checkLate one it answers 200 after the gateway stops waiting; none is on a list of the live environment, or +// matches its patterns, in any file the rows run on. +const ( + checkAdmits = "https://files.acme.example" + checkRefuses = "https://evil.example" + checkDown = "https://down.example" + checkLate = "https://late.example" +) + +// refusedOrigin is what the answer to a refused origin carries, with the key as without it: the proxy's own text/plain, +// with no Access-Control-Allow-Origin and none of the origin check's own headers, and refusedOriginBody its body, which +// the Envoy output's listener writes (listener.yaml). +var refusedOrigin = map[string]string{"access-control-allow-origin": "", "content-type": "text/plain", "x-origin-check": ""} + +const refusedOriginBody = "Invalid CORS request" + // auth: every value measured on Envoy 1.40.2. The two denial rows assert that no x-envoy-upstream-service-time comes // with the check's answer: Envoy's client for the check adds it, and the header mutation filter removes it (without the // removal both rows got "0"). A header that is absent is absent for every proxy. Envoy also answers, and no row diff --git a/conformance/stub/backend.go b/conformance/stub/backend.go index 3f54909..030770c 100644 --- a/conformance/stub/backend.go +++ b/conformance/stub/backend.go @@ -33,6 +33,8 @@ func (b *backend) ServeHTTP(w http.ResponseWriter, r *http.Request) { b.grpc(w, r) case b.service == "accounts" && r.URL.Path == "/auth/check": b.check(w, r) + case b.service == "accounts" && r.URL.Path == "/auth/origin": + originCheck(w, r, b.hang) default: b.reply(w, r) } diff --git a/conformance/stub/check.go b/conformance/stub/check.go index 6983f1b..5e2d326 100644 --- a/conformance/stub/check.go +++ b/conformance/stub/check.go @@ -108,6 +108,40 @@ func (b *backend) check(w http.ResponseWriter, r *http.Request) { } } +// originCheck answers the check an environment puts a browser origin its lists do not hold to +// (origins..ask_unlisted), at /auth/origin: 200 for the one origin it admits, +// https://files.acme.example, asked the question browser-origin with no authorization header, and for any other origin +// or question, or a request that carries the client's authorization, 401 with a JSON body and an x-origin-check header +// of its own. So a row that wants the proxy's own 403 for a refused origin fails when the proxy passes the check's +// denial on, a row that wants an origin never put to the check, a listed one or none, fails when the proxy asks it, as +// no such origin is admitted here, and a row that sends the admitted origin with an authorization header fails when +// the proxy passes the client's credential on to this check, which is asked about an origin, not a user. +// +// 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. +func originCheck(w http.ResponseWriter, r *http.Request, hang time.Duration) { + switch origin := r.Header.Get("origin"); { + case origin == "https://down.example": + w.Header().Set("content-type", "application/json") + w.Header().Set("x-origin-check", "down") + w.WriteHeader(http.StatusServiceUnavailable) + io.WriteString(w, `{"down": "the check"}`) + case origin == "https://late.example": + time.Sleep(hang) + w.Header().Set("x-origin-check", "late") + w.WriteHeader(http.StatusOK) + case r.Header.Get("x-gateway-question") == "browser-origin" && origin == "https://files.acme.example" && + r.Header.Values("authorization") == nil: + w.WriteHeader(http.StatusOK) + default: + w.Header().Set("content-type", "application/json") + w.Header().Set("x-origin-check", "refused") + w.WriteHeader(http.StatusUnauthorized) + io.WriteString(w, `{"refused": "the origin"}`) + } +} + // allowed sets the headers of the check's allowing answer: two the full example's auth.accept admits, x-other, which // it does not, so the proxy must not pass it on to the service, and x-user-check set to report, a scenario reading it // back from the service's echo. diff --git a/conformance/stub/main.go b/conformance/stub/main.go index a8067d1..899ef36 100644 --- a/conformance/stub/main.go +++ b/conformance/stub/main.go @@ -56,8 +56,10 @@ func serve(args []string) { instance := flags.String("instance", "", "the instance the echo names, such as shop-1") ports := flags.String("ports", "", "the ports to answer on, separated by commas") state := flags.String("state", "/state", "the folder every backend shares, which remembers each x-stub-fail-first key") - // 3s is twice the full example's auth.timeout of 1500ms, so the proxy gives up on a check that hangs. - hang := flags.Duration("hang", 3*time.Second, "how long the auth check waits before it answers the token hang") + // 3s is twice the full example's auth.timeout of 1500ms, and three times the 1s the gateway waits for an origin + // check, so the proxy gives up on a check that hangs. + hang := flags.Duration("hang", 3*time.Second, + "how long the auth check waits before it answers the token hang, and the origin check the origin https://late.example") flags.Parse(args) if *service == "" || *instance == "" || *ports == "" || flags.NArg() > 0 { usageError("serve needs -service, -instance and -ports, and nothing after them") diff --git a/conformance/targets_test.go b/conformance/targets_test.go index 824d406..086be49 100644 --- a/conformance/targets_test.go +++ b/conformance/targets_test.go @@ -62,6 +62,10 @@ var ( // nginx entry and each HAProxy entry run; it runs the rows of the scheme the check is told alone, as no other row is // there for plain HTTP under connection. connectionFile = file{label: "connection", proxyfile: "testdata/connection.yaml", scenarios: []string{toldScheme.name}} + // unlistedFile is the battery's file with an environment that puts a browser origin no list holds to a check of its + // own, which only Envoy's entry runs, as the nginx and HAProxy generators refuse the key; it runs the rows of that + // scenario alone. + unlistedFile = file{label: "unlisted-origins", proxyfile: "testdata/unlisted-origins.yaml", scenarios: []string{unlisted.name}} ) // haproxyLimitsFile is the battery's file for HAProxy's connection limit, which Envoy's entry and each HAProxy entry @@ -110,6 +114,7 @@ func targets(t testing.TB) []target { tracingByNameFile, limitsFile, connectionFile, + unlistedFile, }, 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/unlisted-origins.yaml b/conformance/testdata/unlisted-origins.yaml new file mode 100644 index 0000000..69bfdcc --- /dev/null +++ b/conformance/testdata/unlisted-origins.yaml @@ -0,0 +1,38 @@ +# The conformance battery's file for a browser origin no list holds, which an environment puts to a check of its own +# (origins..ask_unlisted): the live environment of examples/full, api.example.com admitting +# https://www.example.com by its list and https://*.partner.example by a pattern, asks accounts at /auth/origin about +# any other origin, with the question browser-origin, and the stub's origin check admits https://files.acme.example +# alone, and only when it is not sent an authorization header; it answers https://down.example 503 and +# https://late.example too late. The pattern covers no origin a row puts to the check, nor the environment's own host. The auth check runs after it, under deny, asked of a request with an authorization +# header. The local environment asks no check, so an origin its hosts do not serve is refused there as without the +# key. It runs the scenario of an origin no list holds alone, and only Envoy's entry runs it: the nginx and HAProxy +# generators refuse ask_unlisted. Each literal on it is Envoy's measured answer. +listen: 10000 +admin: 9901 +services: + shop: + http: 8080 + 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 + accept: [x-user-check] +cors: + allow_methods: "*" + allow_headers: "*" + max_age: "600" +origins: + live: + hosts: [api.example.com] + origins: ["https://www.example.com"] + patterns: ["https://*.partner.example"] + ask_unlisted: accounts /auth/origin + question: browser-origin + local: + hosts: [127.0.0.1, localhost] +routes: + - {name: shop, prefix: /, to: shop} diff --git a/docs/auth.md b/docs/auth.md index bb6c1af..2cef8b0 100644 --- a/docs/auth.md +++ b/docs/auth.md @@ -138,6 +138,19 @@ the case of letters reach the route, the check and the service as sent. So write service that holds nothing that needs the check, as the sign-in services of the recipes are. A route that must open one path of a service that holds more is matched with `path`, not `prefix`. +## The check of an origin no list holds + +An environment of `origins` may put a browser origin its lists and hosts do not admit to a check of its own, +`ask_unlisted`, written as `ask` is, with the question `question` +([An origin no list holds](origins.md#an-origin-no-list-holds)). That check is asked before CORS and before this one, +in HTTP mode as this one is, at its own path, with the `Origin` and the question in `x-gateway-question`; it is never +sent the client's `Authorization`, and `send`, `accept`, `send_request` and `when_unavailable` do not apply to it. Its +`200` admits the origin, and the request then goes through this check as a request from a listed origin does: a +denial of this check reaches the client with the origin's `Access-Control-Allow-Origin`. Any other answer, a `5xx` +among them, and no answer within `1s`, refuse the origin with the `403` a foreign origin gets, before this check is +asked. A route with `auth: off` turns this check off, not the origin's. The envoy target writes it; the nginx and +haproxy targets refuse the key ([Portability](portability.md)). + ## Recipes Each recipe shows the services, the `auth` block and the routes it needs. The sign-in route comes before the diff --git a/docs/conformance.md b/docs/conformance.md index 1baa92b..b882d70 100644 --- a/docs/conformance.md +++ b/docs/conformance.md @@ -22,9 +22,11 @@ found by name, and, with a connection limit, [`conformance/testdata/haproxy.yaml`](../conformance/testdata/haproxy.yaml), [`conformance/testdata/two-checks.yaml`](../conformance/testdata/two-checks.yaml), [`conformance/testdata/haproxy-traffic.yaml`](../conformance/testdata/haproxy-traffic.yaml) and -[`conformance/testdata/haproxy-limits.yaml`](../conformance/testdata/haproxy-limits.yaml), and, with `client_address: +[`conformance/testdata/haproxy-limits.yaml`](../conformance/testdata/haproxy-limits.yaml), with `client_address: connection` and no `tls`, [`conformance/testdata/connection.yaml`](../conformance/testdata/connection.yaml), which -every entry runs but those on nginx's images tagged `-otel`. +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. 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 @@ -102,6 +104,14 @@ HTTP/2 request with `:scheme https` or `:scheme ftp` and a client's own `x-forwa connection's scheme, by every proxy. Envoy's entry, each nginx entry on the plain image and each HAProxy entry run it. +`unlisted-origins.yaml` writes `shop` and `accounts` at their addresses in the world and one route to shop. Its `live` +environment, `api.example.com`, admits `https://www.example.com` by its list and `https://*.partner.example` by a +pattern, and asks `accounts` at `/auth/origin` about an origin its list, its pattern and its host do not admit, with +`ask_unlisted` and the question `browser-origin`; the auth check runs after it, under `deny`, asked only of a request +with an `authorization` header; and its `local` environment writes no `ask_unlisted`. It runs the rows of the scenario +an origin no list holds alone, and Envoy's entry alone runs it, as the nginx and HAProxy generators refuse +`ask_unlisted` and `question`. + nginx's `nginx-checks.yaml` is `two-checks.yaml` for nginx: the same check service with two addresses, `when_unavailable: deny`, the `x-api-key` condition and `send_request: true`, with `remove_from_clients` naming `x-request-id` alone, because the nginx generator refuses a name with a `*` prefix there, so each answer the check cannot give runs on nginx under @@ -170,13 +180,14 @@ those routing's and CORS's rows send it before them, against the 20 the bucket o in this order: in Envoy's entry 616 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, and 11 on `connection`; in each nginx entry on the plain image 350 on `nginx-file`, 259 on +HAProxy's own, 11 on `connection` and 15 on `unlisted-origins`; 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,175 rows in Envoy's entry, 2,065 in each +`haproxy-traffic`, 1 on `haproxy-limits` and 11 on `connection`. That is 4,190 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,265 in all, and each passes. The battery counts these rows, and those each scenario's line in the table below +11,280 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 @@ -213,13 +224,16 @@ ran 4,145, 2,047, 615 and 848: each HAProxy entry runs `connection.yaml` too, fi the scheme the check is told, an absolute `https` target and an absolute `http` target with a token the check denies, an absolute target written `HTTPS://`, an HTTP/2 request with `:scheme ftp` and a client's own `x-forwarded-proto` of `http`, which run on `full`, `portable`, `nginx-auth`, `haproxy-file` and `connection`, and one in the scenario mutual -TLS, plain HTTP sent to the TLS port, which runs on every file with `tls`. In order: +TLS, plain HTTP sent to the TLS port, which runs on every file with `tls`. Before the Envoy output put an origin no +list holds to a check of its environment they ran 4,175, 2,065, 615 and 865: `unlisted-origins.yaml` was added with the +scenario an origin no list holds, whose 15 rows run on it alone. In order: | Scenario | Keys | What its rows check | |---|---|---| | routing | `routes[].pattern`, `routes[].path`, `routes[].method`, `routes[].rewrite`, `routes[].prefix`, `routes[].to`, `services..http`, `services..addresses`, `services..address`, `services..host_header`, `dns.resolver`, `origins..hosts`, `client_address`, `tls.certificate`, `limits.request_headers.count`, `limits.request_headers.size` | A pattern route, and a path its pattern misses going to the prefix route; a path and method route with its rewrite, and another method going to the prefix route; a service whose address the resolver gives; the prefix route over HTTP/1.1 and over HTTP/2, where the service still hears HTTP/1.1; the host each service hears, `host_header`'s value for `accounts`; a host of another environment; `404` for a host no environment names, with no `content-type`, with `vary: Origin` and with an `x-request-id` the proxy makes; a service at its one address; a path compared by letter case, `/API/webhooks` going to the prefix route; the path `/_pf_auth`, written and with its underscore escaped, routed as any other; an escaped newline, `%0A`, at the end of a path and inside one, matched by the patterns as written and passed on as sent; an upgrade other than WebSocket answered `403`, and an `h2c` upgrade served as a plain request whose service receives no `upgrade` or `http2-settings`, which HAProxy answers `400`, a declared difference; the scheme the request came in on, in `x-forwarded-proto`; with `client_address = connection`, a client's own `x-forwarded-proto` replaced by the connection's scheme, and its own `x-envoy-external-address` and `x-request-id` by values the proxy writes; each of 32 requests that carry no `x-request-id` gets one the proxy makes, a version 4 UUID in lower case, 8-4-4-4-12 hexadecimal digits with the third group starting with `4` and the fourth with `8`, `9`, `a` or `b`, and the answer carries it too; `502` with no `content-type` for a service that refuses connections, and `502` with no body for a service that takes no connection within 5 s ("a service that takes no connection within 5 s is answered 502"), which only `nginx-plain` has, as its `hold` service behind the route `/hold/` ([The world](#the-world)): Envoy and nginx answer it after at least 4.95 s and under 5.95 s, the connect time of both with no `timeouts`, and every other file serves `/hold/x` from `shop`; a service's `X-Accel-Redirect` passed on to the client, not followed; a service's `Keep-Alive` not passed on to the client; the headers the Envoy output removes (`proxy-connection`, `x-forwarded-client-cert` and the `x-envoy-` headers that steer an Envoy) never reach the service; the host of an absolute request line, not the `Host` header, is the host the service hears, where HAProxy answers every absolute target `400`, a declared difference; an `Upgrade` that `Connection` does not name is removed and the request served; header names holding `_` or `.` reach the service; `TE: gzip, trailers` reaches it as `trailers`; `404` for a host with a dot at its end, with no `content-type`, as the `404` of an empty `X-Forwarded-Proto` and the `403` of an upgrade other than WebSocket from no origin; `400` for a method Envoy's parser does not know, with no `x-request-id`, and after the `400` of a byte above 0x7F in the target, of a header name holding `@` and of `HTTP/1.10` the connection closed, so a request written after it gets no answer, and after the `426` of `HTTP/1.9` and the `403` of an upgrade other than WebSocket, from no origin or a foreign one, closed too, where HAProxy keeps it and serves the request after the body, a declared difference; a `QUERY` with a `Content-Type` served and one with none answered `400`, over HTTP/1.1 and HTTP/2, the `400` with no `content-type` and no `x-request-id`, before the `404` of a host no environment names too; a `QUERY` whose `Content-Type` is spaces alone answered `400` over HTTP/1.1 and served over HTTP/2, where HAProxy answers it `400` over HTTP/2, a declared difference, and one whose `Content-Type` is a tab answered `400` over HTTP/1.1; a pattern's `{,3}` read as text, as RE2 reads it; a long path `((a\|a)*c\|a+b)` takes, which PCRE2 gives up on with the pattern as written, reaching its route; and a long path that makes PCRE2 give up on `(a\|aa)+`, which goes on to the prefix route on Envoy and is answered `400` by nginx, a declared difference. A header name outside RFC 9110's token characters, `x@at`, `x(p)` or one holding the byte 0xFF, is answered `400` over HTTP/1.1 and refused over HTTP/2, where Envoy closes the connection and nginx answers `400`, a declared difference; the same requests, written by hand, with a name of token characters reach the service, and `x-ok`, `x_und` and `x.dot` reach it over both. A header value holding a control byte other than a tab is answered `400` over HTTP/1.1 and refused over HTTP/2, where Envoy closes the connection, HAProxy resets the stream and nginx answers `400`; a value holding a tab and UTF-8 reaches the service over both. A client that sends its request and closes its side of the connection before the service answers gets no answer: Envoy closes the connection, and HAProxy answers `400` or `403` or closes it. The row has its service hold its answer for 500 ms (`x-stub-delay`), because a proxy that reads the client's close after the service's answer passes the answer on: with a service that answered at once, a close sent with the request got no answer in 300 of 300 tries through Envoy and each nginx, and one sent 1 ms later got the service's `200` in 297 of 300 through Envoy and 300 of 300 through each nginx, so the row was a race, and it failed once in a whole run on nginx 1.31.8 and once on HAProxy 3.4.7. Under `client_address = forwarded`, an empty `X-Forwarded-Proto` from a client in front is answered `404` ("an empty X-Forwarded-Proto from a client in front is answered 404"), and with `connection` the request is served with the connection's scheme in its place; an `X-Forwarded-Proto` of spaces alone over HTTP/2 is served, where HAProxy answers `404`, a declared difference. A header written `x_forwarded_proto`, a name nginx reads as its own `X-Forwarded-Proto`, reaches the service as sent through Envoy and is answered `400` by nginx, a declared difference; `x_forwarded_for`, which nginx does not read as its own `X-Forwarded-For`, and a header named `constructor` or `__proto__`, over HTTP/1.1 and HTTP/2, reach the service as sent through both. Two `Accept` lines reach the service as one line through Envoy and as two lines through nginx, the same message, and two `Content-Type`, `User-Agent`, `Referer` or `If-Match` lines are joined and served by Envoy and answered `400` by nginx, each a declared difference on nginx's request-line row. With two or three spaces around an absolute target, the target's host is the host the service hears whatever the `Host` header says, and one that ends with a dot gets `404`; a tab after the method is served by Envoy and answered `400` by nginx, a declared difference; an absolute target whose host a query follows is refused. `TE: Trailers` reaches the service as `trailers` when `Connection` names `te` and is removed when it does not, and `Connection: close,` is served. An absolute target with an empty port, `http://localhost:/products/1`, is answered `400`. A chunked body's trailer reaches the service through no proxy, which receives the body; a trailer whose name holds `@` is answered `400` by Envoy and let through by nginx, which serves the body without it, and so is a trailer whose value holds a control byte, which HAProxy lets through too, over HTTP/1.1 and HTTP/2, and over HTTP/2 a trailer is served by Envoy and ends the connection on nginx, each a declared difference. A header line with no colon is answered `400` by Envoy and reaches the service through nginx as a header with an empty value, one of nginx's less strict ways. A header line folded onto the next, with a space or a tab, is served by Envoy and answered `400` by nginx and HAProxy, and a `Host` whose port is `99999` or `+1` is served by Envoy and answered `400` by nginx, declared differences. 100 header lines reach the service and 101 are refused (on `full` and `portable`, whose `limits.request_headers` admits 150, they reach it), and 96 header fields over HTTP/2 reach it, which nginx refuses, one field under Envoy's count, a declared difference, and 97 are refused ("97 header fields over HTTP 2 are refused", on the files that write `limits.request_headers.count`: Envoy resets the stream and nginx refuses the request, and `full` and `portable`, whose count is 150, serve them), and so are 96 beside `:authority` and a `host` field of the same value, which Envoy counts as two fields ("96 header fields over HTTP 2 beside :authority and a host field are refused", on the same files); HTTP/1.0 is answered `426`, with no `x-request-id`, and so are `HTTP/1.2`, `HTTP/1.9`, `HTTP/0.9` with headers, where nginx answers `400`, and `HTTP/2.0` on an HTTP/1 connection, where nginx answers `505`, and a request line with no version, where HAProxy answers `400` and nginx closes the connection, each a declared difference; `HTTP/1.10` and `HTTP/1.01` are answered `400`, and a method in lower case `400`; a header a `Connection` token names does not reach the service, where nginx and HAProxy answer `400`, a declared difference, and neither does `Keep-Alive`; `HTTP2-Settings` on a request that is no upgrade reaches the service; ten `Connection` tokens are answered `400` and nine served, a token and ten empty elements are served, where HAProxy answers `400`, a token and nine elements of white space are answered `400`, and ten tokens `close` are answered `400`, where HAProxy serves them, each a declared difference; a WebSocket over HTTP/2 is refused; over HTTP/2 an `:authority` with an empty port, `localhost:`, reaches the service as sent, where HAProxy sends `localhost`; two `Host` lines of one host are answered `404`, where HAProxy serves the request and nginx answers `400`; two `Content-Length` lines of one value, and `Content-Length` beside `Transfer-Encoding: chunked`, are answered `400`, and `Transfer-Encoding: gzip, chunked` `501`, where HAProxy serves the first two and answers the third `422`; a `POST` with no body reaches the service with `content-length: 0`, which neither nginx nor HAProxy sends; a WebSocket upgrade the service answers `200` without switching reaches the client with no body, where nginx and HAProxy pass the service's; a header of 20,000 bytes and a path of 20,000 bytes reach the service, where HAProxy answers `431` and `414`; on the files that write `limits.request_headers.size`, a head 64 bytes under the size, 61,376 bytes for the 60 KiB `nginx-file` writes, reaches the service as a header block ("a header block 64 bytes under the size", one header of 61,322 bytes) and as a request line ("a request line 64 bytes under the size", a path of `/products/` and 61,332 `a`), and a head one byte over Envoy's bound, 61,441 bytes, is refused: Envoy answers `431` to both, and nginx `400` to the header block ("a header block one byte over the size") and `414` to the request line ("a request line one byte over the size"), its own literal under `limits.request_headers.size`, while `full` and `portable` write 96 KiB and serve both; nginx reads a head of 61,376 bytes at most ([nginx](nginx.md#the-header-limits)), so the rows 64 bytes under have no margin on it; and over HTTP/2 a path of 7,000 bytes above 0x7F reaches the service, which HAProxy refuses and nginx answers `400` on `nginx-file`, each a declared difference; and a service that closes the connection of the first request a client sends on its connection before it answers is answered `502`, and so is one that closes, before its answer, a connection to `catalog` the proxy kept from a request on the client's same connection, over HTTP/1.1 and HTTP/2, the request reaching it once, where HAProxy sent it again before each request had a connection of its own. On `haproxy-file`, whose `test` environment has the hosts `.dot.example.com`, `dot.example.com.`, `-f`, `-i` and `-n`, a request to each reaches the service with that host, and on every other file it gets `404`. With `client_address = connection`, a client's `X-Forwarded-For` reaches the service on one line with the peer's address, and so do two lines of it, which Envoy joins, where nginx answers `400`, a declared difference, and the `x-envoy-` headers only a proxy in front may send (`x-envoy-decorator-operation`, `x-envoy-downstream-service-cluster`, `x-envoy-downstream-service-node`, `x-envoy-original-host`, `x-envoy-original-path`) do not reach it. The check location's own path, `/.proxyfile/check`, written or with its dot escaped, is routed as any other path and reaches `shop` as written, a prefix route's path without its slash, `/catalog`, is routed and not redirected, and a client that closes its side of the connection right after a request with a dot segment with a `;` parameter gets no answer, where nginx answers `400`, a declared difference. In Envoy's entry: 150 rows on `full`, `portable` and `nginx-file`, 149 on `nginx-auth`, which writes no `dns.resolver`, 144 on `haproxy-file`, which writes no `limits.request_headers`, 144 on `nginx-tracing`, which writes no `dns.resolver`, no `tls` and no `client_address`, and 131 on `nginx-plain`, `two-checks` and `nginx-checks`, which write none of those, no `limits.request_headers` and no pattern route. | | mutual TLS | `tls.certificate`, `tls.key`, `tls.clients.ca`, `origins..hosts` | A client with no certificate, one whose certificate another CA signed, and one whose certificate the clients CA signed and whose validity ended reach no service: the handshake fails, or the proxy refuses it, where nginx completes the handshake and answers an empty `400`, the difference nginx's row of `tls.clients.ca` names. A request whose TLS server name is one host of an environment and whose `Host` is another host of the same environment is served by Envoy and answered with an empty `421` by nginx, which asks for client certificates, a declared difference. The other CA carries the clients CA's name, so a proxy that matched the issuer by name would let it through. Every other row sends a client certificate the clients CA signed. A client that offers only TLS 1.1, a TLS 1.2 client that offers only a CBC suite, and one that offers only the group P-384 are refused in the handshake, and one that offers only the group X25519MLKEM768 is served. Plain HTTP sent to the TLS port, with a token the check allows, reaches no service: the Envoy output and HAProxy close the connection, and nginx answers an empty `400`, the difference nginx's row of `tls` names. In Envoy's entry: 9 rows on `full`, `portable`, `nginx-file`, `haproxy-file` and `nginx-auth`, the files that write `tls`. | | CORS | `cors.allow_methods`, `cors.allow_headers`, `cors.expose_headers`, `cors.max_age`, `origins..hosts`, `origins..origins`, `origins..patterns` | A preflight from a listed origin and one from an origin a pattern covers answer `200` with `access-control-allow-origin` and `access-control-max-age`; a preflight and a request from another origin answer `403`, and so does a request from another origin to a path ending `.html`, as `text/plain` on every proxy, whose own answers take no type from the path's ending; a request from a listed origin reaches the service with its `origin` and is answered with `access-control-allow-origin` and `access-control-expose-headers`. The preflight from a listed origin and the request from another origin carry a token the check denies and one the token filter refuses, each answered `401` alone, so on a file that writes the check their `200` and `403` show that the origin is decided before the token and the check. An origin on the environment's own host that neither list holds, `https://api.example.org` to `api.example.org`, is admitted without `access-control-allow-origin`: its request reaches the service and its preflight answers `200`. With no list, an origin on one of the environment's hosts is admitted and every other refused: a request with no `Origin`, and one from `http://localhost` over `http` or `https`, with a port, or from the environment's other host `http://127.0.0.1` reaches the service, and a preflight from `http://localhost` is answered `200` by the proxy; an origin on another environment's host, the host in capitals, with a trailing dot or with other characters for its dots, `null`, a present but empty `Origin`, a preflight from another origin and a WebSocket upgrade from one answer `403`, where HAProxy's parser answers that upgrade, which carries no `Sec-WebSocket-Key`, `400`, a declared difference. An empty `Origin` over HTTP/2 is answered `403` too, and an empty `Origin` line before or after the origin of the host, or a tab before that origin, changes nothing: the service receives the origin as one line. A preflight from a listed origin with no token is answered with the method and the headers it asks for; one from a listed origin in capitals is admitted with the origin as sent, and one from a pattern's origin in capitals is refused. The `Origin` header is read as one line: two `Origin` lines a pattern covers when joined are admitted with the joined line in `access-control-allow-origin`, where nginx answers `403`, a declared difference, two whose first is listed, two of the request's own origin, and one line holding a listed origin after a comma are refused, and an empty `Origin` line after a listed one is left out; a preflight that asks on two lines for two methods or for headers is answered with both, joined with a comma, and by nginx with a comma and a space, a declared difference. A listed origin with a trailing space is admitted, and the service receives it without the space. A service that is down, asked from a listed origin, is answered `502` with `access-control-allow-origin` and `access-control-expose-headers`, and a request from a listed origin to a host no environment names is answered `404` with no `access-control-allow-origin`. A refused path, a preflight to it, an upgrade other than WebSocket, a request with a NUL byte in a header from a listed origin and one with `Content-Length` beside `Transfer-Encoding: chunked` from it are answered with no `access-control-allow-origin`, where HAProxy serves the last with it, a declared difference, and a header line of 9,000 bytes from one is served with it by every proxy, nginx's header buffers reading a line as long as the header limit ([nginx](nginx.md#the-header-limits)). An admitted `Origin` of 600 bytes is echoed beside a service's answer of 100 KB, and so is one of 1,100 bytes, where HAProxy answers `403` before the service, a declared difference. A preflight from a listed origin to `/..;x/products/1`, with no token and with a token the check allows, is answered `200` by Envoy, which resolves the path and asks no check, and `400` by nginx and HAProxy, which with the token ask the check first, each a declared difference, and a denial of the check from a listed origin carries `access-control-allow-origin` and `access-control-expose-headers`. In Envoy's entry: 52 rows on `full`, `portable`, `haproxy-file`, `nginx-auth` and `nginx-tracing`, 50 on `nginx-file`, which writes no check, and 19 on `nginx-plain`, `two-checks` and `nginx-checks`, which write no list of origins and no `cors`. | +| an origin no list holds | `origins..ask_unlisted`, `origins..question`, `origins..origins`, `origins..patterns`, `origins..hosts`, `auth.ask`, `auth.only_with_header` | On `unlisted-origins`, whose environment `live` asks the stub's origin check about an origin its list, its pattern and its hosts do not admit: a preflight from `https://files.acme.example`, which the check admits, answers `200` with `access-control-allow-origin` set to it, and its request reaches the service with its `origin` and is answered with that header, over HTTP/1.1 and HTTP/2; a preflight and a request from `https://evil.example`, which the check refuses with `401`, a JSON body and an `x-origin-check` header, answer `403` with the body `Invalid CORS request` as `text/plain`, with no `access-control-allow-origin` and no header of the check's, as a refused origin is answered without the key; a request from `https://down.example`, which the check answers `503`, and one from `https://late.example`, which it answers `200` only after 3 s, get the same `403`, the late one after the 1 s the gateway waits, so a check that fails admits no origin; a preflight and a request from the listed `https://www.example.com`, a request from `https://shop.partner.example`, which the environment's pattern covers, answered with `access-control-allow-origin` set to it, a request from `https://api.example.com`, the environment's own host, and a request with no `Origin` are served as without the key, which they could not be if the check were asked, as it refuses them; a request from the admitted origin with a token the auth check denies gets the check's `401` with `access-control-allow-origin`, so the auth check still decides after the origin check; a request from the admitted origin with a token the auth check allows is served with that header, which it could not be if the origin check were sent the client's `authorization`, as the stub's origin check refuses a request that carries one; and the admitted origin, to `local`, which writes no `ask_unlisted`, gets the same `403`. Each of these five refusals is checked down to its body. In Envoy's entry: 15 rows on `unlisted-origins`. | | auth | `auth.ask`, `auth.only_with_header`, `auth.send`, `auth.accept`, `auth.send_request`, `auth.timeout`, `auth.when_unavailable`, `routes[].auth`, `remove_from_clients`, `auth.jwt.claims`, `services..host_header`, `cors.expose_headers`, `origins..origins`, `log` | A request with no `authorization` header reaches the service, which it could not if the check were asked; when the check allows, the service receives the check's headers `auth.accept` admits and not another, and what the check was told (the method, the path with its query, `x-country`), never the `x-forwarded-uri` and `x-forwarded-method` the client sent; the check's `401` and `403` reach the client, without the `x-envoy-upstream-service-time` Envoy's client for the check adds; a check that answers `503` lets the request through, as `when_unavailable = allow` says, and on `two-checks` and `nginx-checks`, whose `when_unavailable` is `deny`, gets `403`; the mark of a request the check could not answer reaches the service, and a client's own copy never does, whether the check allows or is not asked; a route with `auth = off` is not checked; a client's own copies of the headers `remove_from_clients` names, of the check's headers and question, and of the headers `auth.jwt.claims` sets never reach the service. A header `remove_from_clients` names does not reach the service when a client sends it on two lines, one with its name in capitals; a client's own `x-request-id` is replaced by another when `remove_from_clients` names it; and on `two-checks`, whose `remove_from_clients` names the prefix `ho*`, a client's `ho-x` does not reach the service and its `Host` does. The check is told it is internal and its deadline, `x-envoy-internal: true` and `x-envoy-expected-rq-timeout-ms: 1500`; a header sent on two lines reaches it as one line, joined with a comma; a client's own `x-forwarded-proto` reaches it under `forwarded`, and the connection's scheme under `connection`; it receives the `Host` the client sent whatever the check service's `host_header`; and the `only_with_header` header sent twice, an empty line before or after the token, asks it. A check's `201` is answered `403`, and a status of `600` is passed on as the check's own, where HAProxy and nginx answer `403`. A denial of 20,000 bytes, and one with a header of 50,000, reach the client, and an allowing answer whose `x-user-id` holds 20,000 bytes sets it on the request where `auth.accept` admits it, where HAProxy answers each `403`, a declared difference. An answer whose body breaks off, and one of 101 header lines, are a check that could not answer: the request is served with the mark under `allow` and answered `403` under `deny`. A `200` that RFC 9112 does not read whole is such a check for Envoy too, in these forms: a `Content-Length` that is not a number, two `Content-Length` lines, a control byte in a header value, a status that is not three digits, a header name outside the token characters, `Content-Length` beside `Transfer-Encoding`, a chunk size that is not hexadecimal, a malformed header line in a `1xx` before it, and a malformed trailer line; HAProxy answers each `403` under `allow` too, a declared difference. Of 24 requests while `check-2`, one of the two check backends of `two-checks` and `nginx-checks`, refuses connections, at least one is answered `403` on those files: no other backend answers a check it refused. Rows for each form of an answer a check can write that RFC 9112 reads in a way of its own hold Envoy's reading, measured on Envoy 1.40.2: a status line of `2 0 0`, `20` or `000`, of `304` or of `101` is passed on as the check's own, and so is a denial with a folded header line; a status of `200.1`, `500`, `599`, or `503` with a body, a `200` with a header line with no colon, a header value with a vertical tab, `Transfer-Encoding: gzip, chunked`, or `identity` beside a `Content-Length`, a chunk that does not end its line, a space before a header's colon, a header name that holds a NUL or the byte `0xE9`, and a `Content-Length` past what any reader holds, are each a check that could not answer, and so is a denial with a header line with no colon; a `200` of `HTTP/2.0`, with two spaces after its version, with a space after a chunk's size, with spaces around its `Content-Length`, with a lone CR before a CRLF, with `_` in a header name, with bytes after its body, with a body of 1 MiB, or holding the relay's own header name `x-proxyfile-check`, is read as allowed. A denial with a body of 1 MiB, of 1 MiB and a byte and of 1,100,000 bytes reaches the client whole, and a denial's header that holds the byte `0xE9` reaches it as the check wrote it, and a denial with no body reaches it with no `content-type`. A `200` whose chunk-size line ends in a bare LF, or whose last chunk's line does, is a check that could not answer on Envoy, and a `200` whose chunk data, trailer line and final line end in a bare LF is read as allowed; nginx's relay and HAProxy's script refuse the first two under `allow` too, a declared difference. A `200` whose accepted header is folded reaches the service with the spaces and tabs of the fold, a tab, spaces on both lines or two folds, where HAProxy joins them by one space, a declared difference, and one whose accepted header is empty reaches the service empty. A `200` whose accepted header takes the request past the header size is answered `500`, where HAProxy answers `431`, a declared difference, and one whose accepted headers take it past the header count, 100 fields as Envoy counts them, is answered `500` by Envoy on every file but `full` and `portable`, which serve it, by nginx and by HAProxy, with an admitted origin's CORS answer, where one they take to the count is served: with `client_address: connection` the `x-forwarded-for` and `x-envoy-external-address` the proxy sets count too, so 87 lines from the client reach the count there and 91 elsewhere. A `200` that sets no accepted header is not counted, so with 96 numbered lines beside it the request is served by every proxy. With the accepted header and 91 numbered lines, a request with a chunked body is served, its `Transfer-Encoding` line not counted, and one with a body framed by its length is answered `500`, its `Content-Length` line counted, on `two-checks` and `nginx-checks`, where `haproxy-file` and `nginx-auth`, with three accepted headers and the two the proxy sets under `client_address: connection`, answer both `500` and `full` and `portable`, whose count is 150, serve both; and a gRPC call over HTTP/2 whose accepted header and 87 numbered fields take it past the count is answered `200` with `grpc-status` `2` and reaches no service, and one with 86 is served, where `haproxy-file` and `nginx-auth` answer 86 with `grpc-status` `2` too and `full` and `portable` serve both. nginx's relay reads some of these forms otherwise, and each such row holds nginx's own answer under `by`, named by the row of `auth.ask` or of `auth.when_unavailable` that declares it. Rows for how nginx asks the check hold Envoy's answer, and nginx's own where it declares a difference: the check location's own path asks the check as any other path does; an upload sent with `Expect: 100-continue` that the check refuses gets `100 Continue` first; a request with a body the check allows reaches the service with its body; a sent header that holds the byte `0xE9` reaches the check with a `!` for it, one that holds well-formed UTF-8 reaches it as sent, one that holds well-formed UTF-8 and then a byte that is not reaches it with a `!` for that byte, a header on two lines of characters outside ASCII reaches it as sent, joined by a comma, and a path of well-formed UTF-8 and then a byte that is not, over HTTP/2, is told to it escaped, as the service receives it; an `only_with_header` header sent as a lone tab is not asked; 100 checked streams at once on one HTTP/2 connection are each answered by their own check; an absolute target's host is the host the check is told, whatever the `Host` header, and its scheme under `forwarded`, where under `connection` the check and the service are told the connection's; a client's own user, question and unchecked mark do not reach the service when the check allows with none of them, and the check receives none of a client's own removed header, user and mark; a dot segment with a `;` parameter asks the check first, and is answered `400` when the check allows; a denial of a request from a listed origin carries the CORS answer; a WebSocket upgrade the check allows reaches the service, and one it denies is answered with the denial; a header the check's answer sets on one request is not on the next request of the same connection, and a check's `2xx` other than `200` is answered at once on a kept-alive connection; a request the check denies, one whose check is unanswered and one whose check's status is passed on each have a body that holds a request read as a body, and the next request on the connection is answered, where nginx and HAProxy answer a status of `600` `403` and the unanswered one is `403` first on `two-checks` and `nginx-checks`; a client's own `x-proxyfile-method` and `x-proxyfile-path` change nothing the check is told; the check is told the path with an escaped letter, with a dot-dot segment and a query, with a query's escapes of unreserved and of reserved characters, and with a quote; an HTTP/2 request is told its `:scheme` under `forwarded`, and under `connection` the check and the service are told the connection's scheme; a client's `HTTP2-Settings` of an h2c upgrade does not reach the check, and with no upgrade it reaches it when `send` covers it; a check's redirect whose `Location` is a path reaches the client as the check sent it; and the request log holds how long a denied request's check took, no check time for a request with no `only_with_header` header, and an unanswered check for a request the check cannot answer under `allow`. A request to a retried route is checked once, before its first try: with one shop backend refusing connections, each of 20 requests the check allows reaches the other backend with the header the check accepted, each of 6 it denies is answered `403` with no service, and each of 10 whose check answers `503` reaches the other backend with the unchecked mark under `allow` and is answered `403` under `deny`. In Envoy's entry: 152 rows on `full`, 151 on `nginx-auth`, which writes no `auth.jwt.claims`, 148 on `portable`, which writes neither that nor `routes[].retries`, 148 on `nginx-tracing`, which writes no `auth.jwt.claims` and no `client_address`, 144 on `haproxy-file`, which writes neither of the first two, no `log` and no `limits.request_headers`, 132 on `nginx-checks`, which writes none of `auth.jwt.claims`, `auth.send`, `log` and `client_address`, no `limits.request_headers`, no route with `auth = off` and no list of origins, 129 on `two-checks`, which writes no `routes[].retries` either, and 3 on `nginx-file` and `nginx-plain`, the rows of `remove_from_clients`, which they write with no check. | | the scheme the check is told | `client_address`, `auth.ask`, `auth.accept`, `auth.send_request` | Each row asks the check, which reports the scheme it was told, and the service reports the `x-forwarded-proto` it received. Under `client_address: connection` every proxy tells the check and the service the connection's scheme, whatever the client writes: an absolute `https` target, and one written `HTTPS://`, is served over TLS and told `https`, but by HAProxy, which answers an absolute target `400`, and on `connection`, over plain HTTP, the Envoy output answers it `403`, and nginx serves it and tells the check and the service `http`, a declared difference; the same request with a token the check denies is answered `401` where the check is asked, and `403` by the Envoy output on `connection` and `400` by HAProxy on every file, so neither asks the check; an absolute `http` target with that token is answered `401`, and `400` by HAProxy; an HTTP/2 request with `:scheme https`, or with `:scheme ftp`, is told `https` over TLS and `http` on `connection`; and a client's own `x-forwarded-proto` of `https`, `http` or `ftp` is replaced by the connection's scheme. Under `forwarded`, on `two-checks`, `nginx-checks` and `nginx-tracing`: an absolute `https` target sent with `x-forwarded-proto: http` is told `https`, the target's scheme, and the service is sent `http`, where HAProxy answers `400`; an HTTP/2 request with `:scheme https` sent with `x-forwarded-proto: http` is told `https` by the Envoy output and `http` by nginx and HAProxy, a declared difference, and the service is sent `http`; and an `x-forwarded-proto` of `ftp` reaches the service as sent, while the Envoy output tells the check `http`, the connection's scheme, and nginx and HAProxy tell it `ftp`, a declared difference, which each one's list of ways it is less strict names. In Envoy's entry: 11 rows on `full`, `portable`, `nginx-auth`, `haproxy-file` and `connection`, and 3 on `two-checks`, `nginx-checks` and `nginx-tracing`, the rows whose keys hold no `client_address`. | | 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. | @@ -274,7 +288,7 @@ 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, and the auth check `auth.ask` names. | +| `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. | | `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. | @@ -291,7 +305,13 @@ protocol, method, path, host and headers, so a row can say which service answere 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 `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. Other tokens give the answers a proxy must read with care: `report`, `report-forwarded` and +fails when the proxy asks it. The origin check at `/auth/origin` answers `200` to the origin +`https://files.acme.example` asked the question `browser-origin` alone, with no `authorization` header; `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 +fails when the proxy passes that refusal on, or admits an origin whose check failed, or +answers an origin it admits without the key as the check would. Other tokens give the answers a proxy must read with care: `report`, `report-forwarded` and `report-trace` allow and put in `x-user-check` what the check was told (`x-envoy-internal` and `x-envoy-expected-rq-timeout-ms`, `x-forwarded-proto` and `Host`, or `traceparent` and `tracestate`); `big-accept` allows with an `x-user-id` of 20,000 bytes; `big-denial` denies with a body of 20,000 bytes and `big-header` with a header of 50,000; `deny-401-message` denies with a body that holds a `%`, a @@ -343,12 +363,14 @@ signs, and one the clients CA signed whose validity ended a day before the run, ## What it does not prove -- Answers each proxy writes in its own words. No row checks a local reply's body, or that an answer carries a header a - proxy names after itself, which [portability](portability.md) classes as that proxy's own: measured on Envoy 1.40.2, - the `403` body `Invalid CORS request`, the empty `502`, the `429` body `local_rate_limited`, and the `403` Envoy - answers when the check answers `204`. A row may check such a header absent, which holds for every proxy, as the - denial rows do. The mark of a request the check could not answer, `x-envoy-auth-failure-mode-allowed`, is checked - although it carries Envoy's name, because every proxy writes that name. +- Answers each proxy writes in its own words, which [portability](portability.md) classes as that proxy's own. No row + checks that an answer carries a header a proxy names after itself, and only the rows of the scenario an origin no list + holds, which only Envoy's entry runs, check a local reply's body: the `403` body `Invalid CORS request` + (`answer.ownBody`). Measured on Envoy 1.40.2 and checked by no row: that body on a foreign origin's `403` in the other + scenarios, the empty `502`, the `429` body `local_rate_limited`, and the `403` Envoy answers when the check answers + `204`. A row may check such a header absent, which holds for every proxy, as the denial rows do. The mark of a request + the check could not answer, `x-envoy-auth-failure-mode-allowed`, is checked although it carries Envoy's name, because + every proxy writes that name. - A retry of a service with one backend. A row would need the backend to refuse exactly one connection and accept the next, which the stub cannot time. Measured on Envoy 1.40.2 instead, with a firewall rule in the backend's own network namespace that refused one connection: the retry went to the same backend and was answered `200`, five times of diff --git a/docs/defaults.md b/docs/defaults.md index 534c59e..6fb289a 100644 --- a/docs/defaults.md +++ b/docs/defaults.md @@ -115,11 +115,13 @@ what that is. user agent or referrer, because paths can carry links and tokens. With `log`, the request log writes every response at or above `status_from`, every response with a response flag, and `sample` of the rest, chosen by the first eight hex digits of `x-request-id`. -- **The order of the filters:** set metadata (with `auth.ask`), header mutation, the RBAC refusal of a foreign browser - origin, CORS, the rate limit filter (only when a route or the rpc entry has a `rate_limit`), the token filter (with - `auth.jwt`), the auth check (with `auth.ask`), the Lua status filter and the Connect bridge (with an rpc entry, unless - `envoy.connect_bridge` is `false`), and the router. A foreign origin and a request over a rate limit are refused - before a token is verified or the check could be called, and a token is verified before the check is asked. +- **The order of the filters:** set metadata (with `auth.ask`), header mutation, the check of each environment that + writes `ask_unlisted`, which RBAC reads ([An origin no list holds](origins.md#an-origin-no-list-holds)), the RBAC + refusal of a foreign browser origin, CORS, the rate limit filter (only when a route or the rpc entry has a + `rate_limit`), the token filter (with `auth.jwt`), the auth check (with `auth.ask`), the Lua status filter and the + Connect bridge (with an rpc entry, unless `envoy.connect_bridge` is `false`), and the router. A foreign origin and a + request over a rate limit are refused before a token is verified or the check could be called, and a token is + verified before the check is asked. ## Fixed names @@ -139,7 +141,10 @@ runtime value, for example, looks it up by its key. | `otel_collector` | The cluster of the tracing endpoint, written with the `otel` provider. | | `jwks` | The cluster of the keys URL's host, written when `auth.jwt.keys` is an https URL. | | `browser-origins` | The one RBAC policy of each virtual host. | +| `ask_unlisted:` | Followed by the environment's name, the name of the check of an environment that writes `ask_unlisted`, a filter off on every route but the environment's copies of the routes for an origin no list holds, which turn it on by this name. It keeps its decision in the filter state under this name and `.shadow`. | +| `admitted-by-the-check` | The RBAC policy of each such copy of a route, which admits a request only when the environment's check answered `200`. | | `x-gateway-action`, `x-gateway-reports` | The question headers of an RPC route, read by the auth check. | +| `x-gateway-question` | The question `origins..question` sends the environment's check. | | `x-gateway-timeout-ms` | The check's deadline in milliseconds. | One line of the generated file is meant for a tool to switch by editing the file as text: the default of the auth check. diff --git a/docs/format.md b/docs/format.md index cce24a0..1eb00a8 100644 --- a/docs/format.md +++ b/docs/format.md @@ -6,20 +6,22 @@ names, the forms of sizes, times and percentages, the rules that compare keys wi [what 2.2 changes for a 2.1 file](#from-21-to-22). `examples/full/yaml/proxyfile.yaml` holds every key a proxyfile can have, with invented values, except `rpc.proto`, -`envoy.tracing`, the `xray` provider, `hash.client` and the `nginx` and `haproxy` blocks, which take no key in this -version. Other examples write the first four and what the full example writes one way only: -`examples/partial/proto-methods` writes `rpc.proto`; `examples/tracing` the `xray` provider at `tracing` and, in -`envoy-tracing/`, at `envoy.tracing`, where it gives the same `envoy.yaml`; `examples/balanced` and `examples/dns` the -other ways to give a service its backends, `hash.client` among them; `examples/otel` a tracing endpoint by name; and -`examples/jwt` a keys file and a route without the token check. `examples/partial` gives its methods three ways, each -in a folder of its own: `yaml/proxyfile.yaml` with `--rpc-methods ../methods.json`, `hocon/Proxyfile` through +`envoy.tracing`, the `xray` provider, `hash.client`, an environment's `ask_unlisted` and `question`, and the `nginx` +and `haproxy` blocks, which take no key in this version. Other examples write the first four and what the full example +writes one way only: `examples/partial/proto-methods` writes `rpc.proto`; `examples/tracing` the `xray` provider at +`tracing` and, in `envoy-tracing/`, at `envoy.tracing`, where it gives the same `envoy.yaml`; `examples/balanced` and +`examples/dns` the other ways to give a service its backends, `hash.client` among them; `examples/otel` a tracing +endpoint by name; and `examples/jwt` a keys file and a route without the token check. `examples/partial` gives its +methods three ways, each in a folder of its own: `yaml/proxyfile.yaml` with `--rpc-methods ../methods.json`, `hocon/Proxyfile` through `include required("../rpc-methods.conf")`, and `proto-methods/Proxyfile` through `rpc.proto` and the `.proto` files -under `proto/`. `examples/grpc/yaml/proxyfile.yaml` turns `envoy.connect_bridge` off. Only `listen`, `services`, -`origins` and `routes` are required. The rest is left out when you do not need it. +under `proto/`. `examples/grpc/yaml/proxyfile.yaml` turns `envoy.connect_bridge` off. The conformance battery's +[`unlisted-origins.yaml`](../conformance/testdata/unlisted-origins.yaml) writes `ask_unlisted` and `question` +([An origin no list holds](origins.md#an-origin-no-list-holds)). Only `listen`, `services`, `origins` and `routes` are +required. The rest is left out when you do not need it. ```yaml # yaml-language-server: $schema=../../../schema/proxyfile.schema.json -# Every key but rpc.proto, envoy.tracing, the xray provider, hash.client, nginx and haproxy, with invented values. +# Every key but rpc.proto, envoy.tracing, the xray provider, hash.client, origins..ask_unlisted and question, nginx and haproxy, with invented values. listen: 10000 admin: 9901 tls: diff --git a/docs/origins.md b/docs/origins.md index edf6acd..6efe202 100644 --- a/docs/origins.md +++ b/docs/origins.md @@ -11,23 +11,25 @@ part, so a local setup may reach the gateway on any port. A browser request is a - its `Origin` is in the environment's `origins` or matches one of its `patterns`. Any other browser origin is refused with `403`, preflights, requests and WebSocket upgrades alike, before CORS, the auth -check or any service sees it. For an admitted origin the gateway answers every preflight itself, so none reaches a -service or the check. - -Only an origin that `origins` or `patterns` holds gets `Access-Control-Allow-Origin` and -`Access-Control-Expose-Headers`. To such an origin every answer, its preflight's included, carries -`Access-Control-Allow-Origin` with that origin, and `Access-Control-Expose-Headers` when `expose_headers` is written, -replacing any the service sent. An origin on one of the environment's own hosts that neither holds is admitted without -those two headers, also when its host and port are the request's own `Host`: its requests reach the service, and its -preflight is answered `200` with `Access-Control-Allow-Methods`, `Access-Control-Allow-Headers` and -`Access-Control-Max-Age` from `cors` but no `Access-Control-Allow-Origin`, so a browser does not act on them (the Fetch -standard, "CORS check"). A browser needs no CORS header for a page's own origin, which it sends with some requests, -such as a `POST`, so the gateway admits it. A page on another port or scheme of the same host is another origin to the -browser, which refuses an answer without `Access-Control-Allow-Origin`; to let it read answers, write its origin in -`origins` or `patterns`. Measured on Envoy 1.40.2 with the full example's `live` environment and `cors`: -`https://www.example.com` to `api.example.com`, listed in `origins`, got both headers on its request and its preflight; -`https://api.example.org` to `api.example.org`, and `https://api.example.org:8443` to `api.example.org:8443`, in -neither list, got neither, and their preflights carried the other three. +check or any service sees it, unless the environment puts it to a check of its own +([An origin no list holds](#an-origin-no-list-holds)). For an admitted origin the gateway answers every preflight +itself, so none reaches a route's service or the auth check; the preflight of an origin no list holds reaches only the +environment's own check, when it writes one. + +Only an origin that `origins` or `patterns` holds, or that the environment's own check admits, gets +`Access-Control-Allow-Origin` and `Access-Control-Expose-Headers`. To such an origin every answer, its preflight's +included, carries `Access-Control-Allow-Origin` with that origin, and `Access-Control-Expose-Headers` when +`expose_headers` is written, replacing any the service sent. An origin on one of the environment's own hosts that +neither holds is admitted without those two headers, also when its host and port are the request's own `Host`: its +requests reach the service, and its preflight is answered `200` with `Access-Control-Allow-Methods`, +`Access-Control-Allow-Headers` and `Access-Control-Max-Age` from `cors` but no `Access-Control-Allow-Origin`, so a +browser does not act on them (the Fetch standard, "CORS check"). A browser needs no CORS header for a page's own origin, +which it sends with some requests, such as a `POST`, so the gateway admits it. A page on another port or scheme of the +same host is another origin to the browser, which refuses an answer without `Access-Control-Allow-Origin`; to let it +read answers, write its origin in `origins` or `patterns`. Measured on Envoy 1.40.2 with the full example's `live` +environment and `cors`: `https://www.example.com` to `api.example.com`, listed in `origins`, got both headers on its +request and its preflight; `https://api.example.org` to `api.example.org`, and `https://api.example.org:8443` to +`api.example.org:8443`, in neither list, got neither, and their preflights carried the other three. The `max_age` lets a browser keep an admitted preflight, so an origin removed from the file may keep working that long in a browser that cached its preflight. @@ -42,8 +44,44 @@ Each list is sorted in byte order and holds no value twice, so adding or removin | `origins..hosts` | The host names the environment serves, without a port. | Required. A list; each item is text. Not empty. Lower-case host names, such as `api.example.com`. No host is in two environments. | core | | `origins..origins` | The browser origins admitted exactly, each scheme://host\[:port\]. | A list; each item is text. Lower case, `http` or `https`, no path. | core | | `origins..patterns` | The browser origins admitted by pattern, where \* matches any run of characters. | A list; each item is text. A `*` matches dots too. Each is `scheme://host[:port]` with at least one `*`. | core | +| `origins..ask_unlisted` | The service and the path asked about a browser origin that neither origins nor patterns holds, and that is not on one of the hosts; an origin it admits is answered as a listed one. | A service and a path, such as accounts /check. The service needs an `http` port. It is asked before CORS, and sent the `Origin` and `question`: its `200` admits the origin, and any other answer, or none within `1s`, refuses it with the `403` a foreign origin gets. An origin a list or a host admits is never asked about. | core | +| `origins..question` | The question sent to the check ask\_unlisted names, in x-gateway-question. | Letters, digits, dots, - and \_. Needs `ask_unlisted`. Without it the check is sent no `x-gateway-question`. | core | +## An origin no list holds + +A gateway whose customers bring their own domains cannot list every origin. `ask_unlisted` names a service of the +gateway and the path it is asked at, written as `auth.ask` is, and `question` what it is asked: + +```yaml +origins: + live: + hosts: [api.example.com] + origins: ["https://www.example.com"] + ask_unlisted: accounts /auth/origin + question: browser-origin +``` + +A browser request to `live` whose `Origin` is in neither list, and is not on one of the environment's hosts, is then +put to that service before CORS instead of being refused. The gateway sends it a request at the path, with the +`Origin` and, when `question` is written, `x-gateway-question` set to it. Like the auth check's, that request carries +the client's `Host` and method and `Content-Length: 0`, never the client's path or query, and here never its +`Authorization` either: the service is asked about an origin, not a user. The service answers: + +- `200` to admit the origin. The request is then answered as one from a listed origin: its preflight gets `200` with + `Access-Control-Allow-Origin` set to the origin and the rest of `cors`, and any other request goes on to the auth + check, when `auth.ask` is written, and to its service, and its answer carries `Access-Control-Allow-Origin`, a + denial of the auth check's too. +- Anything else to refuse it: the client gets the `403` `Invalid CORS request` a foreign origin gets without the key, + with none of the service's status, headers or body. A `5xx`, and no answer within `1s`, refuse the origin too. + +An origin a list or a host admits, and a request with no `Origin`, are never put to the service, and an environment +that writes no `ask_unlisted` refuses every origin its lists and hosts do not admit, as before. The gateway keeps no +answer: each request from such an origin asks the service again, and a browser keeps an admitted preflight for +`max_age`, as it does a listed origin's. Measured on Envoy 1.40.2, by the scenario "an origin no list holds" of the +[conformance battery](conformance.md). The nginx and HAProxy generators of this version refuse both keys +([Portability](portability.md)). + ## The origins file When `origins` names a file, a relative path is read from the proxyfile's directory, and an absolute path as written. @@ -98,4 +136,6 @@ like this: | `environments[].hosts` | The host names the environment serves, without a port. | Required. A list; each item is text. Not empty. Lower-case host names, such as `api.example.com`. No host is in two environments. | core | | `environments[].origins` | The browser origins admitted exactly, each scheme://host\[:port\]. | A list; each item is text. Lower case, `http` or `https`, no path. | core | | `environments[].patterns` | The browser origins admitted by pattern, where \* matches any run of characters. | A list; each item is text. A `*` matches dots too. Each is `scheme://host[:port]` with at least one `*`. | core | +| `environments[].ask_unlisted` | The service and the path asked about a browser origin that neither origins nor patterns holds, and that is not on one of the hosts; an origin it admits is answered as a listed one. | A service and a path, such as accounts /check. The service needs an `http` port. It is asked before CORS, and sent the `Origin` and `question`: its `200` admits the origin, and any other answer, or none within `1s`, refuses it with the `403` a foreign origin gets. An origin a list or a host admits is never asked about. | core | +| `environments[].question` | The question sent to the check ask\_unlisted names, in x-gateway-question. | Letters, digits, dots, - and \_. Needs `ask_unlisted`. Without it the check is sent no `x-gateway-question`. | core | diff --git a/docs/portability.md b/docs/portability.md index d607d04..a79785c 100644 --- a/docs/portability.md +++ b/docs/portability.md @@ -51,6 +51,7 @@ HAProxy's own OpenTelemetry filter from 3.4 on, where its OpenTracing filter is | `remove_from_clients` | removal by name and by prefix | `proxy_set_header X ""` for each name; no prefix | `http-request del-header`, by name or `-m beg` | core; nginx refuses the prefix form, HAProxy a name or prefix that covers `content-length`, `connection` or `upgrade` | | `cors.*`, `origins..origins`, `.patterns` | the CORS filter | `map` on the `Origin`, `add_header`, a preflight `return 200` | ACLs, `http-request return` for the preflight, `http-after-response set-header` | core | | `origins..hosts` | virtual host domains | `server_name` | `hdr(host)` ACLs and `use_backend` | core | +| `origins..ask_unlisted`, `.question` | an `ext_authz` filter of the environment in shadow mode, before RBAC, on a copy of each route that takes only an origin the environment does not admit, whose RBAC admits the request when the check answered `200` and whose CORS admits any origin | not written by this version's generator: list the origin in `origins` or `patterns` | not written by this version's generator: list the origin in `origins` or `patterns` | core | | `routes[].name` | the route's name, in the logs | none beyond a log variable | the ACL's name | core; nginx keeps it in the log only | | `routes[].prefix`, `.path` | prefix and path matches | `location ^~`, `location =` | `path_beg`, `path` | core | | `routes[].pattern` | RE2 | PCRE, `location ~` | PCRE, `path_reg` | core, on the part of regular-expression syntax the three share | @@ -155,6 +156,8 @@ proxy refuses. | `origins..hosts` | supported | partial: a foreign or empty Origin to a path no route takes gets 403, where Envoy answers 404; refuses holding a host that starts or ends with .: nginx reads a dot at a host's start as every name under it and drops one at its end; write the host without it, or render it for envoy | supported | | `origins..origins` | supported | supported | partial: an admitted Origin longer than 872 bytes less the length of cors.expose\_headers is answered 403 with the body Invalid CORS request before the check and the service, where the Envoy output echoes it: HAProxy has 1,024 bytes for the lines it adds to an answer | | `origins..patterns` | supported | partial: an Origin holding a comma is answered 403, where the Envoy output can match two Origin lines joined with a comma; an Origin longer than 8,192 bytes is not matched against the patterns, so one a pattern would take is refused | partial: an admitted Origin longer than 872 bytes less the length of cors.expose\_headers is answered 403 with the body Invalid CORS request before the check and the service, where the Envoy output echoes it: HAProxy has 1,024 bytes for the lines it adds to an answer | +| `origins..ask_unlisted` | supported | refused: not written by this version's nginx generator; list the origin in origins or patterns, or render it for envoy | refused: not written by this version's HAProxy generator; list the origin in origins or patterns, or render it for envoy | +| `origins..question` | supported | refused: not written by this version's nginx generator; list the origin in origins or patterns, or render it for envoy | refused: not written by this version's HAProxy generator; list the origin in origins or patterns, or render it for envoy | | `routes` | supported | supported | supported | | `routes[].rpc` | supported | supported | supported | | `routes[].rpc.retries` | supported | partial: a call whose method is not POST is not tried again; a service with one backend is not tried again, where the Envoy output tries the same backend; less strict than the Envoy output: a retried request or call is sent again at once and with no limit on retries at the same time | refused: with retry-on at HAProxy's default, a gRPC call whose connection to the service failed was not sent again, and the wider retry-on that sends it also sends again a request a service may have read; leave retries out of the rpc entry, or render it for envoy | diff --git a/docs/routes.md b/docs/routes.md index c92162b..1111852 100644 --- a/docs/routes.md +++ b/docs/routes.md @@ -76,6 +76,9 @@ seconds. - Each limited route has one bucket, shared by its copy in every environment. On the rpc entry, every method the entry routes shares one bucket. A route without `rate_limit` is never limited. +- A limit does not limit the calls to the check of an origin no list holds: an environment that writes `ask_unlisted` + asks it about every request from such an origin before the request reaches a bucket, on a limited route too, so the + check's service carries that load ([An origin no list holds](origins.md#an-origin-no-list-holds)). - With `by: client`, the default, each client address has a bucket of its own: the address [`client_address`](listener.md#the-clients-address) names. With `forwarded`, a client that reaches the gateway directly writes its own `X-Forwarded-For`, and so chooses its own bucket; a gateway on plain HTTP that faces its diff --git a/examples/full/hocon/Proxyfile b/examples/full/hocon/Proxyfile index 435e46c..b5f6e36 100644 --- a/examples/full/hocon/Proxyfile +++ b/examples/full/hocon/Proxyfile @@ -1,5 +1,6 @@ -# Every key but rpc.proto, envoy.tracing, the xray provider, hash.client, nginx and haproxy, in HOCON, with invented -# values. It gives the same envoy.yaml as ../yaml/proxyfile.yaml. +# Every key but rpc.proto, envoy.tracing, the xray provider, hash.client, origins..ask_unlisted +# and question, nginx and haproxy, in HOCON, with invented values. It gives the same envoy.yaml as +# ../yaml/proxyfile.yaml. listen = 10000 admin = 9901 diff --git a/examples/full/yaml/proxyfile.yaml b/examples/full/yaml/proxyfile.yaml index 6d23c43..6d3e3b3 100644 --- a/examples/full/yaml/proxyfile.yaml +++ b/examples/full/yaml/proxyfile.yaml @@ -1,5 +1,5 @@ # yaml-language-server: $schema=../../../schema/proxyfile.schema.json -# Every key but rpc.proto, envoy.tracing, the xray provider, hash.client, nginx and haproxy, with invented values. +# Every key but rpc.proto, envoy.tracing, the xray provider, hash.client, origins..ask_unlisted and question, nginx and haproxy, with invented values. listen: 10000 admin: 9901 tls: diff --git a/internal/envoy/fragments/filter-cors.yaml b/internal/envoy/fragments/filter-cors.yaml index f0112ca..73cfc81 100644 --- a/internal/envoy/fragments/filter-cors.yaml +++ b/internal/envoy/fragments/filter-cors.yaml @@ -1,12 +1,15 @@ # It answers itself every preflight to a route that reaches it, which is every preflight RBAC admits: RBAC, the filter # before it, refuses one from a foreign origin, and each virtual host sets forward_not_matching_preflights to false, so # a preflight from an origin on one of the environment's own hosts, which RBAC admits and the CORS list does not hold, -# is answered too, with no Access-Control-Allow-Origin. So none reaches a service or ext_authz. On every other answer -# to an origin its list holds it sets Access-Control-Allow-Origin and, when cors sets expose_headers, -# Access-Control-Expose-Headers, replacing any the service sent (Envoy 1.40.2, cors_filter.cc); an origin the list -# does not hold gets neither, also when it is the request's own host and port. The policy is per virtual host. Its -# max_age lets a browser cache an admitted preflight, so an origin taken off its environment's list may keep working -# that long in a browser that cached its preflight. +# is answered too, with no Access-Control-Allow-Origin. So none reaches a service or the auth check's ext_authz; only +# the preflight of an origin no list holds, in an environment that writes ask_unlisted, has been put to that +# environment's check, before RBAC (filter-unlisted-origin.yaml). On every other answer to an origin its list holds it +# sets Access-Control-Allow-Origin and, when cors sets expose_headers, Access-Control-Expose-Headers, replacing any the +# service sent (Envoy 1.40.2, cors_filter.cc); an origin the list does not hold gets neither, also when it is the +# request's own host and port, unless that check admitted it: the copy of the route such an origin takes sets a policy +# of its own, which holds any origin, as only one the check admitted gets past RBAC there (route-unlisted-origin.yaml). +# The policy is per virtual host, and per route on those copies. Its max_age lets a browser cache an admitted preflight, +# so an origin taken off its environment's list may keep working that long in a browser that cached its preflight. name: envoy.filters.http.cors typed_config: "@type": type.googleapis.com/envoy.extensions.filters.http.cors.v3.Cors diff --git a/internal/envoy/fragments/filter-rbac.yaml b/internal/envoy/fragments/filter-rbac.yaml index 5d68282..f0345ae 100644 --- a/internal/envoy/fragments/filter-rbac.yaml +++ b/internal/envoy/fragments/filter-rbac.yaml @@ -1,7 +1,10 @@ # A browser origin the request's virtual host does not admit is refused here with 403, preflight, request and # WebSocket upgrade alike, before CORS, ext_authz or any upstream sees it; a request without an Origin header passes. -# The rules are per virtual host, so per environment of the origins; this filter has none of its own, and without -# rules it enforces nothing (Envoy 1.40.2, rbac.proto: "If absent, no RBAC enforcement occurs"). +# The exception is an environment that writes ask_unlisted: it puts such an origin to its check first, before this +# filter, and the copy of the route the request takes admits it here when the check answered OK +# (filter-unlisted-origin.yaml, route-unlisted-origin.yaml). The rules are per virtual host, so per environment of the +# origins, and those copies carry rules of their own; this filter has none of its own, and without rules it enforces +# nothing (Envoy 1.40.2, rbac.proto: "If absent, no RBAC enforcement occurs"). name: envoy.filters.http.rbac typed_config: "@type": type.googleapis.com/envoy.extensions.filters.http.rbac.v3.RBAC diff --git a/internal/envoy/fragments/filter-unlisted-origin.yaml b/internal/envoy/fragments/filter-unlisted-origin.yaml new file mode 100644 index 0000000..e6a6e0d --- /dev/null +++ b/internal/envoy/fragments/filter-unlisted-origin.yaml @@ -0,0 +1,39 @@ +# The check of one environment that writes ask_unlisted: a gateway whose customers bring their own domains cannot list +# every origin, so a browser origin the environment does not admit by its lists or its hosts is put to a service of +# the gateway, asked in HTTP mode as auth.ask's check is (filter-ext-authz.yaml). +# +# It is off on every route but the copies its environment adds for such an origin (route-unlisted-origin.yaml), each of +# which turns it on by this filter's name: a FilterConfig entry turns on, for its route, a filter the listener's list +# writes as disabled (Envoy 1.40.2, http_filters.rst, "Disabled flag based route filter chain"). +# +# In shadow mode the filter never answers the client itself: it keeps the check's decision in the request's filter +# state under its own name and .shadow (ext_authz.proto, shadow_mode), and RBAC, the filter after it, admits the +# request only when that decision is OK. So an origin the check refuses, or does not answer within the time below, or +# answers with a 5xx, is refused by RBAC with the 403 a foreign origin gets without the key, which the listener's local +# reply mapper answers Invalid CORS request (listener.yaml). The check's status and headers never reach the client +# (measured on Envoy 1.40.2: the check's 401 with a JSON body and a header of its own gave the client 403 as +# text/plain without that header), and shadow mode keeps no body of the check's (ext_authz.proto, ShadowDecision). +name: {{q .Name}} +disabled: true +typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthz + http_service: + # ext_authz reads only the cluster and the timeout here; the uri is a required field it never sends. + server_uri: {uri: {{q .URI}}, cluster: {{q .Cluster}}, timeout: {{.Timeout}}} + # The check is asked at its own path, never at the client's. + path_override: {{q .Path}} +{{- with .Question}} + # headers_to_add sets the question over any copy a client sent. + authorization_request: + headers_to_add: [{key: x-gateway-question, value: {{q .}}}] +{{- end}} + shadow_mode: true + # The Origin is what the check decides on. HTTP mode also always sends the Host, the method and the path above, and + # the client's Authorization, which disallowed_headers keeps from the check: it is asked about an origin, not a user + # (check_request_utils.cc, toRequestMatchers; disallowed_headers overrides allowed_headers, ext_authz.proto). + allowed_headers: + patterns: + - exact: origin + disallowed_headers: + patterns: + - exact: authorization diff --git a/internal/envoy/fragments/route-unlisted-origin.yaml b/internal/envoy/fragments/route-unlisted-origin.yaml new file mode 100644 index 0000000..f7b8db8 --- /dev/null +++ b/internal/envoy/fragments/route-unlisted-origin.yaml @@ -0,0 +1,45 @@ +# What an environment that writes ask_unlisted adds to its copy of a route (unlistedRoutes in generate.go), merged into +# the route as written. +# +# The copy takes only a request that carries an Origin none of the principals of the virtual host's RBAC rules admits +# (virtual-host.yaml): every header matcher here must match (route_components.proto, RouteMatch.headers), and each but +# the first is one of those principals inverted, written from the same lists. So an origin admitted without the key, +# by a list or as one of the environment's own hosts, never takes the copy and is never put to the check, and an +# origin refused without the key always does. A request with no Origin fails the first matcher. +match: + headers: + - {name: origin, present_match: true} +{{- range .SameOrigin}} + - {name: origin, string_match: {safe_regex: {regex: {{q .}}}}, invert_match: true} +{{- end}} +{{- range .Origins}} + - {name: origin, string_match: {exact: {{q .}}, ignore_case: true}, invert_match: true} +{{- end}} +{{- range .Patterns}} + - {name: origin, string_match: {safe_regex: {regex: {{q .}}}}, invert_match: true} +{{- end}} +# A route's own entry for a filter takes the place of its virtual host's (Envoy 1.40.2, http_filters.rst, "Route +# specific config"). +typed_per_filter_config: + # The environment's check, which the listener's list writes as disabled, runs on the copy. + {{q .Check}}: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}} + # RBAC admits the request only when the check's decision is OK: in the filter state, its JSON starts with + # {"check_result":"OK" (ext_authz's ShadowDecision, written with the proto's own field names). An OK decision is + # the check's 200; a refusal, a 5xx and no answer in time are DENIED or ERROR, and a request the check never + # decided has no decision, so RBAC refuses each. + envoy.filters.http.rbac: + "@type": type.googleapis.com/envoy.extensions.filters.http.rbac.v3.RBACPerRoute + rbac: + rules: + action: ALLOW + policies: + admitted-by-the-check: + permissions: [{any: true}] + principals: [{filter_state: {key: {{q .Decision}}, string_match: {prefix: "{\"check_result\":\"OK\""}}}] + # Only an origin the check admitted reaches CORS on the copy, so CORS admits any origin there: it answers the + # preflight and sets Access-Control-Allow-Origin to the origin, as for a listed one. The other settings, methods, + # headers, max_age and forward_not_matching_preflights among them, are the virtual host's: the CORS filter takes + # each from the route's policy when it sets it, and from the virtual host's otherwise (cors_filter.cc). + envoy.filters.http.cors: + "@type": type.googleapis.com/envoy.extensions.filters.http.cors.v3.CorsPolicy + allow_origin_string_match: [{safe_regex: {regex: ".*"}}] diff --git a/internal/envoy/fragments/virtual-host.yaml b/internal/envoy/fragments/virtual-host.yaml index 8730254..17797da 100644 --- a/internal/envoy/fragments/virtual-host.yaml +++ b/internal/envoy/fragments/virtual-host.yaml @@ -1,7 +1,8 @@ # One virtual host per environment of the origins, written in the proxyfile or in an origins file. Each key of # typed_per_filter_config names an http filter by its name in the listener's list (Envoy 1.40.2, http_filters.rst, # "Route specific config"). No route sets its own for these two filters, so these settings hold for every route of -# the virtual host. +# the virtual host, but the copies an environment that writes ask_unlisted adds for an origin no list holds, which set +# both (route-unlisted-origin.yaml). name: {{q .Name}} domains: [{{range $i, $host := .Hosts}}{{if $i}}, {{end}}{{q $host}}{{end}}] typed_per_filter_config: diff --git a/internal/envoy/generate.go b/internal/envoy/generate.go index 079d495..105c719 100644 --- a/internal/envoy/generate.go +++ b/internal/envoy/generate.go @@ -7,6 +7,7 @@ import ( "embed" "errors" "fmt" + "maps" "net" "slices" "strconv" @@ -34,29 +35,43 @@ var fragments embed.FS var connectStatus string // The filters, in order: set_metadata, the header mutation (Vary on every answer, and each RPC route's question for the -// check), the RBAC refusal of a foreign browser origin, CORS, the rate limit (with a rate_limit), the token filter -// (with auth.jwt), ext_authz (with auth.ask), the Lua filter that corrects the status of the bridge's errors and the -// Connect-gRPC bridge (both with envoy.connect_bridge), the router. A foreign origin is refused before ext_authz could -// call the check; a browser's preflight carries no authorization, because it sends only the names of the request's own -// headers (the Fetch standard, "CORS-preflight fetch"), and it is answered before the token filter and ext_authz in -// any case. A request over a limit is refused before its token is verified and before ext_authz could call the check, -// and a token is verified before the check is asked (measured on Envoy 1.40.2); the limit also runs before the bridge, -// which removes the connect-protocol-version header the Connect answer to it is matched on -// (connect_grpc_bridge/filter.cc). +// check), the check of each environment that writes ask_unlisted, the RBAC refusal of a foreign browser origin, CORS, +// the rate limit (with a rate_limit), the token filter (with auth.jwt), ext_authz (with auth.ask), the Lua filter that +// corrects the status of the bridge's errors and the Connect-gRPC bridge (both with envoy.connect_bridge), the router. +// An origin no list holds is put to its environment's check before RBAC, which reads the check's answer +// (filter-unlisted-origin.yaml). A foreign origin is refused before ext_authz could call the check; a browser's +// preflight carries no authorization, because it sends only the names of the request's own headers (the Fetch +// standard, "CORS-preflight fetch"), and it is answered before the token filter and ext_authz in any case. A request +// over a limit is refused before its token is verified and before ext_authz could call the check, and a token is +// verified before the check is asked (measured on Envoy 1.40.2); the limit also runs before the bridge, which removes +// the connect-protocol-version header the Connect answer to it is matched on (connect_grpc_bridge/filter.cc). var httpFilters = []struct { fragment string - present func(g *model.Gateway) bool // whether a gateway has the filter + // copies gives the fragment's data for each copy of the filter a gateway has, none when it has none, from the data + // every filter shares. + copies func(in generator.Input, shared data) []data }{ - {"filter-set-metadata.yaml", hasAuth}, - {"filter-header-mutation.yaml", always}, - {"filter-rbac.yaml", always}, - {"filter-cors.yaml", always}, - {"filter-local-ratelimit.yaml", hasRateLimit}, - {"filter-jwt-authn.yaml", hasJWT}, - {"filter-ext-authz.yaml", hasAuth}, - {"filter-lua.yaml", hasBridge}, - {"filter-connect-bridge.yaml", hasBridge}, - {"filter-router.yaml", always}, + {"filter-set-metadata.yaml", once(hasAuth)}, + {"filter-header-mutation.yaml", once(always)}, + {"filter-unlisted-origin.yaml", unlistedChecks}, + {"filter-rbac.yaml", once(always)}, + {"filter-cors.yaml", once(always)}, + {"filter-local-ratelimit.yaml", once(hasRateLimit)}, + {"filter-jwt-authn.yaml", once(hasJWT)}, + {"filter-ext-authz.yaml", once(hasAuth)}, + {"filter-lua.yaml", once(hasBridge)}, + {"filter-connect-bridge.yaml", once(hasBridge)}, + {"filter-router.yaml", once(always)}, +} + +// once is the copies of a filter a gateway has at most one of, which present says it has, filled with the shared data. +func once(present func(g *model.Gateway) bool) func(generator.Input, data) []data { + return func(in generator.Input, shared data) []data { + if !present(in.Gateway) { + return nil + } + return []data{shared} + } } func always(*model.Gateway) bool { return true } @@ -99,19 +114,23 @@ func Generate(in generator.Input) ([]generator.File, error) { clusters = append(clusters, b.fill("cluster.yaml", keysCluster(g))) } // Every virtual host holds the same routes, so they share one node, which the encoder writes out in full at each - // place. + // place; an environment that writes ask_unlisted holds them too, among routes of its own (unlistedRoutes). sharedRoutes := sequence(b.routes(in)...) var virtualHosts []*yaml.Node for _, environment := range in.Origins.Environments { + routes := sharedRoutes + if environment.AskUnlisted != nil { + routes = b.unlistedRoutes(in, environment, sharedRoutes) + } virtualHosts = append(virtualHosts, - b.fill("virtual-host.yaml", virtualHost(environment, in.Origins.CORS), splice{"routes", sharedRoutes})) + b.fill("virtual-host.yaml", virtualHost(environment, in.Origins.CORS), splice{"routes", routes})) } filterValues := data{"Namespace": g.Envoy.Namespace, "Check": check(g), "JWT": jwt(g), "Script": connectStatus, "RateLimitNamespace": rateLimitNamespace(g.Envoy.Namespace), "Buckets": generator.Buckets(g)} var filters []*yaml.Node for _, filter := range httpFilters { - if filter.present(g) { - filters = append(filters, b.fill(filter.fragment, filterValues)) + for _, values := range filter.copies(in, filterValues) { + filters = append(filters, b.fill(filter.fragment, values)) } } logs := []*yaml.Node{ @@ -355,8 +374,6 @@ func check(g *model.Gateway) data { if a == nil { return nil } - service := g.Service(a.Service.Value) - port, _ := service.Port(model.HTTP) // Under connection every connection the listener takes is of one scheme, which the check is told in place of the // one the client wrote (filter-ext-authz.yaml); under forwarded it stays empty, and the request's own is told. var connectionScheme string @@ -366,12 +383,8 @@ func check(g *model.Gateway) data { connectionScheme = "https" } } - return data{ - // JoinHostPort writes an IPv6 address in brackets, as a URI needs it. ext_authz never sends the uri, so the first - // backend names it whatever the number of backends. - "URI": "http://" + net.JoinHostPort(service.Addresses[0].Value, strconv.FormatInt(port.Number, 10)) + a.Path, - "Cluster": service.Cluster(model.HTTP), - "Path": a.Path, + values := asked(g, a.Service.Value, a.Path) + maps.Copy(values, data{ "Timeout": model.FormatSeconds(a.Timeout.Millis), "TimeoutMillis": a.Timeout.Millis, "Enabled": a.Enabled, @@ -381,7 +394,101 @@ func check(g *model.Gateway) data { "Accept": a.Accept, "SendRequest": a.SendRequest, "ConnectionScheme": connectionScheme, + }) + return values +} + +// asked is the part of a check filter's data that names what it asks: the server_uri's uri and cluster, and the path. +// The read rules have made the service a declared one with an http port. JoinHostPort writes an IPv6 address in +// brackets, as a URI needs it. ext_authz never sends the uri, so the first backend names it whatever the number of +// backends. +func asked(g *model.Gateway, serviceName, path string) data { + service := g.Service(serviceName) + port, _ := service.Port(model.HTTP) + return data{ + "URI": "http://" + net.JoinHostPort(service.Addresses[0].Value, strconv.FormatInt(port.Number, 10)) + path, + "Cluster": service.Cluster(model.HTTP), + "Path": path, + } +} + +// unlistedCheck names the check filter of an environment that writes ask_unlisted. Filter names are unique in the +// listener's list, and each environment's routes turn on their own check by this name. +func unlistedCheck(environment origins.Environment) string { + return "ask_unlisted:" + environment.Name +} + +// unlistedChecks is the data of the check filter of each environment that writes ask_unlisted, in the environments' +// order: the service and the path it asks, the question, and the time it waits. +func unlistedChecks(in generator.Input, _ data) []data { + var copies []data + for _, environment := range in.Origins.Environments { + ask := environment.AskUnlisted + if ask == nil { + continue + } + values := asked(in.Gateway, ask.Service.Value, ask.Path) + maps.Copy(values, data{"Name": unlistedCheck(environment), "Question": ask.Question, + "Timeout": model.FormatSeconds(model.UnlistedCheckMillis)}) + copies = append(copies, values) + } + return copies +} + +// unlistedRoutes is the route list of an environment that writes ask_unlisted: the refused route, then a copy of each +// other route of shared that takes only a request from a browser origin the environment does not admit and asks the +// environment's check about it (route-unlisted-origin.yaml), then the rest of shared as every virtual host holds it. +// Envoy uses the first route that matches, so such a request takes the copy of the route it would take otherwise, and +// any other request the route itself. The copies are filled anew, because the shared nodes are written at every place +// that holds them. +func (b *builder) unlistedRoutes(in generator.Input, environment origins.Environment, shared *yaml.Node) *yaml.Node { + values := virtualHost(environment, in.Origins.CORS) + values["Check"] = unlistedCheck(environment) + // ext_authz in shadow mode keeps its decision in the filter state under its own name and .shadow (ext_authz.proto, + // shadow_mode). + values["Decision"] = unlistedCheck(environment) + ".shadow" + copies := b.routes(in)[1:] + for _, route := range copies { + if err := merge(route, b.fill("route-unlisted-origin.yaml", values)); err != nil && b.err == nil { + b.err = fmt.Errorf("fragment route-unlisted-origin.yaml: %w", err) + } + } + return sequence(slices.Concat(shared.Content[:1], copies, shared.Content[1:])...) +} + +// merge adds the mapping from to the mapping into: a key into lacks is added with its value, a list under a key both +// hold gets from's items after its own, and a mapping under a key both hold is merged in turn. A scalar under a key +// both hold is an error, so no part of a route is overwritten. +func merge(into, from *yaml.Node) error { + if into == nil || from == nil || into.Kind != yaml.MappingNode || from.Kind != yaml.MappingNode { + return errors.New("only a mapping merges into a mapping") + } + for i := 0; i < len(from.Content); i += 2 { + key, value := from.Content[i], from.Content[i+1] + held := valueOf(into, key.Value) + switch { + case held == nil: + into.Content = append(into.Content, key, value) + case held.Kind == yaml.SequenceNode && value.Kind == yaml.SequenceNode: + held.Content = append(held.Content, value.Content...) + default: + if err := merge(held, value); err != nil { + return fmt.Errorf("%s: %w", key.Value, err) + } + } } + return nil +} + +// valueOf returns the value of key in a mapping node, or nil when the mapping does not hold the key. A mapping's +// Content holds its keys and values in turn. +func valueOf(mapping *yaml.Node, key string) *yaml.Node { + for i := 0; i+1 < len(mapping.Content); i += 2 { + if mapping.Content[i].Value == key { + return mapping.Content[i+1] + } + } + return nil } // jwt is the token filter's data, nil without auth.jwt. The authorization header carries the token after the Bearer diff --git a/internal/format/check_test.go b/internal/format/check_test.go index cc53c45..db2ea4a 100644 --- a/internal/format/check_test.go +++ b/internal/format/check_test.go @@ -228,7 +228,7 @@ func TestCheck(t *testing.T) { // The key is the environment's name, so the name key of an origins file's environment is not known here. {name: "environment with a name key", spec: Proxyfile, document: m.Replaced(4, 4, "origins:", " all: {hosts: [localhost], name: all}"), - want: []string{`g.yaml:5:29: unknown key "name"; known here: hosts, origins, patterns`}}, + want: []string{`g.yaml:5:29: unknown key "name"; known here: ask_unlisted, hosts, origins, patterns, question`}}, {name: "cors max_age a number", spec: Proxyfile, document: m.Replaced(4, 4, "cors: {max_age: 600}", "origins:", " all: {hosts: [localhost]}"), want: []string{`g.yaml:4:17: "max_age" must be text; quote it`}}, diff --git a/internal/format/spec.go b/internal/format/spec.go index cf54a06..06c6e67 100644 --- a/internal/format/spec.go +++ b/internal/format/spec.go @@ -90,6 +90,10 @@ const ( // A header named exactly, for the rules that take no prefix: auth.only_with_header and a tracing tag's header. lowerHeaderPattern = `^[a-z0-9][a-z0-9-]*$` lowerHeaderExpect = "a lower-case header name" + // A key that names a check: one service name, one space and a path, as auth.ask and an environment's ask_unlisted + // write it. The reader splits the value at the space (model.SplitAsk). + askPattern = `^[a-z][a-z0-9-]* /[^\t\n\f\r ]*$` + askExpect = "a service and a path, such as accounts /check" // Envoy 1.40.2 holds these whole numbers in a uint32 and refuses a larger value when it loads the file: // max_headers_count (protocol.proto), which limits.request_headers.count is written to; the circuit breakers' // max_connections, max_pending_requests and max_requests (circuit_breaker.proto), which limits.connections is @@ -134,6 +138,11 @@ func path(name, doc string) Field { return Field{Name: name, Doc: doc, Kind: Text, Pattern: `^/`, Expect: "a path starting with /"} } +// ask is a key that names a check, a service and the path it is asked at; the rules give the service an http port. +func ask(name, doc string) Field { + return Field{Name: name, Doc: doc, Kind: Text, Pattern: askPattern, Expect: askExpect, Rule: "The service needs an `http` port."} +} + // absolutePath is a file the proxy reads on its host. It is absolute, so what the file names never depends on the // directory the proxy starts in. func absolutePath(name, doc string, required bool) Field { @@ -269,8 +278,7 @@ var Proxyfile = Field{ // AtLeastOneOf and authNeeds say so for the schema, and each key's Rule for the key tables. {Name: "auth", Doc: "The checks every request goes through before it reaches a service: a service of yours asked about each request, " + "a signed token the proxy verifies, or both.", Kind: Map, Rule: "At least one of `ask` and `jwt`. Without `auth` there is no check.", AtLeastOneOf: []string{"ask", "jwt"}, Needs: authNeeds, Fields: []Field{ - {Name: "ask", Doc: "The service and the path the gateway asks.", Kind: Text, - Pattern: `^[a-z][a-z0-9-]* /[^\t\n\f\r ]*$`, Expect: "a service and a path, such as accounts /check", Rule: "The service needs an `http` port."}, + ask("ask", "The service and the path the gateway asks."), {Name: "timeout", Doc: "How long the gateway waits for the answer.", Kind: Text, Pattern: model.TimePattern, Expect: "a time such as 2s", Rule: "Required with `ask`, and refused without it. At most `4294967295s`. `none` is not accepted."}, {Name: "enabled", Doc: "true runs the check on every request it applies to, false on none.", Kind: Bool, @@ -296,7 +304,8 @@ var Proxyfile = Field{ Kind: Either, Required: true, Expect: "a mapping of environments by name, or a file name", Rule: "At least one environment.", Choices: []Field{ {Kind: Text, Pattern: `^[^\t\n\f\r ]+$`, Expect: "a file name"}, {Kind: Dict, Key: &Field{Name: "environment name", Kind: Text, Pattern: `[\s\S]`, Expect: "one character or more"}, - Item: &Field{Doc: "One environment: its hosts and the browser origins it admits.", Kind: Map, Fields: environmentLists}}, + Item: &Field{Doc: "One environment: its hosts and the browser origins it admits.", Kind: Map, Fields: environmentLists, + Needs: environmentNeeds}}, }}, {Name: "routes", Doc: "The routes, tried in the order written; the rpc entry marks where the RPC routes go.", Kind: List, Required: true, Rule: "Not empty. The rpc entry is `- rpc:` in YAML and `{ rpc { ... } }` in HOCON.", @@ -542,7 +551,22 @@ var ( "Lower case, `http` or `https`, no path."), withRule(texts("patterns", "The browser origins admitted by pattern, where * matches any run of characters.", false), "A `*` matches dots too. Each is `scheme://host[:port]` with at least one `*`."), + // A gateway whose customers bring their own domains cannot list them all, so it asks a service of its own about + // an origin no list holds. + withRule(ask("ask_unlisted", "The service and the path asked about a browser origin that neither origins nor patterns holds, "+ + "and that is not on one of the hosts; an origin it admits is answered as a listed one."), + "The service needs an `http` port. It is asked before CORS, and sent the `Origin` and `question`: its `200` admits "+ + "the origin, and any other answer, or none within `"+model.FormatSeconds(model.UnlistedCheckMillis)+"`, refuses it "+ + "with the `403` a foreign origin gets. An origin a list or a host admits is never asked about."), + // The question is a header value, which Envoy's check writes through its substitution formatter, where a % starts + // a command, so it keeps to the characters of a route's name. + {Name: "question", Doc: "The question sent to the check ask_unlisted names, in x-gateway-question.", + Kind: Text, Pattern: routeNamePattern, Expect: routeNameExpect, + Rule: "Needs `ask_unlisted`. Without it the check is sent no `x-gateway-question`."}, } + // environmentNeeds says, for the schema, that question needs ask_unlisted beside it; the origins reader refuses the + // same in its own words. + environmentNeeds = map[string][]string{"question": {"ask_unlisted"}} ) // The rules for hosts, origins and patterns belong to the origins reader, which names the environment in its @@ -555,7 +579,7 @@ var Origins = Field{ corsField, {Name: "environments", Doc: "The environments, each with its hosts and the browser origins it admits.", Kind: List, Required: true, Rule: "At least one environment.", - Item: &Field{Doc: "One environment.", Kind: Map, Place: "origins.", Fields: slices.Concat([]Field{ + Item: &Field{Doc: "One environment.", Kind: Map, Place: "origins.", Needs: environmentNeeds, Fields: slices.Concat([]Field{ {Name: "name", Doc: "The environment's name.", Kind: Text, Required: true, Place: "origins.", Rule: "It names the environment's virtual host. Not empty, and not used by another environment."}, }, environmentLists)}}, diff --git a/internal/format/support_haproxy.go b/internal/format/support_haproxy.go index 8638ed5..b0e2aa6 100644 --- a/internal/format/support_haproxy.go +++ b/internal/format/support_haproxy.go @@ -20,6 +20,10 @@ var ( // addon built outside HAProxy's source tree, and the OpenTracing filter is not compiled into the images either. haproxyNoTracing = Support{Level: Refused, Note: "the official HAProxy images have no tracing filter (the OpenTelemetry filter is an addon built from source); remove tracing, or render it for envoy"} + // haproxyNoUnlistedCheck is the declaration of an environment's ask_unlisted and its question: HAProxy decides an + // origin by ACLs before its check action runs, and this version asks no check before that decision. + haproxyNoUnlistedCheck = Support{Level: Refused, + Note: "not written by this version's HAProxy generator; list the origin in origins or patterns, or render it for envoy"} // haproxyNoZone is what HAProxy says of a server address that carries an IPv6 zone, such as fe80::1%eth0: the reader // takes it as an IP address (netip.ParseAddr), and HAProxy refuses to load it in a server line ("could not resolve // address", measured on HAProxy 3.2.26 and 3.4.7, with the brackets and without them). @@ -324,6 +328,8 @@ var haproxyTarget = Target{Name: "haproxy", Title: "HAProxy", Keys: map[string]S Note: "an admitted Origin longer than 872 bytes less the length of cors.expose_headers is answered 403 with the body Invalid CORS request before the check and the service, where the Envoy output echoes it: HAProxy has 1,024 bytes for the lines it adds to an answer"}, "origins..patterns": {Level: Partial, Note: "an admitted Origin longer than 872 bytes less the length of cors.expose_headers is answered 403 with the body Invalid CORS request before the check and the service, where the Envoy output echoes it: HAProxy has 1,024 bytes for the lines it adds to an answer"}, + "origins..ask_unlisted": haproxyNoUnlistedCheck, + "origins..question": haproxyNoUnlistedCheck, "routes": {Level: Supported}, "routes[].rpc": {Level: Supported}, diff --git a/internal/format/support_nginx.go b/internal/format/support_nginx.go index 6b96e67..f9a29b1 100644 --- a/internal/format/support_nginx.go +++ b/internal/format/support_nginx.go @@ -30,6 +30,10 @@ var ( Note: "not read: open-source nginx sends no check request (health_check is NGINX Plus's), so its passive check reads the service's own requests"} nginxNoJWT = Support{Level: Refused, Note: "nginx open source cannot verify a token (nginx Plus's auth_jwt); verify it in the service, or render it for envoy"} + // nginxNoUnlistedCheck is the declaration of an environment's ask_unlisted and its question: nginx decides an origin + // by a map before its locations, and this version's script asks no check before that decision. + nginxNoUnlistedCheck = Support{Level: Refused, + Note: "not written by this version's nginx generator; list the origin in origins or patterns, or render it for envoy"} // The official images hold one tracer, ngx_otel_module, in the images tagged -otel, which exports OTLP alone (the // modules folder of nginx 1.31.8-otel holds no other). nginxNoXRay = Support{Level: Refused, @@ -556,6 +560,8 @@ var nginxTarget = Target{Name: "nginx", Title: "nginx", Keys: map[string]Support // request should take (the generator's longestMatchedOrigin). "origins..patterns": {Level: Partial, Note: "an Origin holding a comma is answered 403, where the Envoy output can match two Origin lines joined with a comma; an Origin longer than 8,192 bytes is not matched against the patterns, so one a pattern would take is refused"}, + "origins..ask_unlisted": nginxNoUnlistedCheck, + "origins..question": nginxNoUnlistedCheck, "routes": {Level: Supported}, "routes[].rpc": {Level: Supported}, diff --git a/internal/format/support_test.go b/internal/format/support_test.go index 5d0538d..77a1b68 100644 --- a/internal/format/support_test.go +++ b/internal/format/support_test.go @@ -39,7 +39,7 @@ func TestCoreKeys(t *testing.T) { name string got, want any }{ - {name: "the count", got: len(full), want: 129}, + {name: "the count", got: len(full), want: 131}, {name: "the first", got: first, want: "listen"}, {name: "the last", got: last, want: "tracing.path_in_url"}, {name: "a key of a Dict's value", got: slices.Contains(full, "services..http"), want: true}, @@ -954,7 +954,8 @@ func TestHAProxyWrites(t *testing.T) { note: "over HTTP/1.1 an absolute target is answered 400, where Envoy routes it by its host and sends the path alone with that host as Host, or answers 404 when no environment has the host, and OPTIONS * and CONNECT are answered 400, where Envoy answers 404; a request line with no version, HTTP/0.9's form, is answered 400, where Envoy answers 426; after its 426 to HTTP/1.0 asking for keep-alive or to HTTP/1.2 to HTTP/1.9, and after its 403 to an upgrade other than WebSocket, from any origin, HAProxy keeps the connection and serves the next request on it, where Envoy closes it; a Connection token other than close, keep-alive, upgrade, HTTP2-Settings and te is answered 400, where Envoy removes the header the token names and serves the request; ten Connection elements or more, an empty one counted but for an empty last one, are answered 400, where Envoy counts no empty element and serves a token with ten; an h2c upgrade is answered 400, where Envoy serves it as a plain request; a header line folded onto the next, and a header value that holds three spaces or tabs in a row, are answered 400, where Envoy serves them; over HTTP/2 a cookie field that starts with two spaces or tabs, as one of spaces alone does, or ends with three is answered 400 too, where Envoy serves it, as HAProxy keeps the spaces around a cookie field's value and drops them around any other field's; a WebSocket upgrade with no Sec-WebSocket-Key is answered 400, where Envoy passes it on, or answers 403 to an origin it does not admit; more than 100 header lines are answered 431 or, from 102, 400, where Envoy answers 431, and 101 lines or more of a header Envoy joins into one line are answered 400, where Envoy serves them; two Host lines of different hosts, and a Host that holds a comma, are answered 400, where Envoy answers 404; Transfer-Encoding: chunked on two lines is answered 400, and Transfer-Encoding: gzip, chunked 422, where Envoy answers 501; a request line and header lines of more than 15,277 bytes together, counted as sent with their line ends, Host alone beside the line and 4 bytes fewer for each further header line (3.4.7: 8 bytes more), are answered 431, and a request line of 16,319 bytes or more (3.4.7: 16,327) 414, where Envoy serves both up to its default limit of 60 KiB; over HTTP/2 a request with 97 header fields or more is answered 400, where Envoy resets its stream, and so is one with fewer whose cookies, counted one a field, reach 97, and one with 97 fields or more of a header Envoy joins, which Envoy serves, is answered 400 or, with 120, its stream reset; a WebSocket, an extended CONNECT, is answered 400, where Envoy closes the connection; a path whose escaped form outgrows HAProxy's buffer, such as one of 7000 bytes above 0x7F, is answered 400 by HAProxy 3.4.7 and 500 by 3.2.26, where Envoy serves it; a header or trailer name outside RFC 9110's token characters resets the stream, where Envoy closes the connection; a # in :path resets the stream, where Envoy answers 400; and a request with neither :authority nor host is answered 404, where Envoy closes the connection; over HTTP/1.1 a request trailer whose name is outside those characters ends the connection with no answer when the body comes after the headers, where Envoy answers 400; over HTTP/2 a QUERY whose content-type field is spaces alone is answered 400, where Envoy serves it: HAProxy reads an HTTP/2 value of spaces alone as empty, and Envoy answers 400 to a QUERY with no Content-Type or an empty one"}, } wantRefused := map[string][]string{ - + "not written by this version's HAProxy generator; list the origin in origins or patterns, or render it for envoy": { + "origins..ask_unlisted", "origins..question"}, "with retry-on at HAProxy's default, a gRPC call whose connection to the service failed was not sent again, and the wider retry-on that sends it also sends again a request a service may have read; leave retries out of the rpc entry, or render it for envoy": { "routes[].rpc.retries"}, "HAProxy has no gRPC health check: http-check send writes a text body, not the health service's gRPC message; write health.path on the service's http port": { diff --git a/internal/model/model.go b/internal/model/model.go index 8b38a75..99e4321 100644 --- a/internal/model/model.go +++ b/internal/model/model.go @@ -167,6 +167,18 @@ type Auth struct { SendRequest bool // send_request: true, which tells the check the request's path, method, scheme and host } +// SplitAsk splits a value the check's pattern for a service and a path accepted, auth.ask's or an environment's +// ask_unlisted: one service name, one space and the path. +func SplitAsk(text string) (service, path string) { + service, path, _ = strings.Cut(text, " ") + return service, path +} + +// UnlistedCheckMillis is how long the gateway waits for the check an environment's ask_unlisted names. The key takes +// no time of its own, and a browser's preflight waits on the check, so the wait is short; an origin the check has not +// answered by then is refused. +const UnlistedCheckMillis = 1000 + // JWT is auth.jwt: the proxy verifies a signed token on each request itself. type JWT struct { Issuer string diff --git a/internal/origins/origins.go b/internal/origins/origins.go index aa0d042..0437c16 100644 --- a/internal/origins/origins.go +++ b/internal/origins/origins.go @@ -31,9 +31,18 @@ type CORS struct { type Environment struct { Name string Hosts, Origins, Patterns []string // nil when not written or empty + AskUnlisted *Check // nil when ask_unlisted is not written Pos model.Pos // the environment's mapping in an origins file; its key in the proxyfile } +// Check is an environment's ask_unlisted: the service and the path asked about a browser origin that the environment's +// lists and hosts do not admit, and the question it is asked. +type Check struct { + Service model.Text // at the position of ask_unlisted's value, which the rule of a declared service names + Path string + Question string // "" when question is not written +} + // Listed says whether the environment admits origins by a list, origins or patterns: only such an environment answers // a browser with CORS headers, so each generator writes those lines for it alone. func (e Environment) Listed() bool { @@ -169,16 +178,32 @@ func (r *reader) environments(holder *tree.Node, none string, list []writtenEnvi } r.hostsOnce(i, name, hosts) environments = append(environments, Environment{ - Name: name, - Hosts: r.values(name, item, hostList), - Origins: r.values(name, item, originList), - Patterns: r.values(name, item, patternList), - Pos: w.pos, + Name: name, + Hosts: r.values(name, item, hostList), + Origins: r.values(name, item, originList), + Patterns: r.values(name, item, patternList), + AskUnlisted: r.check(name, item), + Pos: w.pos, }) } return environments } +// check reads an environment's ask_unlisted with its question, nil when ask_unlisted is not written. A question with +// no check to ask it of is refused, as a key of the auth check is without auth.ask. Whether the service is declared is +// read against the proxyfile's services, which an origins file does not hold (read.OriginChecks). +func (r *reader) check(environment string, item *tree.Node) *Check { + ask := item.Get("ask_unlisted") + if ask == nil { + if question := item.Entry("question"); question != nil { + r.Add(question.KeyPos, "environment %q: question is written, but ask_unlisted is not", environment) + } + return nil + } + service, path := model.SplitAsk(ask.Text) + return &Check{Service: model.Text{Value: service, Pos: ask.Pos}, Path: path, Question: item.GetText("question")} +} + // values returns the texts of one list of an environment, after it checks each against the list's form and the // whole against the list's order. func (r *reader) values(environment string, item *tree.Node, rule list) []string { diff --git a/internal/origins/origins_test.go b/internal/origins/origins_test.go index 68ddee1..bed417c 100644 --- a/internal/origins/origins_test.go +++ b/internal/origins/origins_test.go @@ -111,7 +111,7 @@ func TestReadProblems(t *testing.T) { {name: "no environment", file: `{"environments": []}`, want: []string{`o.json:1:18: the file names no environment`}}, {name: "unknown key", file: `{"environments": [{"name": "a", "hosts": ["x.example"], "domains": []}]}`, - want: []string{`o.json:1:57: unknown key "domains"; known here: hosts, name, origins, patterns`}}, + want: []string{`o.json:1:57: unknown key "domains"; known here: ask_unlisted, hosts, name, origins, patterns, question`}}, {name: "name twice", file: `{"environments": [{"name": "a", "hosts": ["x.example"]}, {"name": "a", "hosts": ["y.example"]}]}`, want: []string{`o.json:1:58: environment "a" is listed twice`}}, // Both spellings of no name, counted from 1; two environments without a name are not also listed twice. diff --git a/internal/read/decode.go b/internal/read/decode.go index 9f3f9da..d57a93c 100644 --- a/internal/read/decode.go +++ b/internal/read/decode.go @@ -309,8 +309,7 @@ func (d *decoder) auth(root *tree.Node) *model.Auth { d.Add(n.Pos, "%q is required here", key) } } - // The check's pattern for ask is one service name, one space and a path. - service, path, _ := strings.Cut(ask.Text, " ") + service, path := model.SplitAsk(ask.Text) auth := &model.Auth{ Service: model.Text{Value: service, Pos: ask.Pos}, Path: path, diff --git a/internal/read/read.go b/internal/read/read.go index 157c126..a052a30 100644 --- a/internal/read/read.go +++ b/internal/read/read.go @@ -53,7 +53,7 @@ func Proxyfile(path string) (*File, []model.Problem) { if problems != nil { return nil, problems } - inline, originsProblems := readOrigins(root) + inline, originsProblems := readOrigins(g, root) proto, protoProblems := readProto(root, path) if problems := slices.Concat(meaning(g), originsProblems, protoProblems); len(problems) > 0 { model.SortProblems(problems) @@ -69,10 +69,15 @@ func Proxyfile(path string) (*File, []model.Problem) { return file, nil } -// readOrigins reads the origins the proxyfile writes, or returns nil when "origins" names a file. -func readOrigins(root *tree.Node) (*origins.File, []model.Problem) { +// readOrigins reads the origins the proxyfile writes, or returns nil when "origins" names a file, with the rules that +// read them against the gateway. +func readOrigins(g *model.Gateway, root *tree.Node) (*origins.File, []model.Problem) { if environments := root.Get("origins"); environments.Kind == tree.Map { - return origins.Inline(root.Get("cors"), environments) + file, problems := origins.Inline(root.Get("cors"), environments) + if problems != nil { + return nil, problems + } + return file, OriginChecks(g, file) } // An origins file holds its own cors settings, and those are the ones render.Read gives the generator, so a cors // written here would be ignored. diff --git a/internal/read/read_test.go b/internal/read/read_test.go index 7c147d4..5b94a0b 100644 --- a/internal/read/read_test.go +++ b/internal/read/read_test.go @@ -37,6 +37,22 @@ routes = [ ] ` +// asking is a valid proxyfile whose live environment puts a browser origin its lists do not hold to the check on line +// 8, asking the question on line 9, which the origin check rows change, one change each. +var asking = testsupport.Document{ + "listen: 8000", + "services:", + " web: {http: 3000}", + " rpc-backend: {grpc: 5000}", + "origins:", + " live:", + " hosts: [api.example.com]", + " ask_unlisted: web /origin", + " question: browser-origin", + "routes:", + " - {name: web, prefix: /, to: web}", +} + func TestReadProblems(t *testing.T) { cases := []struct { name string @@ -362,6 +378,20 @@ func TestReadProblems(t *testing.T) { {name: "HOCON: rate as a number", file: "g.conf", document: bHOCON + "envoy { tracing { provider { xray { segment = s, sample { rate = 5 } } } } }\n", want: []string{`g.conf: envoy.tracing.provider.xray.sample.rate: "rate" must be a whole percentage such as 5%`}}, + // An environment may put a browser origin its lists do not hold to a check of its own, written as auth.ask is, + // a service with an http port and a path, and asked the environment's question; a question with no check to + // ask it of is refused, as a key of the auth check is without ask. + {name: "an origin no list holds put to a check", document: asking.String()}, + {name: "an origin check naming a service that is not declared", + document: asking.Replaced(8, 8, " ask_unlisted: nobody /origin"), + want: []string{`g.yaml:8:19: environment "live": the service "nobody" is not declared`}}, + {name: "an origin check naming a service with no http port", + document: asking.Replaced(8, 8, " ask_unlisted: rpc-backend /origin"), + want: []string{`g.yaml:8:19: environment "live": the service "rpc-backend" has no http port`}}, + {name: "an origin check with no path", document: asking.Replaced(8, 8, " ask_unlisted: web"), + want: []string{`g.yaml:8:19: "ask_unlisted" must be a service and a path, such as accounts /check`}}, + {name: "a question with no origin check", document: asking.Replaced(8, 8), + want: []string{`g.yaml:8:5: environment "live": question is written, but ask_unlisted is not`}}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { diff --git a/internal/read/rules.go b/internal/read/rules.go index cd8b711..a693f20 100644 --- a/internal/read/rules.go +++ b/internal/read/rules.go @@ -7,6 +7,7 @@ import ( "slices" "github.com/kitecorp/proxyfile/v2/internal/model" + "github.com/kitecorp/proxyfile/v2/internal/origins" ) // rules holds the checks no single key can fail: a name that must match a declaration, two entries that clash, and @@ -139,6 +140,19 @@ func (r *rules) route(route *model.Route, earlier []*model.Route) { } } +// OriginChecks refuses an environment's ask_unlisted that names a service that is not declared or has no http port, +// as auth.ask is refused. It reads the origins apart from the proxyfile, because an origins file holds them when +// "origins" names one, and render.Read reads that file after the proxyfile. +func OriginChecks(g *model.Gateway, file *origins.File) []model.Problem { + r := rules{g: g} + for _, environment := range file.Environments { + if check := environment.AskUnlisted; check != nil { + r.service(fmt.Sprintf("environment %q:", environment.Name), check.Service, model.HTTP) + } + } + return r.Sorted() +} + // service reports a reference to a service that is not declared, or that has no port for the protocol the // reference needs. subject starts the message, naming what refers to the service. func (r *rules) service(subject string, ref model.Text, protocol model.Protocol) { diff --git a/internal/render/render.go b/internal/render/render.go index 43f6ede..f6ac3ec 100644 --- a/internal/render/render.go +++ b/internal/render/render.go @@ -110,7 +110,7 @@ func Read(req Request) (*Run, []model.Problem) { var root *tree.Node file, root, problems = origins.Read(originsPath) if problems == nil { - problems = format.Refusals(format.Origins, root, proxyfile.Tree, target) + problems = slices.Concat(read.OriginChecks(g, file), format.Refusals(format.Origins, root, proxyfile.Tree, target)) } all = append(all, problems...) inputPaths = append(inputPaths, originsPath) diff --git a/internal/render/render_test.go b/internal/render/render_test.go index 871c17c..9b71b35 100644 --- a/internal/render/render_test.go +++ b/internal/render/render_test.go @@ -291,8 +291,9 @@ func TestRenderProblems(t *testing.T) { target string // the request's Target, "" for envoy // named is, when set, the name of the file beside the configuration that the generator of a target nginx // declared for the row returns. - named string - want []string + named string + origins string // written to origins.json; testdata/origins.json when empty + want []string }{ // A generator names each file beside the configuration by a name alone, so a name that holds a folder is a bug // in proxyfile, and no file is written outside the folder of -o. @@ -323,13 +324,22 @@ func TestRenderProblems(t *testing.T) { "g.yaml:6:5: the routes have an rpc entry, so rpc.methods, rpc.proto or --rpc-methods must list the RPC methods", "origins-absent.json: the file cannot be read: no such file or directory", }}, + // An origins file's ask_unlisted names a service of the proxyfile, which render reads apart from the file, and is + // refused as the proxyfile's own origins are when the proxyfile does not declare it. + {name: "an origins file's origin check naming a service that is not declared", proxyfile: beside, + origins: "{\n" + + " \"environments\": [\n" + + " {\"name\": \"all\", \"hosts\": [\"localhost\"], \"ask_unlisted\": \"nobody /origin\"}\n" + + " ]\n" + + "}\n", + want: []string{`origins.json:3:61: environment "all": the service "nobody" is not declared`}}, } - origins := testsupport.ReadFile(t, "testdata/origins.json") + defaultOrigins := string(testsupport.ReadFile(t, "testdata/origins.json")) for _, c := range cases { t.Run(c.name, func(t *testing.T) { dir := t.TempDir() testsupport.WriteFile(t, filepath.Join(dir, "g.yaml"), c.proxyfile) - testsupport.WriteFile(t, filepath.Join(dir, "origins.json"), string(origins)) + testsupport.WriteFile(t, filepath.Join(dir, "origins.json"), cmp.Or(c.origins, defaultOrigins)) if c.named != "" { declareNginx(t, []generator.File{{Bytes: []byte("config\n")}, {Name: c.named, Bytes: []byte("script\n")}}) } diff --git a/internal/render/testdata/full-before-ask-unlisted.envoy.yaml b/internal/render/testdata/full-before-ask-unlisted.envoy.yaml new file mode 100644 index 0000000..78cfca5 --- /dev/null +++ b/internal/render/testdata/full-before-ask-unlisted.envoy.yaml @@ -0,0 +1,657 @@ +# Generated by proxyfile. Do not edit: change the proxyfile beside it and run proxyfile render; proxyfile check fails on a hand edit. +admin: + address: {socket_address: {address: 127.0.0.1, port_value: 9901}} + allow_paths: [{exact: /ready}, {exact: /stats}, {exact: /server_info}] +overload_manager: + refresh_interval: 0.25s + resource_monitors: + - name: envoy.resource_monitors.fixed_heap + typed_config: + "@type": type.googleapis.com/envoy.extensions.resource_monitors.fixed_heap.v3.FixedHeapConfig + max_heap_size_bytes: 268435456 + - name: envoy.resource_monitors.global_downstream_max_connections + typed_config: + "@type": type.googleapis.com/envoy.extensions.resource_monitors.downstream_connections.v3.DownstreamConnectionsConfig + max_active_downstream_connections: 4096 + actions: + - name: envoy.overload_actions.shrink_heap + triggers: [{name: envoy.resource_monitors.fixed_heap, threshold: {value: 0.90}}] + - name: envoy.overload_actions.stop_accepting_requests + triggers: [{name: envoy.resource_monitors.fixed_heap, threshold: {value: 0.98}}] +static_resources: + listeners: + - name: public + address: {socket_address: {address: 0.0.0.0, port_value: 10000}} + filter_chains: + - filters: + - name: envoy.filters.network.http_connection_manager + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager + stat_prefix: public + use_remote_address: true + always_set_request_id_in_response: true + request_id_extension: + typed_config: + "@type": type.googleapis.com/envoy.extensions.request_id.uuid.v3.UuidRequestIdConfig + pack_trace_reason: false + tracing: + client_sampling: {value: 0} + random_sampling: {value: 10} + custom_tags: + - tag: "environment" + environment: {name: "APP_ENVIRONMENT", default_value: "local"} + - tag: "request_id" + request_header: {name: "x-request-id"} + provider: + name: envoy.tracers.opentelemetry + typed_config: + "@type": type.googleapis.com/envoy.config.trace.v3.OpenTelemetryConfig + grpc_service: + envoy_grpc: {cluster_name: "otel_collector"} + service_name: "example-gateway" + server_header_transformation: PASS_THROUGH + max_request_headers_kb: 96 + common_http_protocol_options: {max_headers_count: 150} + normalize_path: true + merge_slashes: true + path_with_escaped_slashes_action: UNESCAPE_AND_FORWARD + upgrade_configs: [{upgrade_type: websocket}] + local_reply_config: + mappers: + - filter: {response_flag_filter: {flags: [UF, UH, UC, URX]}} + status_code: 502 + body: {inline_string: ""} + - filter: + and_filter: + filters: + - status_code_filter: + comparison: {op: EQ, value: {default_value: 403, runtime_key: gateway.local_reply.origin_refused_status}} + - header_filter: + header: {name: origin, present_match: true} + body: {inline_string: "Invalid CORS request"} + - filter: + and_filter: + filters: + - response_flag_filter: {flags: [UAEX]} + - status_code_filter: {comparison: {op: GE, value: {default_value: 200}}} + - status_code_filter: {comparison: {op: LE, value: {default_value: 299}}} + status_code: 403 + - filter: {response_flag_filter: {flags: [UAEX]}} + - filter: + and_filter: + filters: + - status_code_filter: + comparison: {op: EQ, value: {default_value: 429, runtime_key: gateway.local_reply.rate_limited_status}} + - header_filter: + header: {name: connect-protocol-version, present_match: true} + body: {inline_string: '{"code":"resource_exhausted","message":"local_rate_limited"}'} + body_format_override: + text_format_source: {inline_string: "%LOCAL_REPLY_BODY%"} + content_type: application/json + access_log: + - name: envoy.access_loggers.stdout + filter: + or_filter: + filters: + - status_code_filter: + comparison: {op: GE, value: {default_value: 400, runtime_key: gateway.request_log.min_status}} + - response_flag_filter: {} + - runtime_filter: + runtime_key: gateway.request_log.sample + percent_sampled: {numerator: 1, denominator: HUNDRED} + typed_config: + "@type": type.googleapis.com/envoy.extensions.access_loggers.stream.v3.StdoutAccessLog + log_format: + json_format: + time: "%START_TIME%" + route: "%ROUTE_NAME%" + host: "%REQ(:AUTHORITY)%" + method: "%REQ(:METHOD)%" + protocol: "%PROTOCOL%" + status: "%RESPONSE_CODE%" + flags: "%RESPONSE_FLAGS%" + details: "%RESPONSE_CODE_DETAILS%" + duration_ms: "%DURATION%" + upstream_ms: "%RESPONSE_DURATION%" + bytes_in: "%BYTES_RECEIVED%" + bytes_out: "%BYTES_SENT%" + upstream: "%UPSTREAM_CLUSTER%" + request_id: "%REQ(X-REQUEST-ID)%" + authz_us: "%FILTER_STATE(envoy.filters.http.ext_authz:FIELD:latency_us)%" + - name: envoy.access_loggers.stdout + filter: + response_flag_filter: {flags: [UH, UF, UO, UC, UT, URX, UPE]} + typed_config: + "@type": type.googleapis.com/envoy.extensions.access_loggers.stream.v3.StdoutAccessLog + log_format: + json_format: + event: gateway_upstream_failure + route: "%ROUTE_NAME%" + status: "%RESPONSE_CODE%" + flags: "%RESPONSE_FLAGS%" + upstream: "%UPSTREAM_CLUSTER%" + - name: envoy.access_loggers.stdout + filter: + and_filter: + filters: + - header_filter: + header: {name: x-envoy-auth-failure-mode-allowed, present_match: true} + - metadata_filter: + matcher: {filter: "example.gateway", path: [{key: filtered}], value: {bool_match: true}} + match_if_key_not_found: false + typed_config: + "@type": type.googleapis.com/envoy.extensions.access_loggers.stream.v3.StdoutAccessLog + log_format: + json_format: + event: gateway_auth_unavailable + route: "%ROUTE_NAME%" + action: "%METADATA(ROUTE:example.gateway:action)%" + status: "%RESPONSE_CODE%" + failure_mode_allowed: "%REQ(x-envoy-auth-failure-mode-allowed)%" + request_id: "%REQ(X-REQUEST-ID)%" + early_header_mutation_extensions: + - name: envoy.http.early_header_mutation.header_mutation + typed_config: + "@type": type.googleapis.com/envoy.extensions.http.early_header_mutation.header_mutation.v3.HeaderMutation + mutations: + - remove_on_match: {key_matcher: {prefix: "x-user-"}} + - remove_on_match: {key_matcher: {prefix: "x-client-"}} + - remove_on_match: {key_matcher: {prefix: "x-tier-"}} + - remove_on_match: {key_matcher: {prefix: "x-gateway-"}} + - remove: "x-subject" + - remove: "x-roles" + - remove: x-envoy-auth-failure-mode-allowed + - remove: x-envoy-downstream-service-cluster + - remove: x-envoy-downstream-service-node + - remove: x-envoy-decorator-operation + http_filters: + - name: envoy.filters.http.set_metadata + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.set_metadata.v3.Config + metadata: + - metadata_namespace: "example.gateway" + value: {filtered: true} + - name: envoy.filters.http.header_mutation + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutation + mutations: + response_mutations: + - append: + header: {key: vary, value: Origin} + append_action: APPEND_IF_EXISTS_OR_ADD + - remove: x-envoy-upstream-service-time + - name: envoy.filters.http.rbac + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.rbac.v3.RBAC + - name: envoy.filters.http.cors + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.cors.v3.Cors + - name: envoy.filters.http.local_ratelimit + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.local_ratelimit.v3.LocalRateLimit + stat_prefix: rate_limit + filter_enabled: + default_value: + numerator: 100 + denominator: HUNDRED + filter_enforced: + default_value: + numerator: 100 + denominator: HUNDRED + rate_limited_as_resource_exhausted: true + always_consume_default_token_bucket: false + max_dynamic_descriptors: 65536 + rate_limits: + - actions: + - metadata: {descriptor_key: bucket, metadata_key: {key: "example.gateway.rate_limit", path: [{key: all}]}, source: ROUTE_ENTRY} + - actions: + - metadata: {descriptor_key: bucket, metadata_key: {key: "example.gateway.rate_limit", path: [{key: client}]}, source: ROUTE_ENTRY} + - remote_address: {} + descriptors: + - entries: [{key: bucket, value: "rpc"}] + token_bucket: {max_tokens: 100, tokens_per_fill: 100, fill_interval: 1s} + - entries: [{key: bucket, value: "catalog"}, {key: remote_address}] + token_bucket: {max_tokens: 30, tokens_per_fill: 20, fill_interval: 1s} + - name: envoy.filters.http.jwt_authn + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.JwtAuthentication + providers: + jwt: + issuer: "https://login.example.com" + audiences: ["api.example.com", "admin.example.com"] + require_expiration: true + remote_jwks: + http_uri: {uri: "https://login.example.com/.well-known/jwks.json", cluster: jwks, timeout: 2s} + retry_policy: {num_retries: 1} + forward: true + from_headers: [{name: "x-access-token"}] + claim_to_headers: [{header_name: "x-subject", claim_name: "sub"}, {header_name: "x-roles", claim_name: "realm.roles"}] + rules: + - match: {prefix: "/"} + requires: + requires_any: + requirements: [{provider_name: jwt}, {allow_missing: {}}] + - name: envoy.filters.http.ext_authz + typed_config: + "@type": type.googleapis.com/envoy.extensions.common.matching.v3.ExtensionWithMatcher + extension_config: + name: envoy.filters.http.ext_authz + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthz + http_service: + server_uri: {uri: "http://127.0.0.1:7070/auth/check", cluster: "accounts_http", timeout: 1.5s} + path_override: "/auth/check" + authorization_request: + headers_to_add: [{key: x-gateway-timeout-ms, value: "1500"}, {key: x-forwarded-uri, value: "%REQ(:PATH)%"}, {key: x-forwarded-method, value: "%REQ(:METHOD)%"}, {key: x-forwarded-proto, value: "https"}, {key: x-forwarded-host, value: "%REQ(:AUTHORITY)%"}] + authorization_response: + allowed_upstream_headers: + patterns: + - prefix: "x-user-" + - prefix: "x-tier-" + failure_mode_allow: true + failure_mode_allow_header_add: true + allowed_headers: + patterns: + - exact: "authorization" + - exact: "x-country" + - exact: x-gateway-action + - exact: x-gateway-reports + emit_filter_state_stats: true + filter_enabled: + default_value: {numerator: 100, denominator: HUNDRED} + runtime_key: gateway.ext_authz.enabled + xds_matcher: + matcher_list: + matchers: + - predicate: + not_matcher: + single_predicate: + input: + name: "authorization" + typed_config: + "@type": type.googleapis.com/envoy.type.matcher.v3.HttpRequestHeaderMatchInput + header_name: "authorization" + value_match: {safe_regex: {google_re2: {}, regex: ".+"}} + on_match: + action: + name: skip + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.common.matcher.action.v3.SkipFilter + - name: envoy.filters.http.lua + disabled: true + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua + default_source_code: + inline_string: | + -- Connect's status today for each code whose status the bridge writes from the old table. + local CONNECT_STATUS = { + canceled = "499", + deadline_exceeded = "504", + failed_precondition = "400", + unimplemented = "501", + } + local OLD_STATUS = {["404"] = true, ["408"] = true, ["412"] = true} + + function envoy_on_response(response_handle) + local headers = response_handle:headers() + if not OLD_STATUS[headers:get(":status")] or headers:get("content-type") ~= "application/json" then + return + end + local body = response_handle:body() + if body == nil then + return + end + -- The bridge writes the error with protobuf's JSON printer: its keys come in no fixed order + -- (message before code, as measured), and a quote inside a string is always escaped, so the + -- only "code":"..." pair in the body is the error's own. + local code = body:getBytes(0, body:length()):match('"code"%s*:%s*"([%l_]+)"') + local status = CONNECT_STATUS[code] + if status ~= nil then + -- Asked for again: the header object from before body() died while the body was awaited. + response_handle:headers():replace(":status", status) + end + end + - name: envoy.filters.http.connect_grpc_bridge + disabled: true + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.connect_grpc_bridge.v3.FilterConfig + - name: envoy.filters.http.router + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router + suppress_envoy_headers: true + route_config: + name: public + request_headers_to_remove: [x-gateway-action, x-gateway-reports] + ignore_port_in_host_matching: true + virtual_hosts: + - name: "live" + domains: ["api.example.com", "api.example.org"] + typed_per_filter_config: + envoy.filters.http.rbac: + "@type": type.googleapis.com/envoy.extensions.filters.http.rbac.v3.RBACPerRoute + rbac: + rules: + action: ALLOW + policies: + browser-origins: + permissions: [{any: true}] + principals: + - {not_id: {header: {name: origin, present_match: true}}} + - {header: {name: origin, string_match: {safe_regex: {regex: "^https?://api\\.example\\.com(:[0-9]+)?$"}}}} + - {header: {name: origin, string_match: {safe_regex: {regex: "^https?://api\\.example\\.org(:[0-9]+)?$"}}}} + - {header: {name: origin, string_match: {exact: "https://example.com", ignore_case: true}}} + - {header: {name: origin, string_match: {exact: "https://www.example.com", ignore_case: true}}} + - {header: {name: origin, string_match: {safe_regex: {regex: "^https://.*\\.example\\.com$"}}}} + envoy.filters.http.cors: + "@type": type.googleapis.com/envoy.extensions.filters.http.cors.v3.CorsPolicy + allow_origin_string_match: + - {exact: "https://example.com", ignore_case: true} + - {exact: "https://www.example.com", ignore_case: true} + - {safe_regex: {regex: "^https://.*\\.example\\.com$"}} + allow_methods: "*" + allow_headers: "*" + expose_headers: "Content-Disposition,X-Request-Id" + max_age: "600" + forward_not_matching_preflights: false + routes: + - name: "refused:dot-segment-with-parameter" + match: {safe_regex: {regex: ".*/\\.\\.?(?:;|%3[Bb]).*"}} + direct_response: {status: 400} + - name: "accounts-events" + match: {safe_regex: {regex: "^/events/[a-z0-9-]+$"}} + decorator: {operation: "accounts-events", propagate: false} + route: {cluster: "accounts_http", host_rewrite_literal: "127.0.0.1:7070", timeout: 0s, idle_timeout: 90s} + typed_per_filter_config: + envoy.filters.http.jwt_authn: + "@type": type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.PerRouteConfig + disabled: true + envoy.filters.http.ext_authz: + "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute + disabled: true + - {name: "accounts-rpc", match: {path: "/example.accounts.v1.ProfileService/GetProfile"}, metadata: {filter_metadata: {"example.gateway": {action: ""}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "accounts-rpc", propagate: false}, typed_per_filter_config: {envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "accounts_grpc", host_rewrite_literal: "127.0.0.1:7070", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem"}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/GetCart"}, metadata: {filter_metadata: {"example.gateway": {action: "browse"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - name: "accounts-webhooks" + match: {path: "/api/webhooks", headers: [{name: ":method", string_match: {exact: "POST"}}]} + decorator: {operation: "accounts-webhooks", propagate: false} + route: {cluster: "accounts_http", host_rewrite_literal: "127.0.0.1:7070", prefix_rewrite: "/hooks/payments", timeout: 0s, idle_timeout: 90s} + typed_per_filter_config: + envoy.filters.http.jwt_authn: + "@type": type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.PerRouteConfig + disabled: true + envoy.filters.http.ext_authz: + "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute + disabled: true + - name: "catalog" + match: {prefix: "/catalog/"} + metadata: {filter_metadata: {"example.gateway": {action: ""}, "example.gateway.rate_limit": {client: "catalog"}}} + decorator: {operation: "catalog", propagate: false} + route: {cluster: "catalog_http", timeout: 0s, idle_timeout: 90s} + - name: "shop" + match: {prefix: "/"} + metadata: {filter_metadata: {"example.gateway": {action: ""}}} + decorator: {operation: "shop", propagate: false} + route: {cluster: "shop_http", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}} + - name: "test" + domains: ["api.test.example.com"] + typed_per_filter_config: + envoy.filters.http.rbac: + "@type": type.googleapis.com/envoy.extensions.filters.http.rbac.v3.RBACPerRoute + rbac: + rules: + action: ALLOW + policies: + browser-origins: + permissions: [{any: true}] + principals: + - {not_id: {header: {name: origin, present_match: true}}} + - {header: {name: origin, string_match: {safe_regex: {regex: "^https?://api\\.test\\.example\\.com(:[0-9]+)?$"}}}} + - {header: {name: origin, string_match: {exact: "http://localhost:3000", ignore_case: true}}} + - {header: {name: origin, string_match: {exact: "https://test.example.com", ignore_case: true}}} + - {header: {name: origin, string_match: {safe_regex: {regex: "^https://.*\\.test\\.example\\.com$"}}}} + envoy.filters.http.cors: + "@type": type.googleapis.com/envoy.extensions.filters.http.cors.v3.CorsPolicy + allow_origin_string_match: + - {exact: "http://localhost:3000", ignore_case: true} + - {exact: "https://test.example.com", ignore_case: true} + - {safe_regex: {regex: "^https://.*\\.test\\.example\\.com$"}} + allow_methods: "*" + allow_headers: "*" + expose_headers: "Content-Disposition,X-Request-Id" + max_age: "600" + forward_not_matching_preflights: false + routes: + - name: "refused:dot-segment-with-parameter" + match: {safe_regex: {regex: ".*/\\.\\.?(?:;|%3[Bb]).*"}} + direct_response: {status: 400} + - name: "accounts-events" + match: {safe_regex: {regex: "^/events/[a-z0-9-]+$"}} + decorator: {operation: "accounts-events", propagate: false} + route: {cluster: "accounts_http", host_rewrite_literal: "127.0.0.1:7070", timeout: 0s, idle_timeout: 90s} + typed_per_filter_config: + envoy.filters.http.jwt_authn: + "@type": type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.PerRouteConfig + disabled: true + envoy.filters.http.ext_authz: + "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute + disabled: true + - {name: "accounts-rpc", match: {path: "/example.accounts.v1.ProfileService/GetProfile"}, metadata: {filter_metadata: {"example.gateway": {action: ""}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "accounts-rpc", propagate: false}, typed_per_filter_config: {envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "accounts_grpc", host_rewrite_literal: "127.0.0.1:7070", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem"}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/GetCart"}, metadata: {filter_metadata: {"example.gateway": {action: "browse"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - name: "accounts-webhooks" + match: {path: "/api/webhooks", headers: [{name: ":method", string_match: {exact: "POST"}}]} + decorator: {operation: "accounts-webhooks", propagate: false} + route: {cluster: "accounts_http", host_rewrite_literal: "127.0.0.1:7070", prefix_rewrite: "/hooks/payments", timeout: 0s, idle_timeout: 90s} + typed_per_filter_config: + envoy.filters.http.jwt_authn: + "@type": type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.PerRouteConfig + disabled: true + envoy.filters.http.ext_authz: + "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute + disabled: true + - name: "catalog" + match: {prefix: "/catalog/"} + metadata: {filter_metadata: {"example.gateway": {action: ""}, "example.gateway.rate_limit": {client: "catalog"}}} + decorator: {operation: "catalog", propagate: false} + route: {cluster: "catalog_http", timeout: 0s, idle_timeout: 90s} + - name: "shop" + match: {prefix: "/"} + metadata: {filter_metadata: {"example.gateway": {action: ""}}} + decorator: {operation: "shop", propagate: false} + route: {cluster: "shop_http", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}} + - name: "local" + domains: ["127.0.0.1", "localhost"] + typed_per_filter_config: + envoy.filters.http.rbac: + "@type": type.googleapis.com/envoy.extensions.filters.http.rbac.v3.RBACPerRoute + rbac: + rules: + action: ALLOW + policies: + browser-origins: + permissions: [{any: true}] + principals: + - {not_id: {header: {name: origin, present_match: true}}} + - {header: {name: origin, string_match: {safe_regex: {regex: "^https?://127\\.0\\.0\\.1(:[0-9]+)?$"}}}} + - {header: {name: origin, string_match: {safe_regex: {regex: "^https?://localhost(:[0-9]+)?$"}}}} + - {header: {name: origin, string_match: {safe_regex: {regex: "^http://.*\\.example\\.com:.*$"}}}} + - {header: {name: origin, string_match: {safe_regex: {regex: "^http://localhost:.*$"}}}} + envoy.filters.http.cors: + "@type": type.googleapis.com/envoy.extensions.filters.http.cors.v3.CorsPolicy + allow_origin_string_match: + - {safe_regex: {regex: "^http://.*\\.example\\.com:.*$"}} + - {safe_regex: {regex: "^http://localhost:.*$"}} + allow_methods: "*" + allow_headers: "*" + expose_headers: "Content-Disposition,X-Request-Id" + max_age: "600" + forward_not_matching_preflights: false + routes: + - name: "refused:dot-segment-with-parameter" + match: {safe_regex: {regex: ".*/\\.\\.?(?:;|%3[Bb]).*"}} + direct_response: {status: 400} + - name: "accounts-events" + match: {safe_regex: {regex: "^/events/[a-z0-9-]+$"}} + decorator: {operation: "accounts-events", propagate: false} + route: {cluster: "accounts_http", host_rewrite_literal: "127.0.0.1:7070", timeout: 0s, idle_timeout: 90s} + typed_per_filter_config: + envoy.filters.http.jwt_authn: + "@type": type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.PerRouteConfig + disabled: true + envoy.filters.http.ext_authz: + "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute + disabled: true + - {name: "accounts-rpc", match: {path: "/example.accounts.v1.ProfileService/GetProfile"}, metadata: {filter_metadata: {"example.gateway": {action: ""}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "accounts-rpc", propagate: false}, typed_per_filter_config: {envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "accounts_grpc", host_rewrite_literal: "127.0.0.1:7070", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/AddItem"}, metadata: {filter_metadata: {"example.gateway": {action: "buy"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "buy"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}, {append: {header: {key: x-gateway-reports, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - {name: "shop", match: {path: "/example.shop.v1.CartService/GetCart"}, metadata: {filter_metadata: {"example.gateway": {action: "browse"}, "example.gateway.rate_limit": {all: "rpc"}}}, decorator: {operation: "shop", propagate: false}, typed_per_filter_config: {envoy.filters.http.header_mutation: {"@type": type.googleapis.com/envoy.extensions.filters.http.header_mutation.v3.HeaderMutationPerRoute, mutations: {request_mutations: [{append: {header: {key: x-gateway-action, value: "browse"}, append_action: OVERWRITE_IF_EXISTS_OR_ADD}}]}}, envoy.filters.http.connect_grpc_bridge: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}, envoy.filters.http.lua: {"@type": type.googleapis.com/envoy.config.route.v3.FilterConfig, config: {}}}, route: {cluster: "shop_grpc", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}}} + - name: "accounts-webhooks" + match: {path: "/api/webhooks", headers: [{name: ":method", string_match: {exact: "POST"}}]} + decorator: {operation: "accounts-webhooks", propagate: false} + route: {cluster: "accounts_http", host_rewrite_literal: "127.0.0.1:7070", prefix_rewrite: "/hooks/payments", timeout: 0s, idle_timeout: 90s} + typed_per_filter_config: + envoy.filters.http.jwt_authn: + "@type": type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.PerRouteConfig + disabled: true + envoy.filters.http.ext_authz: + "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthzPerRoute + disabled: true + - name: "catalog" + match: {prefix: "/catalog/"} + metadata: {filter_metadata: {"example.gateway": {action: ""}, "example.gateway.rate_limit": {client: "catalog"}}} + decorator: {operation: "catalog", propagate: false} + route: {cluster: "catalog_http", timeout: 0s, idle_timeout: 90s} + - name: "shop" + match: {prefix: "/"} + metadata: {filter_metadata: {"example.gateway": {action: ""}}} + decorator: {operation: "shop", propagate: false} + route: {cluster: "shop_http", timeout: 0s, idle_timeout: 90s, retry_policy: {retry_on: "connect-failure,reset-before-request", num_retries: 1, retry_host_predicate: [{name: envoy.retry_host_predicates.previous_hosts, typed_config: {"@type": type.googleapis.com/envoy.extensions.retry.host.previous_hosts.v3.PreviousHostsPredicate}}], host_selection_retry_max_attempts: 20}} + transport_socket: + name: envoy.transport_sockets.tls + typed_config: + "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.DownstreamTlsContext + common_tls_context: + alpn_protocols: [h2, http/1.1] + tls_certificates: [{certificate_chain: {filename: "/etc/gateway/tls/certificate.pem"}, private_key: {filename: "/etc/gateway/tls/key.pem"}}] + validation_context: {trusted_ca: {filename: "/etc/gateway/tls/clients-ca.pem"}} + require_client_certificate: true + clusters: + - name: "shop_http" + type: STATIC + lb_policy: LEAST_REQUEST + load_assignment: + cluster_name: "shop_http" + endpoints: [{lb_endpoints: [{endpoint: {address: {socket_address: {address: "10.0.1.11", port_value: 8080}}}}, {endpoint: {address: {socket_address: {address: "10.0.1.12", port_value: 8080}}}}]}] + health_checks: + - timeout: 1s + interval: 10s + no_traffic_interval: 10s + healthy_threshold: 2 + unhealthy_threshold: 3 + http_health_check: {path: "/healthz", expected_statuses: [{start: 200, end: 300}], retriable_statuses: [{start: 100, end: 600}]} + common_lb_config: {healthy_panic_threshold: {value: 0}} + circuit_breakers: {thresholds: [{max_connections: 4096, max_pending_requests: 4096, max_requests: 4096}]} + typed_extension_protocol_options: + envoy.extensions.upstreams.http.v3.HttpProtocolOptions: + "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions + common_http_protocol_options: {idle_timeout: 45s} + explicit_http_config: {http_protocol_options: {}} + - name: "shop_grpc" + type: STATIC + lb_policy: LEAST_REQUEST + load_assignment: + cluster_name: "shop_grpc" + endpoints: [{lb_endpoints: [{endpoint: {address: {socket_address: {address: "10.0.1.11", port_value: 8081}}}}, {endpoint: {address: {socket_address: {address: "10.0.1.12", port_value: 8081}}}}]}] + health_checks: + - timeout: 1s + interval: 10s + no_traffic_interval: 10s + healthy_threshold: 2 + unhealthy_threshold: 3 + grpc_health_check: {} + common_lb_config: {healthy_panic_threshold: {value: 0}} + circuit_breakers: {thresholds: [{max_connections: 4096, max_pending_requests: 4096, max_requests: 4096}]} + typed_extension_protocol_options: + envoy.extensions.upstreams.http.v3.HttpProtocolOptions: + "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions + common_http_protocol_options: {idle_timeout: 45s} + explicit_http_config: {http2_protocol_options: {}} + - name: "accounts_grpc" + type: STATIC + load_assignment: + cluster_name: "accounts_grpc" + endpoints: [{lb_endpoints: [{endpoint: {address: {socket_address: {address: "127.0.0.1", port_value: 7070}}}}]}] + circuit_breakers: {thresholds: [{max_connections: 4096, max_pending_requests: 4096, max_requests: 4096}]} + typed_extension_protocol_options: + envoy.extensions.upstreams.http.v3.HttpProtocolOptions: + "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions + common_http_protocol_options: {idle_timeout: 45s} + explicit_http_config: {http2_protocol_options: {}} + - name: "accounts_http" + type: STATIC + load_assignment: + cluster_name: "accounts_http" + endpoints: [{lb_endpoints: [{endpoint: {address: {socket_address: {address: "127.0.0.1", port_value: 7070}}}}]}] + circuit_breakers: {thresholds: [{max_connections: 4096, max_pending_requests: 4096, max_requests: 4096}]} + typed_extension_protocol_options: + envoy.extensions.upstreams.http.v3.HttpProtocolOptions: + "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions + common_http_protocol_options: {idle_timeout: 45s} + explicit_http_config: {http_protocol_options: {}} + - name: "catalog_http" + cluster_type: + name: envoy.cluster.dns + typed_config: + "@type": type.googleapis.com/envoy.extensions.clusters.dns.v3.DnsCluster + dns_lookup_family: ALL + typed_dns_resolver_config: + name: envoy.network.dns_resolver.cares + typed_config: + "@type": type.googleapis.com/envoy.extensions.network.dns_resolver.cares.v3.CaresDnsResolverConfig + resolvers: [{socket_address: {address: "10.0.0.2", port_value: 53}}] + lb_policy: RING_HASH + load_assignment: + cluster_name: "catalog_http" + endpoints: [{lb_endpoints: [{endpoint: {address: {socket_address: {address: "catalog.internal.example", port_value: 8090}}}}]}] + circuit_breakers: {thresholds: [{max_connections: 4096, max_pending_requests: 4096, max_requests: 4096}]} + typed_extension_protocol_options: + envoy.extensions.upstreams.http.v3.HttpProtocolOptions: + "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions + hash_policy: [{header: {header_name: "x-session-id"}}] + common_http_protocol_options: {idle_timeout: 45s} + explicit_http_config: {http_protocol_options: {}} + - name: "otel_collector" + type: STATIC + load_assignment: + cluster_name: "otel_collector" + endpoints: [{lb_endpoints: [{endpoint: {address: {socket_address: {address: "10.0.3.40", port_value: 4317}}}}]}] + typed_extension_protocol_options: + envoy.extensions.upstreams.http.v3.HttpProtocolOptions: + "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions + explicit_http_config: {http2_protocol_options: {}} + - name: "jwks" + cluster_type: + name: envoy.cluster.dns + typed_config: + "@type": type.googleapis.com/envoy.extensions.clusters.dns.v3.DnsCluster + dns_lookup_family: ALL + typed_dns_resolver_config: + name: envoy.network.dns_resolver.cares + typed_config: + "@type": type.googleapis.com/envoy.extensions.network.dns_resolver.cares.v3.CaresDnsResolverConfig + resolvers: [{socket_address: {address: "10.0.0.2", port_value: 53}}] + load_assignment: + cluster_name: "jwks" + endpoints: [{lb_endpoints: [{endpoint: {address: {socket_address: {address: "login.example.com", port_value: 443}}}}]}] + transport_socket: + name: envoy.transport_sockets.tls + typed_config: + "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext + sni: "login.example.com" + common_tls_context: + validation_context: + trusted_ca: {filename: "/etc/gateway/jwt/ca.pem"} + match_typed_subject_alt_names: [{san_type: DNS, matcher: {exact: "login.example.com"}}] + typed_extension_protocol_options: + envoy.extensions.upstreams.http.v3.HttpProtocolOptions: + "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions + explicit_http_config: {http_protocol_options: {}} diff --git a/internal/render/testdata/full-before-ask-unlisted.yaml b/internal/render/testdata/full-before-ask-unlisted.yaml new file mode 100644 index 0000000..8b66417 --- /dev/null +++ b/internal/render/testdata/full-before-ask-unlisted.yaml @@ -0,0 +1,95 @@ +# yaml-language-server: $schema=../../../schema/proxyfile.schema.json +# examples/full/yaml/proxyfile.yaml as it was before origins..ask_unlisted, kept here because the +# example itself may take the key: the file every key but a few writes, none of its environments asking about an +# origin no list holds. full-before-ask-unlisted.envoy.yaml is the Envoy file the generator wrote for it then. +listen: 10000 +admin: 9901 +tls: + certificate: /etc/gateway/tls/certificate.pem + key: /etc/gateway/tls/key.pem + clients: {ca: /etc/gateway/tls/clients-ca.pem} +client_address: connection +limits: + connections: 4096 + request_headers: {size: 96KiB, count: 150} +timeouts: + request: none + idle: 90s + upstream_idle: 45s +services: + shop: + http: 8080 + grpc: 8081 + addresses: ["10.0.1.11", "10.0.1.12"] + balance: least_requests + health: {path: /healthz, grpc: true, interval: 10s, timeout: 1s, healthy: 2, unhealthy: 3} + accounts: {grpc: 7070, http: 7070, host_header: "127.0.0.1:7070"} + catalog: {http: 8090, address: catalog.internal.example, balance: hash, hash: {header: x-session-id}} +dns: {resolver: "10.0.0.2:53"} +auth: + ask: accounts /auth/check + timeout: 1500ms + enabled: true + when_unavailable: allow + only_with_header: authorization + send: [authorization, x-country] + accept: [x-user-*, x-tier-*] + send_request: true + jwt: + issuer: https://login.example.com + audiences: [api.example.com, admin.example.com] + keys: https://login.example.com/.well-known/jwks.json + ca: /etc/gateway/jwt/ca.pem + header: x-access-token + optional: true + claims: {x-subject: sub, x-roles: realm.roles} +remove_from_clients: [x-user-*, x-client-*, x-tier-*, x-gateway-*] +cors: + allow_methods: "*" + allow_headers: "*" + expose_headers: "Content-Disposition,X-Request-Id" + max_age: "600" +origins: + live: + hosts: [api.example.com, api.example.org] + origins: ["https://example.com", "https://www.example.com"] + patterns: ["https://*.example.com"] + test: + hosts: [api.test.example.com] + origins: ["http://localhost:3000", "https://test.example.com"] + patterns: ["https://*.test.example.com"] + local: + hosts: [127.0.0.1, localhost] + origins: [] + patterns: ["http://*.example.com:*", "http://localhost:*"] +routes: + - {name: accounts-events, pattern: "^/events/[a-z0-9-]+$", to: accounts, auth: off} + - rpc: + retries: 1 + rate_limit: {requests: 100, per: 1s, by: all} + to: + example.shop.*: {service: shop, name: shop} + "*": accounts + - {name: accounts-webhooks, path: /api/webhooks, method: POST, to: accounts, rewrite: /hooks/payments, auth: off} + - {name: catalog, prefix: /catalog/, to: catalog, rate_limit: {requests: 20, per: 1s, burst: 10, by: client}} + - {name: shop, prefix: /, to: shop, retries: 1} +rpc: + methods: + - {service: example.shop.v1.CartService, method: GetCart, action: browse} + - {service: example.accounts.v1.ProfileService, method: GetProfile} + - {service: example.shop.v1.CartService, method: AddItem, action: buy, reports: [browse]} +log: {status_from: 400, sample: 1%} +tracing: + provider: + otel: + endpoint: 10.0.3.40:4317 + service: example-gateway + sample: {rate: 10%} + tags: + environment: {env: APP_ENVIRONMENT, default: local} + request_id: {header: x-request-id} + path_in_url: true +envoy: + namespace: example.gateway + heap: 256MiB + connect_bridge: true diff --git a/internal/render/unlisted_test.go b/internal/render/unlisted_test.go new file mode 100644 index 0000000..676f028 --- /dev/null +++ b/internal/render/unlisted_test.go @@ -0,0 +1,368 @@ +package render + +import ( + "bytes" + "fmt" + "path/filepath" + "reflect" + "regexp" + "slices" + "strings" + "testing" + + "github.com/kitecorp/proxyfile/v2/internal/testsupport" +) + +// An environment may put a browser origin that none of its origins and patterns holds to a check of its own, +// origins..ask_unlisted, asking it the environment's question: a gateway whose customers bring their +// own domains cannot list them all. The Envoy output gains one HTTP filter, a second ext_authz before CORS, which asks +// the service and path ask_unlisted names, sends the Origin and the question, and refuses an origin it could not ask +// about; it runs on the routes that take such an origin, in that environment alone, and nowhere else. Every other +// filter, every other route and every other environment are written as they are without the key. What Envoy answers +// with it, a preflight and a request admitted with Access-Control-Allow-Origin, a refusal 403, a listed origin never +// asked, is the conformance battery's scenario "an origin no list holds" (conformance/scenarios_test.go), run on +// Envoy 1.40.2: this test holds the file's parts, the battery what they do. +func TestAskUnlisted(t *testing.T) { + // Without the key a file renders the bytes it rendered before the key existed: examples/full's YAML form, every key + // but a few, as the base of this change rendered it. -update never rewrites these two files, where it rewrites + // examples/full once the example takes the key. + t.Run("without the key, the file renders the bytes it rendered before the key", func(t *testing.T) { + dir := t.TempDir() + files, problems := render(Request{Proxyfile: filepath.Join("testdata", "full-before-ask-unlisted.yaml"), + Out: filepath.Join(dir, "envoy.yaml")}) + if problems != nil { + t.Fatalf("render problems = %q, want none", testsupport.ProblemStrings(problems)) + } + want := testsupport.ReadFile(t, filepath.Join("testdata", "full-before-ask-unlisted.envoy.yaml")) + if !bytes.Equal(files[0].Bytes, want) { + line, before, now := testsupport.FirstDifferentLine(want, files[0].Bytes) + t.Errorf("envoy.yaml differs first on line %d:\n before the key: %s\n rendered: %s", line, before, now) + } + }) + + manager := []any{"static_resources", "listeners", 0, "filter_chains", 0, "filters", 0, "typed_config"} + filtersAt := slices.Concat(manager, []any{"http_filters"}) + hostsAt := slices.Concat(manager, []any{"route_config", "virtual_hosts"}) + without := renderedTree(t, unlistedProxyfile(false)) + with := renderedTree(t, unlistedProxyfile(true)) + withoutFilters, withFilters := listAt(t, without, filtersAt...), listAt(t, with, filtersAt...) + + // The filter the key adds is the one whose removal leaves the filters of the file without the key, each as written + // there and in its order. + added := -1 + for i := range withFilters { + if firstDifference(withoutFilters, slices.Delete(slices.Clone(withFilters), i, i+1), "") == "" { + added = i + break + } + } + if added < 0 { + t.Fatalf("the filters with ask_unlisted are %v, want those without it, %v, each as written there, and one more", + names(withFilters), names(withoutFilters)) + } + filter := withFilters[added] + name, _ := valueAt(filter, "name").(string) + check := extAuthz(filter) + if check == nil { + t.Fatalf("the filter ask_unlisted adds, %q, is not ext_authz: %v", name, filter) + } + withoutHosts, withHosts := listAt(t, without, hostsAt...), listAt(t, with, hostsAt...) + if len(withHosts) != 2 || valueAt(withHosts[0], "name") != "live" || valueAt(withHosts[1], "name") != "test" { + t.Fatalf("the virtual hosts are %v, want live and test", names(withHosts)) + } + live, test := withHosts[0], withHosts[1] + liveRoutes := listAt(t, live, "routes") + // The routes that take an origin no list holds are the ones the key adds to live: each matches on the Origin header, + // which none of the file's own routes reads. + var extra, own []any + for _, route := range liveRoutes { + if matchesOrigin(route) { + extra = append(extra, route) + } else { + own = append(own, route) + } + } + + t.Run("the check sits before CORS", func(t *testing.T) { + cors := slices.IndexFunc(withFilters, func(f any) bool { return valueAt(f, "name") == "envoy.filters.http.cors" }) + if cors < 0 || added > cors { + t.Errorf("the filters are %v; want the check, %q, before envoy.filters.http.cors", names(withFilters), name) + } + }) + + t.Run("the check asks the service and path ask_unlisted names, about the Origin", func(t *testing.T) { + if got := valueAt(check, "http_service", "server_uri", "cluster"); got != "gatekeeper_http" { + t.Errorf("server_uri.cluster = %v, want gatekeeper_http", got) + } + if got := valueAt(check, "http_service", "path_override"); got != "/origin" { + t.Errorf("path_override = %v, want /origin", got) + } + if patterns, _ := valueAt(check, "allowed_headers", "patterns").([]any); !slices.ContainsFunc(patterns, exactly("origin")) { + t.Errorf("allowed_headers.patterns = %v, want one that is {exact: origin}", patterns) + } + }) + + // A check that cannot be asked admits no origin. That a 5xx and no answer in time are refused is the battery's to + // show (its rows of a check that answers 503 and one that answers late); this pins the setting that would let such + // a request through. + t.Run("the check is not written to let a request through when it fails", func(t *testing.T) { + if got := valueAt(check, "failure_mode_allow"); got == true { + t.Errorf("failure_mode_allow = %v, want false or not written", got) + } + }) + + // The question reaches the check in x-gateway-question, set over any copy a client sent: by the check's own + // headers_to_add, or, as an RPC route's question travels, by each added route's header mutation, which the check's + // allowed_headers lets through. + t.Run("the check is asked the environment's question", func(t *testing.T) { + if len(extra) == 0 { + t.Fatal("live has no route that matches on the Origin header to carry the question") + } + headersToAdd, _ := valueAt(check, "http_service", "authorization_request", "headers_to_add").([]any) + byCheck := slices.ContainsFunc(headersToAdd, func(h any) bool { + return reflect.DeepEqual(h, map[string]any{"key": "x-gateway-question", "value": "browser-origin"}) + }) + patterns, _ := valueAt(check, "allowed_headers", "patterns").([]any) + byRoutes := slices.ContainsFunc(patterns, exactly("x-gateway-question")) + want := map[string]any{"append": map[string]any{"header": map[string]any{"key": "x-gateway-question", "value": "browser-origin"}, + "append_action": "OVERWRITE_IF_EXISTS_OR_ADD"}} + for _, route := range extra { + mutations, _ := valueAt(route, "typed_per_filter_config", "envoy.filters.http.header_mutation", "mutations", + "request_mutations").([]any) + byRoutes = byRoutes && slices.ContainsFunc(mutations, func(m any) bool { return reflect.DeepEqual(m, want) }) + } + if !byCheck && !byRoutes { + t.Errorf("the check's headers_to_add = %v and its allowed_headers.patterns = %v; want x-gateway-question: "+ + "browser-origin in headers_to_add, or {exact: x-gateway-question} beside each added route's mutation %v", + headersToAdd, patterns, want) + } + }) + + t.Run("the check runs on the routes that take an origin no list holds in live, and nowhere else", func(t *testing.T) { + if len(extra) == 0 { + t.Fatalf("live's routes are %v; want one or more that match on the Origin header", names(liveRoutes)) + } + off := valueAt(filter, "disabled") == true + routeConfig := valueAt(with, slices.Concat(manager, []any{"route_config"})...) + // withHosts[0] is live. + for i, host := range withHosts { + for _, route := range listAt(t, host, "routes") { + want := i == 0 && slices.ContainsFunc(extra, func(r any) bool { return reflect.DeepEqual(r, route) }) + if got := runsOn(off, routeConfig, host, route, name); got != want { + t.Errorf("virtual host %v, route %v: the check runs = %t, want %t", valueAt(host, "name"), + valueAt(route, "name"), got, want) + } + } + } + }) + + t.Run("every other route and environment is written as without the key", func(t *testing.T) { + if d := firstDifference(withoutHosts[1], stripHost(test, name), "test"); d != "" { + t.Errorf("the environment that writes no ask_unlisted: %s", d) + } + var kept []any + for _, route := range own { + kept = append(kept, strip(route, name)) + } + if d := firstDifference(valueAt(withoutHosts[0], "routes"), kept, "live.routes"); d != "" { + t.Errorf("live's routes but those ask_unlisted adds: %s", d) + } + if d := firstDifference(valueAt(without, "static_resources", "clusters"), valueAt(with, "static_resources", "clusters"), + "clusters"); d != "" { + t.Errorf("the clusters: %s", d) + } + }) +} + +// Envoy takes the first route that matches, so the copies an environment adds for an origin no list holds stand in the +// order of their routes, between the refused route and the routes themselves: an origin the check admits then takes +// the route a listed origin takes. Here an auth-off / comes after /account/, so a copy of / ahead of the copy of +// /account/ would send an admitted origin's /account/x to the public route with the auth check off. +func TestAskUnlistedCopiesKeepTheRouteOrder(t *testing.T) { + routes := "routes:\n - {name: files, prefix: /files/, to: app}\n - {name: app, prefix: /, to: app}\n" + proxyfile := unlistedProxyfile(true) + if !strings.HasSuffix(proxyfile, routes) { + t.Fatalf("unlistedProxyfile does not end with the routes %q to replace", routes) + } + proxyfile = strings.TrimSuffix(proxyfile, routes) + + "routes:\n - {name: account, prefix: /account/, to: accounts}\n - {name: public, prefix: /, to: app, auth: off}\n" + hosts := listAt(t, renderedTree(t, proxyfile), + "static_resources", "listeners", 0, "filter_chains", 0, "filters", 0, "typed_config", "route_config", "virtual_hosts") + if got := valueAt(hosts[0], "name"); got != "live" { + t.Fatalf("the first virtual host is %v, want live", got) + } + // Each route as its name, its prefix, whether it takes only an origin no list holds, and whether the auth check is + // off on it. + var got []string + for _, route := range listAt(t, hosts[0], "routes") { + prefix, _ := valueAt(route, "match", "prefix").(string) + line := strings.TrimSpace(fmt.Sprintf("%v %s", valueAt(route, "name"), prefix)) + if matchesOrigin(route) { + line += ", a copy" + } + if valueAt(route, "typed_per_filter_config", "envoy.filters.http.ext_authz", "disabled") == true { + line += ", auth off" + } + got = append(got, line) + } + want := []string{ + "refused:dot-segment-with-parameter", + "account /account/, a copy", + "public /, a copy, auth off", + "account /account/", + "public /, auth off", + } + if !slices.Equal(got, want) { + t.Errorf("live's routes are %q, want %q", got, want) + } +} + +// nginx and HAProxy cannot carry the check of an origin no list holds, so each refuses the file by the two keys, where +// they are written, as docs/portability.md requires of a key a target cannot carry; the text after the colon is what +// that proxy offers instead, which this test leaves to the declaration. +func TestAskUnlistedRefusedByNginxAndHAProxy(t *testing.T) { + refusal := regexp.MustCompile(`^(g\.yaml:[0-9]+:[0-9]+): "([^"]+)" is refused by --target ([a-z]+): (.+)$`) + for _, target := range []string{"nginx", "haproxy"} { + t.Run(target, func(t *testing.T) { + dir := t.TempDir() + testsupport.WriteFile(t, filepath.Join(dir, "g.yaml"), unlistedProxyfile(true)) + files, problems := render(Request{Proxyfile: filepath.Join(dir, "g.yaml"), Out: filepath.Join(dir, "out"), Target: target}) + if files != nil { + t.Errorf("render returned files %q next to problems", paths(files)) + } + var got []string + for _, problem := range testsupport.ProblemStringsIn(dir, problems) { + parts := refusal.FindStringSubmatch(problem) + if parts == nil { + got = append(got, "not a refusal: "+problem) + continue + } + got = append(got, strings.Join(parts[1:4], " ")) + } + want := []string{ + "g.yaml:11:5 origins..ask_unlisted " + target, + "g.yaml:12:5 origins..question " + target, + } + if !slices.Equal(got, want) { + t.Errorf("problems = %q\nread as %q, want %q", testsupport.ProblemStringsIn(dir, problems), got, want) + } + }) + } +} + +// unlistedProxyfile is a gateway with the auth check and two environments, live and test, each admitting one origin +// by its list, and two routes. With ask, live puts an origin its lists do not hold to gatekeeper /origin, asking +// browser-origin, on lines 11 and 12; test never does. +func unlistedProxyfile(ask bool) string { + var b strings.Builder + b.WriteString("listen: 8000\nservices:\n app: {http: 3000}\n accounts: {http: 7070}\n gatekeeper: {http: 7080}\n") + b.WriteString("auth: {ask: accounts /check, timeout: 1s, enabled: true, when_unavailable: allow}\n") + b.WriteString("origins:\n live:\n hosts: [api.example.com]\n origins: [\"https://www.example.com\"]\n") + if ask { + b.WriteString(" ask_unlisted: gatekeeper /origin\n question: browser-origin\n") + } + b.WriteString(" test:\n hosts: [api.test.example.com]\n origins: [\"https://test.example.com\"]\n") + b.WriteString("routes:\n - {name: files, prefix: /files/, to: app}\n - {name: app, prefix: /, to: app}\n") + return b.String() +} + +// renderedTree renders proxyfile, written to g.yaml in a folder of its own, for envoy and returns the decoded tree. +func renderedTree(t *testing.T, proxyfile string) any { + t.Helper() + dir := t.TempDir() + testsupport.WriteFile(t, filepath.Join(dir, "g.yaml"), proxyfile) + files, problems := render(Request{Proxyfile: filepath.Join(dir, "g.yaml"), Out: filepath.Join(dir, "envoy.yaml")}) + if problems != nil { + t.Fatalf("render problems = %q, want none", testsupport.ProblemStringsIn(dir, problems)) + } + return decode(t, files[0].Bytes) +} + +// extAuthzType is the type of ext_authz's settings. +const extAuthzType = "type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthz" + +// extAuthz returns the ext_authz settings of an HTTP filter, its typed_config or, with a matcher around them, the +// matcher's extension_config (filter-ext-authz.yaml writes both forms), or nil when the filter is not ext_authz. +func extAuthz(filter any) map[string]any { + for _, steps := range [][]any{{"typed_config"}, {"typed_config", "extension_config", "typed_config"}} { + if settings, ok := valueAt(filter, steps...).(map[string]any); ok && settings["@type"] == extAuthzType { + return settings + } + } + return nil +} + +// exactly matches a string matcher that compares a header's name to name, case by case, as ext_authz's lists write one. +func exactly(name string) func(any) bool { + return func(pattern any) bool { return reflect.DeepEqual(pattern, map[string]any{"exact": name}) } +} + +// matchesOrigin reports whether a route's match reads the Origin header. +func matchesOrigin(route any) bool { + headers, _ := valueAt(route, "match", "headers").([]any) + return slices.ContainsFunc(headers, func(h any) bool { return valueAt(h, "name") == "origin" }) +} + +// runsOn reports whether the HTTP filter named name, disabled by default when off, runs on route: the route's own +// entry for it under typed_per_filter_config decides, or its virtual host's when the route has none, or the route +// table's when neither has one. An entry that says disabled: true, as the route's FilterConfig or as ext_authz's own +// ExtAuthzPerRoute, keeps the check from running, and any other entry is the route-specific configuration that turns +// on a filter disabled by default (Envoy's "Route based filter chain", http_filters.rst); no entry at all leaves the +// filter as the listener writes it. +func runsOn(off bool, routeConfig, host, route any, name string) bool { + for _, holder := range []any{route, host, routeConfig} { + if entry := valueAt(holder, "typed_per_filter_config", name); entry != nil { + return valueAt(entry, "disabled") != true + } + } + return !off +} + +// strip returns a copy of a route or a virtual host without its typed_per_filter_config entry for the filter named +// name, and without typed_per_filter_config when nothing else is left in it, so it compares with the same part of a +// file that has no such filter. +func strip(node any, name string) any { + m, ok := node.(map[string]any) + if !ok { + return node + } + entries, ok := m["typed_per_filter_config"].(map[string]any) + if !ok { + return node + } + copied := map[string]any{} + for key, value := range m { + copied[key] = value + } + kept := map[string]any{} + for key, value := range entries { + if key != name { + kept[key] = value + } + } + delete(copied, "typed_per_filter_config") + if len(kept) > 0 { + copied["typed_per_filter_config"] = kept + } + return copied +} + +// stripHost is strip of a virtual host and of each of its routes. +func stripHost(host any, name string) any { + stripped, ok := strip(host, name).(map[string]any) + if !ok { + return host + } + copied := map[string]any{} + for key, value := range stripped { + copied[key] = value + } + if routes, ok := copied["routes"].([]any); ok { + var kept []any + for _, route := range routes { + kept = append(kept, strip(route, name)) + } + copied["routes"] = kept + } + return copied +} diff --git a/schema/proxyfile.schema.json b/schema/proxyfile.schema.json index 9361c55..69de4c5 100644 --- a/schema/proxyfile.schema.json +++ b/schema/proxyfile.schema.json @@ -464,8 +464,18 @@ { "additionalProperties": { "additionalProperties": false, + "dependentRequired": { + "question": [ + "ask_unlisted" + ] + }, "description": "One environment: its hosts and the browser origins it admits.", "properties": { + "ask_unlisted": { + "description": "The service and the path asked about a browser origin that neither origins nor patterns holds, and that is not on one of the hosts; an origin it admits is answered as a listed one.", + "pattern": "^[a-z][a-z0-9-]* /[^\\t\\n\\f\\r ]*$", + "type": "string" + }, "hosts": { "description": "The host names the environment serves, without a port.", "items": { @@ -486,6 +496,11 @@ "type": "string" }, "type": "array" + }, + "question": { + "description": "The question sent to the check ask_unlisted names, in x-gateway-question.", + "pattern": "^[A-Za-z0-9._-]+$", + "type": "string" } }, "required": [