From 36c3d2acc32a4088fde5b295e02886a6e1316a27 Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Thu, 26 Nov 2026 19:49:36 -0800 Subject: [PATCH 1/2] feat(proxy): add proxy.trustedProxies for forwarded-header trust Behind a CDN or another reverse proxy, the managed Traefik sees the front proxy as every request's peer and overwrites the X-Forwarded-For it wrote, so applications cannot learn the client address. proxy.trustedProxies lists the front proxy's CIDR prefixes, and Onebox renders them as forwardedHeaders.trustedIPs on every entrypoint in its generated static configuration: web, websecure and each proxy.entrypoints listener. Entries must be canonical IPv4 or IPv6 prefixes. Bare addresses, prefixes with host bits set (the error names the canonical form), IPv4-mapped IPv6 prefixes and 0.0.0.0/0 or ::/0 are refused; the list is sorted and deduplicated so its order never changes the configuration. The field requires a Onebox-managed proxy and cannot be combined with a project-owned traefik.yml, mirroring proxy.dnsChallenge. An absent or empty list renders the static configuration byte for byte as before, pinned by digest, so upgrading does not restart anyone's proxy. Declaring it changes only the configuration identity, which the plan reports as "restart Traefik (configuration changed)". ob preview prints the effective list. An opt-in e2e test runs the real Traefik image and checks that a trusted peer keeps its X-Forwarded-For while an untrusted one has it replaced. Co-Authored-By: Claude Opus 5.5 --- .../v1alpha2/application.schema.json | 12 ++ cmd/ob/preview.go | 19 +- cmd/ob/preview_test.go | 33 ++++ e2e/trusted_proxies_test.go | 135 ++++++++++++++ internal/app/load.go | 5 + internal/app/trusted_proxies_test.go | 95 ++++++++++ internal/app/types.go | 4 + internal/app/validate.go | 61 +++++++ internal/engine/proxy_converge.go | 2 +- internal/engine/proxy_converge_test.go | 50 ++++++ internal/onebox/proxy_execute_test.go | 2 +- internal/proxy/proxy.go | 74 ++++++-- internal/proxy/proxy_test.go | 10 +- internal/proxy/trusted_proxies_test.go | 165 ++++++++++++++++++ .../v1alpha2/application.schema.json | 12 ++ .../docs/docs/reference/fields/proxy.mdx | 3 +- .../docs/docs/reference/project-file.mdx | 61 +++++++ 17 files changed, 719 insertions(+), 24 deletions(-) create mode 100644 e2e/trusted_proxies_test.go create mode 100644 internal/app/trusted_proxies_test.go create mode 100644 internal/proxy/trusted_proxies_test.go diff --git a/api/application/v1alpha2/application.schema.json b/api/application/v1alpha2/application.schema.json index 8666f300..8feb8bab 100644 --- a/api/application/v1alpha2/application.schema.json +++ b/api/application/v1alpha2/application.schema.json @@ -946,6 +946,18 @@ "default": "onebox-ingress", "description": "External container network shared with routed workloads; default and Onebox's derived application and service network names are reserved.", "type": "string" + }, + "trustedProxies": { + "description": "CIDR prefixes of the reverse proxies or CDN in front of the managed proxy. Requests whose peer address falls in one of them keep their X-Forwarded-For and related forwarded headers instead of having the managed proxy overwrite them. Applies to every entrypoint in Onebox's generated static configuration. Each entry is a canonical IPv4 or IPv6 prefix such as 192.0.2.0/24; a bare address, a prefix with host bits set, and 0.0.0.0/0 or ::/0 are refused. Requires a Onebox-managed proxy and cannot be combined with a project-owned traefik.yml or traefik.yaml.", + "examples": [ + [ + "192.0.2.0/24" + ] + ], + "items": { + "type": "string" + }, + "type": "array" } }, "type": "object" diff --git a/cmd/ob/preview.go b/cmd/ob/preview.go index e66ed9f5..1f842cce 100644 --- a/cmd/ob/preview.go +++ b/cmd/ob/preview.go @@ -78,10 +78,16 @@ func addPreviewCommand(root *cobra.Command, g *globalFlags) { } services[name] = string(doc) } - return writeFiniteSuccess(cmd, g, map[string]any{ + envelope := map[string]any{ "environment": g.Env, "release": release, "digest": rendered.Digest, "redacted": true, "runtime": string(body), "services": services, - }) + } + // Present only when declared, so a project without it keeps + // the envelope it always had. + if len(p.Proxy.TrustedProxies) > 0 { + envelope["proxy"] = map[string]any{"trustedProxies": p.Proxy.TrustedProxies} + } + return writeFiniteSuccess(cmd, g, envelope) } if digestOnly { @@ -100,6 +106,15 @@ func addPreviewCommand(root *cobra.Command, g *globalFlags) { if !showRaw { fmt.Fprintln(out, "# environment values redacted; --raw shows them") } + // The runtime below is the release; forwarded-header trust lives in + // the managed proxy's static configuration, which no release + // carries. Without this line the one setting that decides whether + // a client address is believed would be invisible here. It prints + // the effective list: validated, sorted and deduplicated. + if len(p.Proxy.TrustedProxies) > 0 { + fmt.Fprintf(out, "# proxy trustedProxies %s: every managed entrypoint keeps X-Forwarded-For from these peers\n", + strings.Join(p.Proxy.TrustedProxies, ", ")) + } if _, err := out.Write(body); err != nil { return err } diff --git a/cmd/ob/preview_test.go b/cmd/ob/preview_test.go index 0001dbdf..fdea4fd1 100644 --- a/cmd/ob/preview_test.go +++ b/cmd/ob/preview_test.go @@ -161,3 +161,36 @@ spec: t.Error("the referenced file must be left alone") } } + +// Forwarded-header trust lives in the proxy's static configuration, which no +// release carries, so preview names the effective list itself: validated, +// sorted and deduplicated. A project without it previews exactly as before. +func TestPreviewShowsTrustedProxies(t *testing.T) { + dir := t.TempDir() + writeFile(t, dir, "ob.yml", previewProject) + without, err := run(t, dir, "preview") + if err != nil { + t.Fatalf("preview failed: %v\n%s", err, without) + } + if strings.Contains(without, "trustedProxies") { + t.Fatalf("preview without the field mentions it:\n%s", without) + } + + writeFile(t, dir, "ob.yml", previewProject+" proxy:\n trustedProxies: [2001:db8::/32, 192.0.2.0/24, 192.0.2.0/24]\n") + out, err := run(t, dir, "preview") + if err != nil { + t.Fatalf("preview failed: %v\n%s", err, out) + } + want := "# proxy trustedProxies 192.0.2.0/24, 2001:db8::/32: every managed entrypoint keeps X-Forwarded-For from these peers\n" + if !strings.Contains(out, want) { + t.Fatalf("preview does not show the effective trusted list %q:\n%s", want, out) + } + + structured, err := run(t, dir, "preview", "--output", "json") + if err != nil { + t.Fatalf("preview --output json failed: %v\n%s", err, structured) + } + if !strings.Contains(strings.Join(strings.Fields(structured), ""), `"proxy":{"trustedProxies":["192.0.2.0/24","2001:db8::/32"]}`) { + t.Fatalf("structured preview does not carry the trusted list:\n%s", structured) + } +} diff --git a/e2e/trusted_proxies_test.go b/e2e/trusted_proxies_test.go new file mode 100644 index 00000000..f22c7d6a --- /dev/null +++ b/e2e/trusted_proxies_test.go @@ -0,0 +1,135 @@ +package e2e + +import ( + "context" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/labstack/onebox/internal/app" + "github.com/labstack/onebox/internal/proxy" +) + +// proxy.trustedProxies is rendered into the managed static configuration and +// loaded by the real Traefik image exactly as staged. A request from a peer in +// a trusted prefix keeps the X-Forwarded-For it arrived with, and Traefik +// appends the peer; a request from any other peer has the header replaced by +// the peer's own address. The unit tests can only assert the YAML; this proves +// Traefik reads it that way on an Onebox-declared entrypoint. +func TestTrustedProxiesKeepForwardedHeadersOnlyFromTrustedPeers(t *testing.T) { + gate(t) + ctx := context.Background() + pid := os.Getpid() + application := fmt.Sprintf("obtp%d", pid) + network := application + "_net" + backend, traefik := application+"-backend", application+"-traefik" + // A private /24 chosen per run so that every address, and so trust, is + // fixed by the test rather than by Docker's address pool. + subnet := fmt.Sprintf("10.%d.%d", 200+pid%50, pid%250) + trusted := subnet + ".16/28" + trustedClient, untrustedClient := subnet+".20", subnet+".40" + + body := fmt.Sprintf(`apiVersion: onebox.run/v1alpha2 +kind: Application +metadata: {name: %s} +spec: + environments: + production: {server: root@localhost} + workloads: + web: + image: busybox:1.37 + routes: + - {hostname: app.example.com, port: 80, entrypoint: plain, tls: None} + proxy: + entrypoints: {plain: {port: 8081}} + trustedProxies: [%s] +`, application, trusted) + project, err := app.LoadBytes([]byte(body), filepath.Join(t.TempDir(), "ob.yml")) + if err != nil { + t.Fatal(err) + } + staging := t.TempDir() + if _, err := proxy.StageForAppManaged("", staging, "", "", project.Name, network, project.Proxy.Entrypoints, + project.HasExactTerminatingTLS(), project.HasWildcardTerminatingTLS(), project.Proxy.DNSChallenge, project.Proxy.TrustedProxies); err != nil { + t.Fatal(err) + } + // Discovery's output is replaced by one router, so the request's path to + // the backend does not depend on Host matching inside busybox wget. + router := "http:\n routers:\n probe:\n rule: PathPrefix(`/`)\n entryPoints: [plain]\n service: probe\n" + + " services:\n probe:\n loadBalancer:\n servers:\n - url: http://" + backend + ":80\n" + if err := os.WriteFile(filepath.Join(staging, "dynamic", "probe.yml"), []byte(router), 0o644); err != nil { + t.Fatal(err) + } + // The staged files are written for the proxy's non-root user; this test + // runs Traefik as the image's default user, which must be able to read them. + for _, dir := range []string{filepath.Join(staging, "config"), filepath.Join(staging, "dynamic")} { + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + for _, entry := range entries { + if !entry.IsDir() { + if err := os.Chmod(filepath.Join(dir, entry.Name()), 0o644); err != nil { + t.Fatal(err) + } + } + } + } + + docker := func(args ...string) (string, error) { + out, err := exec.CommandContext(ctx, "docker", args...).CombinedOutput() + return strings.TrimSpace(string(out)), err + } + must := func(args ...string) string { + t.Helper() + out, err := docker(args...) + if err != nil { + t.Fatalf("docker %s: %v\n%s", strings.Join(args, " "), err, out) + } + return out + } + t.Cleanup(func() { + cleanupCtx, cancel := testCleanupContext() + defer cancel() + _ = exec.CommandContext(cleanupCtx, "docker", "rm", "-f", traefik, backend).Run() + _ = exec.CommandContext(cleanupCtx, "docker", "network", "rm", network).Run() + }) + must("network", "create", "--subnet", subnet+".0/24", network) + // The backend answers with the X-Forwarded-For header it received. + must("run", "-d", "--name", backend, "--network", network, "--ip", subnet+".3", "busybox:1.37", "sh", "-c", + `mkdir -p /www/cgi-bin && printf '#!/bin/sh\necho Content-Type: text/plain\necho\necho "xff=$HTTP_X_FORWARDED_FOR"\n' > /www/cgi-bin/h && chmod +x /www/cgi-bin/h && exec httpd -f -p 80 -h /www`) + must("run", "-d", "--name", traefik, "--network", network, "--ip", subnet+".2", + "-v", filepath.Join(staging, "config")+":/etc/traefik:ro", + "-v", filepath.Join(staging, "dynamic")+":/etc/traefik/dynamic:ro", + "--tmpfs", proxy.AcmeStorageDir, + proxy.DefaultImage) + + request := func(client string) (string, error) { + return docker("run", "--rm", "--network", network, "--ip", client, "busybox:1.37", + "wget", "-qO-", "-T", "2", "--header", "X-Forwarded-For: 203.0.113.7", "http://"+traefik+":8081/cgi-bin/h") + } + deadline := time.Now().Add(60 * time.Second) + got, err := request(trustedClient) + for err != nil && time.Now().Before(deadline) { + time.Sleep(time.Second) + got, err = request(trustedClient) + } + if err != nil { + logs, _ := docker("logs", traefik) + t.Fatalf("no response through Traefik: %v\n%s\ntraefik:\n%s", err, got, logs) + } + if want := "xff=203.0.113.7, " + trustedClient; got != want { + t.Errorf("trusted peer: backend saw %q, want %q", got, want) + } + got, err = request(untrustedClient) + if err != nil { + t.Fatalf("untrusted request: %v\n%s", err, got) + } + if want := "xff=" + untrustedClient; got != want { + t.Errorf("untrusted peer: backend saw %q, want %q", got, want) + } +} diff --git a/internal/app/load.go b/internal/app/load.go index 576ac76a..a588c1fd 100644 --- a/internal/app/load.go +++ b/internal/app/load.go @@ -527,6 +527,11 @@ func crossFieldRules(p *Spec) error { if p.Proxy.DNSChallenge != nil && (!p.Proxy.Managed || p.Proxy.Kind == "none") { return errf("project_invalid", "proxy.dns_challenge", "", "dns_challenge requires a Onebox-managed proxy") } + if len(p.Proxy.TrustedProxies) > 0 && (!p.Proxy.Managed || p.Proxy.Kind == "none") { + return errf("project_invalid", "proxy.trusted_proxies", "", + "trustedProxies requires a Onebox-managed proxy, which renders the entrypoints that trust them; "+ + "an operator-owned proxy sets forwarded-header trust in its own configuration") + } if p.Proxy.Managed && p.HasWildcardTerminatingTLS() && p.Proxy.DNSChallenge == nil && p.Proxy.Config == "" { return errf("project_invalid", "proxy.dns_challenge", "", "managed terminating wildcard routes require an ACME DNS challenge; declare proxy.dns_challenge and provide its credentials through proxy.config/.env") diff --git a/internal/app/trusted_proxies_test.go b/internal/app/trusted_proxies_test.go new file mode 100644 index 00000000..09568a44 --- /dev/null +++ b/internal/app/trusted_proxies_test.go @@ -0,0 +1,95 @@ +package app + +import ( + "errors" + "strings" + "testing" +) + +func TestTrustedProxiesValidation(t *testing.T) { + for _, tc := range []struct { + name string + entries string + want string // error text; empty means valid + path string // public error path + result []string // normalised list when valid + }{ + {"ipv4 and ipv6", `["192.0.2.0/24", "2001:db8::/32"]`, "", "", []string{"192.0.2.0/24", "2001:db8::/32"}}, + {"single address as /32 and /128", `["192.0.2.7/32", "2001:db8::7/128"]`, "", "", []string{"192.0.2.7/32", "2001:db8::7/128"}}, + {"sorted, ipv4 first", `["2001:db8::/32", "198.51.100.0/24", "192.0.2.0/24", "192.0.2.0/25"]`, "", "", + []string{"192.0.2.0/24", "192.0.2.0/25", "198.51.100.0/24", "2001:db8::/32"}}, + {"duplicates collapse", `["192.0.2.0/24", "2001:db8::/32", "192.0.2.0/24"]`, "", "", []string{"192.0.2.0/24", "2001:db8::/32"}}, + {"empty list", `[]`, "", "", nil}, + {"host bits set", `["10.20.0.5/24"]`, "write 10.20.0.0/24", "spec.proxy.trustedProxies[0]", nil}, + {"ipv6 host bits set", `["2001:db8::1/32"]`, "write 2001:db8::/32", "spec.proxy.trustedProxies[0]", nil}, + {"ipv6 not compressed", `["2001:0db8:0:0:0:0:0:0/32"]`, "write 2001:db8::/32", "spec.proxy.trustedProxies[0]", nil}, + {"ipv6 upper case", `["2001:DB8::/32"]`, "write 2001:db8::/32", "spec.proxy.trustedProxies[0]", nil}, + {"bare ipv4", `["192.0.2.0/24", "192.0.2.7"]`, "write 192.0.2.7/32", "spec.proxy.trustedProxies[1]", nil}, + {"bare ipv6", `["2001:db8::7"]`, "write 2001:db8::7/128", "spec.proxy.trustedProxies[0]", nil}, + {"ipv4 everything", `["0.0.0.0/0"]`, "trust every peer", "spec.proxy.trustedProxies[0]", nil}, + {"ipv6 everything", `["::/0"]`, "trust every peer", "spec.proxy.trustedProxies[0]", nil}, + {"ipv4-mapped ipv6", `["::ffff:0.0.0.0/96"]`, "IPv4-mapped", "spec.proxy.trustedProxies[0]", nil}, + {"not a prefix", `["cdn.example.com"]`, "not a CIDR prefix", "spec.proxy.trustedProxies[0]", nil}, + {"zone", `["fe80::%eth0/64"]`, "not a CIDR prefix", "spec.proxy.trustedProxies[0]", nil}, + } { + t.Run(tc.name, func(t *testing.T) { + p, err := loadFixtureBytes([]byte(min+"proxy: {trusted_proxies: "+tc.entries+"}\n"), "ob.yml") + if tc.want == "" { + if err != nil { + t.Fatalf("valid trusted proxies: %v", err) + } + if strings.Join(p.Proxy.TrustedProxies, ",") != strings.Join(tc.result, ",") || (tc.result == nil) != (p.Proxy.TrustedProxies == nil) { + t.Fatalf("trusted proxies = %#v, want %#v", p.Proxy.TrustedProxies, tc.result) + } + return + } + var projectErr *Error + if !errors.As(err, &projectErr) || !strings.Contains(projectErr.Message, tc.want) || projectErr.Path != tc.path { + t.Fatalf("error = %v, want text %q at %s", err, tc.want, tc.path) + } + }) + } +} + +func TestTrustedProxiesRequireManagedProxy(t *testing.T) { + for _, tc := range []struct { + name string + body string + }{ + {"unmanaged", min + "proxy: {managed: false, trusted_proxies: [192.0.2.0/24]}\n"}, + {"no routes, so no managed proxy", base + "workloads: {worker: {image: app:1}}\nproxy: {trusted_proxies: [192.0.2.0/24]}\n"}, + } { + t.Run(tc.name, func(t *testing.T) { + _, err := loadFixtureBytes([]byte(tc.body), "ob.yml") + var projectErr *Error + if !errors.As(err, &projectErr) || projectErr.Path != "spec.proxy.trustedProxies" || !strings.Contains(projectErr.Message, "requires a Onebox-managed proxy") { + t.Fatalf("error = %v", err) + } + }) + } + if _, err := loadFixtureBytes([]byte(base+"workloads: {worker: {image: app:1}}\nproxy: {managed: true, trusted_proxies: [192.0.2.0/24]}\n"), "ob.yml"); err != nil { + t.Fatalf("an explicitly managed proxy accepts trusted proxies: %v", err) + } +} + +// The authored spelling is camelCase, like proxyProtocol and dnsChallenge. +func TestTrustedProxiesAuthoredSpelling(t *testing.T) { + p, err := LoadBytes([]byte(`apiVersion: onebox.run/v1alpha2 +kind: Application +metadata: {name: ledger} +spec: + environments: {production: {server: root@192.0.2.10}} + workloads: + web: + image: nginx:1.27 + routes: [{hostname: ledger.example.com, port: 8080}] + proxy: + trustedProxies: [198.51.100.0/24, 192.0.2.0/24] +`), "ob.yml") + if err != nil { + t.Fatal(err) + } + if got := strings.Join(p.Proxy.TrustedProxies, ","); got != "192.0.2.0/24,198.51.100.0/24" { + t.Fatalf("trusted proxies = %s", got) + } +} diff --git a/internal/app/types.go b/internal/app/types.go index d18d7f67..93914e3a 100644 --- a/internal/app/types.go +++ b/internal/app/types.go @@ -546,6 +546,10 @@ type Proxy struct { Network string `json:"network" description:"External container network shared with routed workloads; default and Onebox's derived application and service network names are reserved." default:"onebox-ingress"` Entrypoints map[string]ProxyEntrypoint `json:"entrypoints,omitempty" description:"Additional named TCP listeners published by the managed proxy. Onebox adds them to its generated static configuration; a proxy.config containing custom traefik.yml or traefik.yaml must define matching Traefik entrypoints."` DNSChallenge *ProxyDNSChallenge `json:"dns_challenge,omitempty" description:"Managed ACME DNS-01 challenge used to issue wildcard certificates. Provider credentials belong in proxy.config/.env; Onebox continues to own the static proxy configuration."` + // TrustedProxies is kept sorted and free of duplicates by validation, so + // the rendered static configuration and the proxy identity depend on the + // set of prefixes, not on how the author ordered them. + TrustedProxies []string `json:"trusted_proxies,omitempty" description:"CIDR prefixes of the reverse proxies or CDN in front of the managed proxy. Requests whose peer address falls in one of them keep their X-Forwarded-For and related forwarded headers instead of having the managed proxy overwrite them. Applies to every entrypoint in Onebox's generated static configuration. Each entry is a canonical IPv4 or IPv6 prefix such as 192.0.2.0/24; a bare address, a prefix with host bits set, and 0.0.0.0/0 or ::/0 are refused. Requires a Onebox-managed proxy and cannot be combined with a project-owned traefik.yml or traefik.yaml." example:"192.0.2.0/24"` } type ProxyEntrypoint struct { diff --git a/internal/app/validate.go b/internal/app/validate.go index dc941a6b..5f1840b2 100644 --- a/internal/app/validate.go +++ b/internal/app/validate.go @@ -2,6 +2,8 @@ package app import ( "fmt" + "net/netip" + "slices" "strconv" "strings" "time" @@ -97,6 +99,11 @@ func validateTopLevel(p *Spec) error { } } } + trusted, err := normaliseTrustedProxies(p.Proxy.TrustedProxies) + if err != nil { + return err + } + p.Proxy.TrustedProxies = trusted seenEntrypointPorts := map[int]string{80: "web", 443: "websecure"} for _, name := range sortedKeys(p.Proxy.Entrypoints) { path := "proxy.entrypoints." + name @@ -682,6 +689,60 @@ func validateScheduleFields(cron, timezone, path string) error { return gTZ.checkOptional(path+".timezone", timezone) } +// normaliseTrustedProxies checks each proxy.trusted_proxies entry and returns +// the set sorted and without duplicates, or nil when it is empty, so an absent +// list and an empty one render the same static configuration. +// +// Every entry must be written exactly as the prefix it denotes. A prefix with +// host bits set, such as 10.20.0.5/24, is refused rather than masked: the +// author may have meant the single address, and silently trusting the whole +// /24 is the wrong way to guess. An IPv4-mapped IPv6 prefix is refused because +// ::ffff:0:0/96 matches every IPv4 peer in Go's net package, the comparison +// Traefik uses; write the IPv4 prefix instead. +func normaliseTrustedProxies(entries []string) ([]string, error) { + const path = "proxy.trusted_proxies" + if len(entries) == 0 { + return nil, nil + } + prefixes := make([]netip.Prefix, 0, len(entries)) + for i, entry := range entries { + at := indexed(path, i) + prefix, err := netip.ParsePrefix(entry) + if err != nil { + if addr, addrErr := netip.ParseAddr(entry); addrErr == nil && addr.Zone() == "" { + return nil, errf("project_invalid", at, "", + "%q is an address, not a CIDR prefix; write %s to trust that one address", entry, netip.PrefixFrom(addr, addr.BitLen())) + } + return nil, errf("project_invalid", at, "", "%q is not a CIDR prefix such as 192.0.2.0/24 or 2001:db8::/32", entry) + } + if prefix.Addr().Is4In6() { + return nil, errf("project_invalid", at, "", + "%q is an IPv4-mapped IPv6 prefix; write the IPv4 prefix it denotes instead", entry) + } + if prefix.Bits() == 0 { + return nil, errf("project_invalid", at, "", + "%q would trust every peer, so any client could forge X-Forwarded-For; list only the addresses of the proxies in front of this one", entry) + } + if canonical := prefix.Masked().String(); canonical != entry { + return nil, errf("project_invalid", at, "", + "%q is not a canonical prefix; write %s", entry, canonical) + } + prefixes = append(prefixes, prefix) + } + slices.SortFunc(prefixes, func(a, b netip.Prefix) int { + if c := a.Addr().Compare(b.Addr()); c != 0 { + return c + } + return a.Bits() - b.Bits() + }) + prefixes = slices.Compact(prefixes) + out := make([]string, len(prefixes)) + for i, prefix := range prefixes { + out[i] = prefix.String() + } + return out, nil +} + func indexed(path string, i int) string { return path + "[" + itoa(i) + "]" } diff --git a/internal/engine/proxy_converge.go b/internal/engine/proxy_converge.go index c94fcbf4..bad4780f 100644 --- a/internal/engine/proxy_converge.go +++ b/internal/engine/proxy_converge.go @@ -67,7 +67,7 @@ func (e *Engine) stageProxy(dir string) (proxy.Identity, error) { discoveryImage := proxy.DiscoveryImage(e.Opts.Runner.Version) return proxy.StageForAppManaged(localCfg, dir, e.Spec.Proxy.Image, discoveryImage, e.Spec.Name, e.Spec.Proxy.Network, e.Spec.Proxy.Entrypoints, e.Spec.HasExactTerminatingTLS(), - e.Spec.HasWildcardTerminatingTLS(), e.Spec.Proxy.DNSChallenge) + e.Spec.HasWildcardTerminatingTLS(), e.Spec.Proxy.DNSChallenge, e.Spec.Proxy.TrustedProxies) } func traefikDefinitionChanged(live, rendered []byte) bool { diff --git a/internal/engine/proxy_converge_test.go b/internal/engine/proxy_converge_test.go index 22a1dcd7..f6597fe9 100644 --- a/internal/engine/proxy_converge_test.go +++ b/internal/engine/proxy_converge_test.go @@ -977,3 +977,53 @@ func TestPlanProxyReportsEachAction(t *testing.T) { }) } } + +// Adding proxy.trustedProxies to a project whose proxy is already running is a +// configuration change and nothing more: the plan names the restart, and an +// unchanged list (here, none on either side) plans nothing. +func TestPlanProxyRestartsTraefikWhenTrustedProxiesChange(t *testing.T) { + for _, tt := range []struct { + name string + trusted []string + want string + }{ + {"absent before and after", nil, "unchanged"}, + {"declared", []string{"192.0.2.0/24"}, "restart Traefik (configuration changed)"}, + } { + t.Run(tt.name, func(t *testing.T) { + f := &transport.Fake{} + e, _, _ := proxyFixture(t, f) + e.Spec.Proxy.Config = "" + applied, err := e.stageProxy(t.TempDir()) + if err != nil { + t.Fatal(err) + } + live := string(testProxyCompose(t, e)) + e.Spec.Proxy.TrustedProxies = tt.trusted + f.Dynamic = func(cmd string) (transport.Result, bool) { + switch { + case strings.Contains(cmd, "{{.Image}}") || strings.Contains(cmd, "{{.Id}}"): + return transport.Result{Stdout: "sha256:proxy"}, true + case cmd == "cat '/var/lib/onebox/_host/proxy/compose.yaml'": + return transport.Result{Stdout: live}, true + case strings.HasPrefix(cmd, "cat "): + return transport.Result{Stdout: applied.String() + "\n"}, true + case strings.Contains(cmd, "service=proxy"): + return transport.Result{Stdout: "PX1\n"}, true + case strings.Contains(cmd, "service=discovery"): + return transport.Result{Stdout: "D1\n"}, true + case strings.Contains(cmd, "stat -c %i"): + return transport.Result{Stdout: "12\n"}, true + } + return transport.Result{}, false + } + got, err := e.PlanProxy(context.Background()) + if err != nil { + t.Fatal(err) + } + if got != tt.want { + t.Fatalf("PlanProxy = %q, want %q", got, tt.want) + } + }) + } +} diff --git a/internal/onebox/proxy_execute_test.go b/internal/onebox/proxy_execute_test.go index fba63b40..7a97c207 100644 --- a/internal/onebox/proxy_execute_test.go +++ b/internal/onebox/proxy_execute_test.go @@ -56,7 +56,7 @@ func testExecuteSealedProxyAction(t *testing.T, matching bool) { staging := t.TempDir() spec := lp.resolved id, err := proxy.StageForAppManaged("", staging, spec.Proxy.Image, proxy.DiscoveryImage(svc.runner.Version), - spec.Name, spec.Proxy.Network, spec.Proxy.Entrypoints, spec.HasExactTerminatingTLS(), spec.HasWildcardTerminatingTLS(), spec.Proxy.DNSChallenge) + spec.Name, spec.Proxy.Network, spec.Proxy.Entrypoints, spec.HasExactTerminatingTLS(), spec.HasWildcardTerminatingTLS(), spec.Proxy.DNSChallenge, spec.Proxy.TrustedProxies) if err != nil { t.Fatal(err) } diff --git a/internal/proxy/proxy.go b/internal/proxy/proxy.go index 0c215739..83fe3247 100644 --- a/internal/proxy/proxy.go +++ b/internal/proxy/proxy.go @@ -312,7 +312,12 @@ func foldKey(document map[string]any, key string) any { const managedDynamicConfigName = "onebox-managed.yml" const managedCompressionMiddleware = "onebox-compress" -const defaultStaticConfigHeader = `# Written by Onebox because the project declared no custom static proxy configuration. +// The static configuration is assembled from these parts so that the +// forwarded-header trust for proxy.trusted_proxies can sit inside each +// entrypoint. Without it the parts concatenate to exactly the bytes Onebox has +// always written, which keeps the proxy identity, and so the running proxy, +// unchanged for every project that does not declare it. +const defaultStaticConfigPreamble = `# Written by Onebox because the project declared no custom static proxy configuration. # Add dynamic files through proxy.config, or include traefik.yml/traefik.yaml to own this file. ping: {} providers: @@ -320,18 +325,30 @@ providers: directory: /etc/traefik/dynamic watch: true entryPoints: - web: +` + +const webEntrypointAddress = ` web: address: ":80" - http: +` + +const webEntrypointHTTP = ` http: redirections: entryPoint: {to: websecure, scheme: https} - websecure: +` + +const websecureEntrypointAddress = ` websecure: address: ":443" - http: +` + +const websecureEntrypointHTTP = ` http: middlewares: - ` + managedCompressionMiddleware + `@file ` +const defaultStaticConfigHeader = defaultStaticConfigPreamble + + webEntrypointAddress + webEntrypointHTTP + + websecureEntrypointAddress + websecureEntrypointHTTP + const defaultStaticConfigFooter = `certificatesResolvers: ` + app.ManagedCertificateResolver + `: acme: @@ -365,14 +382,37 @@ func newProxyConfigHash() hash.Hash { } func renderStaticConfig(entrypoints map[string]app.ProxyEntrypoint) []byte { - return renderStaticConfigWithDNS(entrypoints, nil) + return renderManagedStaticConfig(entrypoints, nil, nil) } func renderStaticConfigWithDNS(entrypoints map[string]app.ProxyEntrypoint, dns *app.ProxyDNSChallenge) []byte { + return renderManagedStaticConfig(entrypoints, dns, nil) +} + +// renderManagedStaticConfig writes the static configuration Onebox owns. Each +// rendered entrypoint, built in or declared, trusts the forwarded headers of +// the same trustedProxies: a request reaches the backend through one +// entrypoint, and which one should not decide whether its client address is +// believed. trustedProxies arrives validated, sorted and deduplicated. +func renderManagedStaticConfig(entrypoints map[string]app.ProxyEntrypoint, dns *app.ProxyDNSChallenge, trustedProxies []string) []byte { + var forwarded strings.Builder + if len(trustedProxies) > 0 { + forwarded.WriteString(" forwardedHeaders:\n trustedIPs:\n") + for _, prefix := range trustedProxies { + fmt.Fprintf(&forwarded, " - %q\n", prefix) + } + } var out strings.Builder - out.WriteString(defaultStaticConfigHeader) + out.WriteString(defaultStaticConfigPreamble) + out.WriteString(webEntrypointAddress) + out.WriteString(forwarded.String()) + out.WriteString(webEntrypointHTTP) + out.WriteString(websecureEntrypointAddress) + out.WriteString(forwarded.String()) + out.WriteString(websecureEntrypointHTTP) for _, name := range sortedEntrypointNames(entrypoints) { fmt.Fprintf(&out, " %s:\n address: \":%d\"\n", name, entrypoints[name].Port) + out.WriteString(forwarded.String()) } out.WriteString(defaultStaticConfigFooter) if dns != nil { @@ -392,13 +432,15 @@ func Stage(localCfgDir, stagingDir, image, network string, entrypoints map[strin } func StageForApp(localCfgDir, stagingDir, image, discoveryImage, application, network string, entrypoints map[string]app.ProxyEntrypoint, requireCertificateResolver bool) (Identity, error) { - return StageForAppManaged(localCfgDir, stagingDir, image, discoveryImage, application, network, entrypoints, requireCertificateResolver, false, nil) + return StageForAppManaged(localCfgDir, stagingDir, image, discoveryImage, application, network, entrypoints, requireCertificateResolver, false, nil, nil) } // StageForAppManaged stages a proxy with the managed ACME policy required by // the application's routes. Wildcard termination requires DNS-01 either from -// dns or from a custom static configuration. -func StageForAppManaged(localCfgDir, stagingDir, image, discoveryImage, application, network string, entrypoints map[string]app.ProxyEntrypoint, requireExactCertificateResolver, requireWildcardTLS bool, dns *app.ProxyDNSChallenge) (Identity, error) { +// dns or from a custom static configuration. trustedProxies, when non-empty, +// is rendered into every Onebox-written entrypoint and therefore requires the +// static configuration to be Onebox's. +func StageForAppManaged(localCfgDir, stagingDir, image, discoveryImage, application, network string, entrypoints map[string]app.ProxyEntrypoint, requireExactCertificateResolver, requireWildcardTLS bool, dns *app.ProxyDNSChallenge, trustedProxies []string) (Identity, error) { if application == "" { application = "onebox" } @@ -406,7 +448,7 @@ func StageForAppManaged(localCfgDir, stagingDir, image, discoveryImage, applicat if requireWildcardTLS && dns == nil { return Identity{}, errors.New("managed terminating wildcard routes require an ACME DNS challenge") } - return stageDefaultManaged(stagingDir, image, discoveryImage, application, network, entrypoints, dns) + return stageDefaultManaged(stagingDir, image, discoveryImage, application, network, entrypoints, dns, trustedProxies) } entries, err := os.ReadDir(localCfgDir) if err != nil { @@ -450,6 +492,10 @@ func StageForAppManaged(localCfgDir, stagingDir, image, discoveryImage, applicat if dns != nil && customStatic { return Identity{}, errors.New("proxy.dns_challenge cannot be combined with project-owned traefik.yml or traefik.yaml; remove the static file so Onebox can render DNS-01") } + if len(trustedProxies) > 0 && customStatic { + return Identity{}, errors.New("proxy.trustedProxies cannot be combined with project-owned traefik.yml or traefik.yaml; " + + "remove the static file so Onebox can render the entrypoints, or set entryPoints..forwardedHeaders.trustedIPs there and omit proxy.trustedProxies") + } if requireWildcardTLS && !customStatic && dns == nil { return Identity{}, errors.New("managed terminating wildcard routes require proxy.dns_challenge, or a project-owned traefik.yml or traefik.yaml defining ACME DNS-01") } @@ -467,7 +513,7 @@ func StageForAppManaged(localCfgDir, stagingDir, image, discoveryImage, applicat } staticName := "traefik.yml" - staticBody := renderStaticConfigWithDNS(entrypoints, dns) + staticBody := renderManagedStaticConfig(entrypoints, dns, trustedProxies) if customStatic { staticName = staticConfigs[0] var err error @@ -550,7 +596,7 @@ func StageForAppManaged(localCfgDir, stagingDir, image, discoveryImage, applicat // stageDefaultManaged writes the configuration Onebox owns, so a project that // declares a domain and nothing else can bootstrap. -func stageDefaultManaged(stagingDir, image, discoveryImage, application, network string, entrypoints map[string]app.ProxyEntrypoint, dns *app.ProxyDNSChallenge) (Identity, error) { +func stageDefaultManaged(stagingDir, image, discoveryImage, application, network string, entrypoints map[string]app.ProxyEntrypoint, dns *app.ProxyDNSChallenge, trustedProxies []string) (Identity, error) { cfgOut := filepath.Join(stagingDir, "config") if err := os.MkdirAll(cfgOut, 0o755); err != nil { return Identity{}, err @@ -562,7 +608,7 @@ func stageDefaultManaged(stagingDir, image, discoveryImage, application, network if err := os.MkdirAll(dynamicOut, 0o755); err != nil { return Identity{}, err } - body := renderStaticConfigWithDNS(entrypoints, dns) + body := renderManagedStaticConfig(entrypoints, dns, trustedProxies) if err := os.WriteFile(filepath.Join(cfgOut, "traefik.yml"), body, 0o600); err != nil { return Identity{}, err } diff --git a/internal/proxy/proxy_test.go b/internal/proxy/proxy_test.go index fd70fbcd..edf35bcc 100644 --- a/internal/proxy/proxy_test.go +++ b/internal/proxy/proxy_test.go @@ -139,7 +139,7 @@ func TestManagedDNSChallengeRenderingAndStaging(t *testing.T) { cfgDir := writeCfg(t, map[string]string{".env": "CF_DNS_API_TOKEN=placeholder\n"}) staging := t.TempDir() - if _, err := StageForAppManaged(cfgDir, staging, "", "", "sample", "", nil, true, true, dns); err != nil { + if _, err := StageForAppManaged(cfgDir, staging, "", "", "sample", "", nil, true, true, dns, nil); err != nil { t.Fatal(err) } body, err := os.ReadFile(filepath.Join(staging, "config", "traefik.yml")) @@ -160,20 +160,20 @@ func TestManagedDNSChallengeRenderingAndStaging(t *testing.T) { func TestManagedWildcardTLSRejectsIncompleteDNSConfiguration(t *testing.T) { dns := &app.ProxyDNSChallenge{Provider: "cloudflare"} - if _, err := StageForAppManaged(writeCfg(t, map[string]string{"dynamic.yml": "http: {}\n"}), t.TempDir(), "", "", "sample", "", nil, true, true, dns); err == nil || !strings.Contains(err.Error(), ".env") { + if _, err := StageForAppManaged(writeCfg(t, map[string]string{"dynamic.yml": "http: {}\n"}), t.TempDir(), "", "", "sample", "", nil, true, true, dns, nil); err == nil || !strings.Contains(err.Error(), ".env") { t.Fatalf("missing provider credentials must fail: %v", err) } - if _, err := StageForAppManaged(writeCfg(t, map[string]string{"dynamic.yml": "http: {}\n"}), t.TempDir(), "", "", "sample", "", nil, true, true, nil); err == nil || !strings.Contains(err.Error(), "proxy.dns_challenge") { + if _, err := StageForAppManaged(writeCfg(t, map[string]string{"dynamic.yml": "http: {}\n"}), t.TempDir(), "", "", "sample", "", nil, true, true, nil, nil); err == nil || !strings.Contains(err.Error(), "proxy.dns_challenge") { t.Fatalf("managed HTTP-01 must not claim wildcard support: %v", err) } httpOnly := writeCfg(t, map[string]string{"traefik.yml": testSocketlessStaticWithResolver}) - if _, err := StageForAppManaged(httpOnly, t.TempDir(), "", "", "sample", "", nil, false, true, nil); err == nil || !strings.Contains(err.Error(), app.ManagedWildcardCertificateResolver) { + if _, err := StageForAppManaged(httpOnly, t.TempDir(), "", "", "sample", "", nil, false, true, nil, nil); err == nil || !strings.Contains(err.Error(), app.ManagedWildcardCertificateResolver) { t.Fatalf("custom HTTP-01 resolver must not claim wildcard support: %v", err) } dnsStatic := testSocketlessStatic + "certificatesResolvers:\n " + app.ManagedWildcardCertificateResolver + ":\n acme:\n storage: /letsencrypt/acme-wildcard.json\n dnsChallenge:\n provider: cloudflare\n" - if _, err := StageForAppManaged(writeCfg(t, map[string]string{"traefik.yml": dnsStatic}), t.TempDir(), "", "", "sample", "", nil, false, true, nil); err != nil { + if _, err := StageForAppManaged(writeCfg(t, map[string]string{"traefik.yml": dnsStatic}), t.TempDir(), "", "", "sample", "", nil, false, true, nil, nil); err != nil { t.Fatalf("custom DNS-01 resolver should remain supported: %v", err) } } diff --git a/internal/proxy/trusted_proxies_test.go b/internal/proxy/trusted_proxies_test.go new file mode 100644 index 00000000..a905fecd --- /dev/null +++ b/internal/proxy/trusted_proxies_test.go @@ -0,0 +1,165 @@ +package proxy + +import ( + "crypto/sha256" + "encoding/hex" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/labstack/onebox/internal/app" + "gopkg.in/yaml.v3" +) + +// The full static configuration with trusted proxies, byte for byte: the +// forwarded-header block sits inside every entrypoint Onebox renders, built in +// and declared, and nothing else moves. +func TestTrustedProxiesRenderIntoEveryEntrypoint(t *testing.T) { + entrypoints := map[string]app.ProxyEntrypoint{"otlp-grpc": {Port: 4317}} + got := string(renderManagedStaticConfig(entrypoints, nil, []string{"192.0.2.0/24", "2001:db8::/32"})) + const want = `# Written by Onebox because the project declared no custom static proxy configuration. +# Add dynamic files through proxy.config, or include traefik.yml/traefik.yaml to own this file. +ping: {} +providers: + file: + directory: /etc/traefik/dynamic + watch: true +entryPoints: + web: + address: ":80" + forwardedHeaders: + trustedIPs: + - "192.0.2.0/24" + - "2001:db8::/32" + http: + redirections: + entryPoint: {to: websecure, scheme: https} + websecure: + address: ":443" + forwardedHeaders: + trustedIPs: + - "192.0.2.0/24" + - "2001:db8::/32" + http: + middlewares: + - onebox-compress@file + otlp-grpc: + address: ":4317" + forwardedHeaders: + trustedIPs: + - "192.0.2.0/24" + - "2001:db8::/32" +certificatesResolvers: + letsencrypt: + acme: + storage: /letsencrypt/acme.json + httpChallenge: + entryPoint: web +` + if got != want { + t.Fatalf("static configuration with trusted proxies:\n%s\nwant:\n%s", got, want) + } + var document struct { + EntryPoints map[string]struct { + ForwardedHeaders struct { + TrustedIPs []string `yaml:"trustedIPs"` + } `yaml:"forwardedHeaders"` + } `yaml:"entryPoints"` + } + if err := yaml.Unmarshal([]byte(got), &document); err != nil { + t.Fatalf("rendered configuration is not YAML: %v", err) + } + for _, name := range []string{"web", "websecure", "otlp-grpc"} { + if ips := document.EntryPoints[name].ForwardedHeaders.TrustedIPs; strings.Join(ips, ",") != "192.0.2.0/24,2001:db8::/32" { + t.Errorf("entrypoint %s trusts %v", name, ips) + } + } +} + +// Upgrading Onebox must not restart a proxy whose project does not use the +// field. These digests were taken from the renderer before trusted proxies +// existed; an absent and an empty list must both reproduce them. +func TestStaticConfigWithoutTrustedProxiesIsUnchanged(t *testing.T) { + entrypoints := map[string]app.ProxyEntrypoint{"otlp-grpc": {Port: 4317}} + dns := &app.ProxyDNSChallenge{Provider: "cloudflare", Resolvers: []string{"1.1.1.1:53"}} + for _, trusted := range [][]string{nil, {}} { + for _, tc := range []struct { + body []byte + want string + }{ + {renderManagedStaticConfig(nil, nil, trusted), "7d792804475ccf729251ca2f3482a7f6143a4d62bcb153c0c280f90164538229"}, + {renderManagedStaticConfig(entrypoints, dns, trusted), "29e77be16f406e93fba34fbdbfd4d582c5c53b6d0e180e747581b6baeb1b6059"}, + } { + sum := sha256.Sum256(tc.body) + if got := hex.EncodeToString(sum[:]); got != tc.want { + t.Errorf("static configuration digest = %s, want %s:\n%s", got, tc.want, tc.body) + } + } + id, err := StageForAppManaged("", t.TempDir(), "", DiscoveryImage("v2026.10.4-alpha"), "sample", "", entrypoints, true, false, nil, trusted) + if err != nil { + t.Fatal(err) + } + if id.Config != "sha256:5a25af9957faa759c5497d0f6a9b8e5a9f0eaaf297b490f664e2e1c187509a3f" || + id.Compose != "sha256:2bb10135d395a17c59be97fdd3c6f4801dba6228cf916dac81dc46a3451560d3" { + t.Errorf("proxy identity without trusted proxies changed: %+v", id) + } + } + if string(renderStaticConfig(nil)) != DefaultStaticConfig { + t.Fatal("DefaultStaticConfig no longer matches the renderer") + } +} + +// Declaring trusted proxies changes the configuration digest, which is what +// makes the deploy plan report a Traefik restart, and leaves the container +// definition alone, so the change is a restart and not a recreate. +func TestTrustedProxiesChangeOnlyTheConfigurationIdentity(t *testing.T) { + for _, cfg := range []map[string]string{nil, {"dynamic.yml": "http: {}\n"}} { + stage := func(trusted []string) Identity { + t.Helper() + dir := "" + if cfg != nil { + dir = writeCfg(t, cfg) + } + id, err := StageForAppManaged(dir, t.TempDir(), "", "", "sample", "", nil, true, false, nil, trusted) + if err != nil { + t.Fatal(err) + } + return id + } + without, with := stage(nil), stage([]string{"192.0.2.0/24"}) + if without.Config == with.Config { + t.Errorf("config %v: trusted proxies did not change the configuration identity", cfg) + } + if without.Compose != with.Compose { + t.Errorf("config %v: trusted proxies changed the container definition", cfg) + } + } +} + +func TestTrustedProxiesStageIntoDynamicOnlyConfig(t *testing.T) { + staging := t.TempDir() + if _, err := StageForAppManaged(writeCfg(t, map[string]string{"dynamic.yml": "http: {}\n"}), staging, "", "", "sample", "", nil, true, false, nil, []string{"198.51.100.0/24"}); err != nil { + t.Fatal(err) + } + body, err := os.ReadFile(filepath.Join(staging, "config", "traefik.yml")) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(body), "trustedIPs:\n - \"198.51.100.0/24\"") { + t.Fatalf("staged static configuration lost trusted proxies:\n%s", body) + } +} + +func TestTrustedProxiesRefuseProjectOwnedStaticConfig(t *testing.T) { + for _, name := range []string{"traefik.yml", "traefik.yaml"} { + cfg := writeCfg(t, map[string]string{name: testSocketlessStatic}) + _, err := StageForAppManaged(cfg, t.TempDir(), "", "", "sample", "", nil, false, false, nil, []string{"192.0.2.0/24"}) + if err == nil || !strings.Contains(err.Error(), "proxy.trustedProxies cannot be combined with project-owned traefik.yml") { + t.Fatalf("%s: error = %v", name, err) + } + if _, err := StageForAppManaged(cfg, t.TempDir(), "", "", "sample", "", nil, false, false, nil, nil); err != nil { + t.Fatalf("%s without trusted proxies: %v", name, err) + } + } +} diff --git a/site/public/schemas/application/v1alpha2/application.schema.json b/site/public/schemas/application/v1alpha2/application.schema.json index 8666f300..8feb8bab 100644 --- a/site/public/schemas/application/v1alpha2/application.schema.json +++ b/site/public/schemas/application/v1alpha2/application.schema.json @@ -946,6 +946,18 @@ "default": "onebox-ingress", "description": "External container network shared with routed workloads; default and Onebox's derived application and service network names are reserved.", "type": "string" + }, + "trustedProxies": { + "description": "CIDR prefixes of the reverse proxies or CDN in front of the managed proxy. Requests whose peer address falls in one of them keep their X-Forwarded-For and related forwarded headers instead of having the managed proxy overwrite them. Applies to every entrypoint in Onebox's generated static configuration. Each entry is a canonical IPv4 or IPv6 prefix such as 192.0.2.0/24; a bare address, a prefix with host bits set, and 0.0.0.0/0 or ::/0 are refused. Requires a Onebox-managed proxy and cannot be combined with a project-owned traefik.yml or traefik.yaml.", + "examples": [ + [ + "192.0.2.0/24" + ] + ], + "items": { + "type": "string" + }, + "type": "array" } }, "type": "object" diff --git a/site/src/content/docs/docs/reference/fields/proxy.mdx b/site/src/content/docs/docs/reference/fields/proxy.mdx index 6afb3bff..575efef6 100644 --- a/site/src/content/docs/docs/reference/fields/proxy.mdx +++ b/site/src/content/docs/docs/reference/fields/proxy.mdx @@ -17,7 +17,7 @@ cannot drift from what `ob validate` accepts. ## Fields on this page -`config` · `dnsChallenge` · `entrypoints` · `image` · `kind` · `managed` · `network` · `port` · `provider` · `resolvers` +`config` · `dnsChallenge` · `entrypoints` · `image` · `kind` · `managed` · `network` · `port` · `provider` · `resolvers` · `trustedProxies` ## Reference @@ -33,5 +33,6 @@ cannot drift from what `ob validate` accepts. | `kind` | `TraefikDocker` · `None` | `TraefikDocker` | Proxy implementation, or none to disable routing. | | `managed` | boolean | — | Let Onebox converge the host-scoped proxy when routes are declared. | | `network` | string | `onebox-ingress` | External container network shared with routed workloads; default and Onebox's derived application and service network names are reserved. | +| `trustedProxies` | list | — | CIDR prefixes of the reverse proxies or CDN in front of the managed proxy. Requests whose peer address falls in one of them keep their X-Forwarded-For and related forwarded headers instead of having the managed proxy overwrite them. Applies to every entrypoint in Onebox's generated static configuration. Each entry is a canonical IPv4 or IPv6 prefix such as 192.0.2.0/24; a bare address, a prefix with host bits set, and 0.0.0.0/0 or ::/0 are refused. Requires a Onebox-managed proxy and cannot be combined with a project-owned traefik.yml or traefik.yaml. | `*` marks a field that is required within its own object. diff --git a/site/src/content/docs/docs/reference/project-file.mdx b/site/src/content/docs/docs/reference/project-file.mdx index a84af00a..84fac9e9 100644 --- a/site/src/content/docs/docs/reference/project-file.mdx +++ b/site/src/content/docs/docs/reference/project-file.mdx @@ -358,6 +358,67 @@ is healthy, instead of receiving a header they do not expect. A backend that trusts the header should accept it only from the proxy's address on the `proxy.network` network. +### Trusted proxies in front of the managed proxy + +The managed proxy treats the peer of each connection as the client. When a CDN +or another reverse proxy sits in front of it, that peer is the front proxy, and +Traefik overwrites the `X-Forwarded-For` the front proxy wrote with the front +proxy's own address, so the backend never learns who the client was. List the +front proxy's addresses under `proxy.trustedProxies` to keep its forwarded +headers instead: + +```yaml +proxy: + trustedProxies: + - 192.0.2.0/24 + - 2001:db8:1200::/40 +``` + +Onebox writes the list as `forwardedHeaders.trustedIPs` on every entrypoint in +the static configuration it renders: `web`, `websecure`, and each one under +`proxy.entrypoints`. A request from a listed peer reaches the backend with the +`X-Forwarded-For` it arrived with, and Traefik appends the peer's address. A +request from any other peer has the header replaced by that peer's address, as +before. + +Each entry is a CIDR prefix in canonical form, IPv4 or IPv6. Write a single +address as `/32` or `/128`; a bare address is refused. A prefix with host bits +set, such as `10.20.0.5/24`, is refused with the canonical form to write +instead, because Onebox cannot tell whether you meant the one address or the +whole network. `0.0.0.0/0` and `::/0` are refused outright: trusting every peer +lets any client write its own `X-Forwarded-For`. Onebox sorts the list and +drops duplicates, so the order you write it in does not change the +configuration. `ob preview` prints the effective list. + +The field requires a Onebox-managed proxy. With `proxy.managed: false`, the +operator-owned proxy sets this trust in its own configuration. It cannot be +combined with a project-owned `traefik.yml` or `traefik.yaml` in +`proxy.config`; set `entryPoints..forwardedHeaders.trustedIPs` there +instead. Adding, changing, or removing the list changes the proxy's static +configuration, so the next deploy plan shows `proxy: restart Traefik +(configuration changed)`. A project that never declares it keeps the static +configuration byte for byte. + +The list is only as safe as the front proxy is closed. Trust is decided by the +peer address, so the host must accept connections on the proxy's ports only +from the CDN or edge you listed, for example with a firewall that admits only +its published ranges. If a client can reach the managed proxy directly from a +listed range, or the front proxy forwards a client's `X-Forwarded-For` without +replacing or appending to it correctly, that client can forge its address. + +Applications must read the header correctly too: + +- Walk `X-Forwarded-For` from right to left. The rightmost entry was written + by the managed proxy and the ones before it by the proxies in front; take the + first address, from the right, that is not one of your own proxies. The + leftmost entry is whatever the client sent and proves nothing. +- Include the front proxy's addresses, not only the managed proxy's address on + `proxy.network`, in the application's own list of trusted proxies. Most + frameworks call this a trusted proxy or real-IP setting. +- Ignore `X-Real-Ip`. Traefik passes it through from a trusted peer without + modification, so it carries whatever the front proxy, or a client in front of + it, put there. + :::caution[Compose is an output, not an input] A Compose file you wrote cannot be the contract: the declaration is, and Onebox generates the runtime from it. Individual services can still be adopted with From 2f08805c652b7f893b84e1f8ae7f73e07cf78ff5 Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Thu, 26 Nov 2026 19:55:09 -0800 Subject: [PATCH 2/2] fix(proxy): bound trustedProxies prefixes and clarify their reach Refusing /0 alone let a pair such as 0.0.0.0/1 and 128.0.0.0/1 trust every peer. Trusted prefixes must now be at least /8 for IPv4 and /16 for IPv6; no CDN publishes ranges anywhere near that wide. The no-managed-proxy error blamed an operator-owned proxy even when the cause was that no route is declared or that proxy.kind is none; each case now says what it is and what to do. The docs now state that trusted peers also control X-Forwarded-Proto and X-Forwarded-Host, including that X-Forwarded-Proto: https on the web entrypoint suppresses the HTTPS redirect. Co-Authored-By: Claude Opus 5.5 --- .../v1alpha2/application.schema.json | 2 +- internal/app/load.go | 17 ++++++++++++++--- internal/app/trusted_proxies_test.go | 14 +++++++++++--- internal/app/types.go | 2 +- internal/app/validate.go | 16 ++++++++++++++++ .../v1alpha2/application.schema.json | 2 +- .../docs/docs/reference/fields/proxy.mdx | 2 +- .../docs/docs/reference/project-file.mdx | 14 +++++++++++++- 8 files changed, 58 insertions(+), 11 deletions(-) diff --git a/api/application/v1alpha2/application.schema.json b/api/application/v1alpha2/application.schema.json index 8feb8bab..df3c64db 100644 --- a/api/application/v1alpha2/application.schema.json +++ b/api/application/v1alpha2/application.schema.json @@ -948,7 +948,7 @@ "type": "string" }, "trustedProxies": { - "description": "CIDR prefixes of the reverse proxies or CDN in front of the managed proxy. Requests whose peer address falls in one of them keep their X-Forwarded-For and related forwarded headers instead of having the managed proxy overwrite them. Applies to every entrypoint in Onebox's generated static configuration. Each entry is a canonical IPv4 or IPv6 prefix such as 192.0.2.0/24; a bare address, a prefix with host bits set, and 0.0.0.0/0 or ::/0 are refused. Requires a Onebox-managed proxy and cannot be combined with a project-owned traefik.yml or traefik.yaml.", + "description": "CIDR prefixes of the reverse proxies or CDN in front of the managed proxy. Requests whose peer address falls in one of them keep their X-Forwarded-For and related forwarded headers instead of having the managed proxy overwrite them. Applies to every entrypoint in Onebox's generated static configuration. Each entry is a canonical IPv4 or IPv6 prefix such as 192.0.2.0/24; a bare address, a prefix with host bits set, and an IPv4 prefix shorter than /8 or an IPv6 prefix shorter than /16 are refused. Trusted peers also control X-Forwarded-Proto and X-Forwarded-Host. Requires a Onebox-managed proxy and cannot be combined with a project-owned traefik.yml or traefik.yaml.", "examples": [ [ "192.0.2.0/24" diff --git a/internal/app/load.go b/internal/app/load.go index a588c1fd..a64a5356 100644 --- a/internal/app/load.go +++ b/internal/app/load.go @@ -528,9 +528,20 @@ func crossFieldRules(p *Spec) error { return errf("project_invalid", "proxy.dns_challenge", "", "dns_challenge requires a Onebox-managed proxy") } if len(p.Proxy.TrustedProxies) > 0 && (!p.Proxy.Managed || p.Proxy.Kind == "none") { - return errf("project_invalid", "proxy.trusted_proxies", "", - "trustedProxies requires a Onebox-managed proxy, which renders the entrypoints that trust them; "+ - "an operator-owned proxy sets forwarded-header trust in its own configuration") + switch { + case p.Proxy.Kind == "none": + return errf("project_invalid", "proxy.trusted_proxies", "", + "trustedProxies requires a Onebox-managed proxy, but proxy.kind is \"none\", so no proxy runs; "+ + "remove trustedProxies, or name the proxy that serves the routes") + case !p.routesAnywhere(): + return errf("project_invalid", "proxy.trusted_proxies", "", + "trustedProxies requires a Onebox-managed proxy, but no workload declares a route, so Onebox runs none; "+ + "declare a route, set proxy.managed to true, or remove trustedProxies") + default: + return errf("project_invalid", "proxy.trusted_proxies", "", + "trustedProxies requires a Onebox-managed proxy, which renders the entrypoints that trust them; "+ + "an operator-owned proxy sets forwarded-header trust in its own configuration") + } } if p.Proxy.Managed && p.HasWildcardTerminatingTLS() && p.Proxy.DNSChallenge == nil && p.Proxy.Config == "" { return errf("project_invalid", "proxy.dns_challenge", "", diff --git a/internal/app/trusted_proxies_test.go b/internal/app/trusted_proxies_test.go index 09568a44..0c8f110d 100644 --- a/internal/app/trusted_proxies_test.go +++ b/internal/app/trusted_proxies_test.go @@ -28,6 +28,11 @@ func TestTrustedProxiesValidation(t *testing.T) { {"bare ipv6", `["2001:db8::7"]`, "write 2001:db8::7/128", "spec.proxy.trustedProxies[0]", nil}, {"ipv4 everything", `["0.0.0.0/0"]`, "trust every peer", "spec.proxy.trustedProxies[0]", nil}, {"ipv6 everything", `["::/0"]`, "trust every peer", "spec.proxy.trustedProxies[0]", nil}, + {"ipv4 halves", `["0.0.0.0/1", "128.0.0.0/1"]`, "at least /8", "spec.proxy.trustedProxies[0]", nil}, + {"ipv4 shorter than /8", `["10.0.0.0/8", "192.0.0.0/7"]`, "at least /8", "spec.proxy.trustedProxies[1]", nil}, + {"ipv6 half", `["::/1"]`, "at least /16", "spec.proxy.trustedProxies[0]", nil}, + {"ipv6 shorter than /16", `["2000::/3"]`, "at least /16", "spec.proxy.trustedProxies[0]", nil}, + {"ipv4 /8 and ipv6 /16", `["10.0.0.0/8", "2001::/16"]`, "", "", []string{"10.0.0.0/8", "2001::/16"}}, {"ipv4-mapped ipv6", `["::ffff:0.0.0.0/96"]`, "IPv4-mapped", "spec.proxy.trustedProxies[0]", nil}, {"not a prefix", `["cdn.example.com"]`, "not a CIDR prefix", "spec.proxy.trustedProxies[0]", nil}, {"zone", `["fe80::%eth0/64"]`, "not a CIDR prefix", "spec.proxy.trustedProxies[0]", nil}, @@ -55,14 +60,17 @@ func TestTrustedProxiesRequireManagedProxy(t *testing.T) { for _, tc := range []struct { name string body string + want string }{ - {"unmanaged", min + "proxy: {managed: false, trusted_proxies: [192.0.2.0/24]}\n"}, - {"no routes, so no managed proxy", base + "workloads: {worker: {image: app:1}}\nproxy: {trusted_proxies: [192.0.2.0/24]}\n"}, + {"unmanaged", min + "proxy: {managed: false, trusted_proxies: [192.0.2.0/24]}\n", "an operator-owned proxy"}, + {"no routes, so no managed proxy", base + "workloads: {worker: {image: app:1}}\nproxy: {trusted_proxies: [192.0.2.0/24]}\n", "no workload declares a route"}, + {"routing disabled", base + "workloads: {worker: {image: app:1}}\nproxy: {kind: none, trusted_proxies: [192.0.2.0/24]}\n", "proxy.kind is \"none\""}, } { t.Run(tc.name, func(t *testing.T) { _, err := loadFixtureBytes([]byte(tc.body), "ob.yml") var projectErr *Error - if !errors.As(err, &projectErr) || projectErr.Path != "spec.proxy.trustedProxies" || !strings.Contains(projectErr.Message, "requires a Onebox-managed proxy") { + if !errors.As(err, &projectErr) || projectErr.Path != "spec.proxy.trustedProxies" || + !strings.Contains(projectErr.Message, "requires a Onebox-managed proxy") || !strings.Contains(projectErr.Message, tc.want) { t.Fatalf("error = %v", err) } }) diff --git a/internal/app/types.go b/internal/app/types.go index 93914e3a..420ec79d 100644 --- a/internal/app/types.go +++ b/internal/app/types.go @@ -549,7 +549,7 @@ type Proxy struct { // TrustedProxies is kept sorted and free of duplicates by validation, so // the rendered static configuration and the proxy identity depend on the // set of prefixes, not on how the author ordered them. - TrustedProxies []string `json:"trusted_proxies,omitempty" description:"CIDR prefixes of the reverse proxies or CDN in front of the managed proxy. Requests whose peer address falls in one of them keep their X-Forwarded-For and related forwarded headers instead of having the managed proxy overwrite them. Applies to every entrypoint in Onebox's generated static configuration. Each entry is a canonical IPv4 or IPv6 prefix such as 192.0.2.0/24; a bare address, a prefix with host bits set, and 0.0.0.0/0 or ::/0 are refused. Requires a Onebox-managed proxy and cannot be combined with a project-owned traefik.yml or traefik.yaml." example:"192.0.2.0/24"` + TrustedProxies []string `json:"trusted_proxies,omitempty" description:"CIDR prefixes of the reverse proxies or CDN in front of the managed proxy. Requests whose peer address falls in one of them keep their X-Forwarded-For and related forwarded headers instead of having the managed proxy overwrite them. Applies to every entrypoint in Onebox's generated static configuration. Each entry is a canonical IPv4 or IPv6 prefix such as 192.0.2.0/24; a bare address, a prefix with host bits set, and an IPv4 prefix shorter than /8 or an IPv6 prefix shorter than /16 are refused. Trusted peers also control X-Forwarded-Proto and X-Forwarded-Host. Requires a Onebox-managed proxy and cannot be combined with a project-owned traefik.yml or traefik.yaml." example:"192.0.2.0/24"` } type ProxyEntrypoint struct { diff --git a/internal/app/validate.go b/internal/app/validate.go index 5f1840b2..83c3a851 100644 --- a/internal/app/validate.go +++ b/internal/app/validate.go @@ -723,6 +723,11 @@ func normaliseTrustedProxies(entries []string) ([]string, error) { return nil, errf("project_invalid", at, "", "%q would trust every peer, so any client could forge X-Forwarded-For; list only the addresses of the proxies in front of this one", entry) } + if minimum := minTrustedPrefixBits(prefix); prefix.Bits() < minimum { + return nil, errf("project_invalid", at, "", + "%q trusts too much of the address space; trusted proxy prefixes must be at least /%d, "+ + "and published CDN ranges are far narrower, so list them individually", entry, minimum) + } if canonical := prefix.Masked().String(); canonical != entry { return nil, errf("project_invalid", at, "", "%q is not a canonical prefix; write %s", entry, canonical) @@ -743,6 +748,17 @@ func normaliseTrustedProxies(entries []string) ([]string, error) { return out, nil } +// minTrustedPrefixBits is the shortest prefix proxy.trusted_proxies accepts. +// No CDN or edge publishes ranges anywhere near this wide, so a shorter +// prefix is a typo or an attempt to trust everyone in a few entries, such as +// 0.0.0.0/1 and 128.0.0.0/1, which refusing /0 alone would let through. +func minTrustedPrefixBits(prefix netip.Prefix) int { + if prefix.Addr().Is4() { + return 8 + } + return 16 +} + func indexed(path string, i int) string { return path + "[" + itoa(i) + "]" } diff --git a/site/public/schemas/application/v1alpha2/application.schema.json b/site/public/schemas/application/v1alpha2/application.schema.json index 8feb8bab..df3c64db 100644 --- a/site/public/schemas/application/v1alpha2/application.schema.json +++ b/site/public/schemas/application/v1alpha2/application.schema.json @@ -948,7 +948,7 @@ "type": "string" }, "trustedProxies": { - "description": "CIDR prefixes of the reverse proxies or CDN in front of the managed proxy. Requests whose peer address falls in one of them keep their X-Forwarded-For and related forwarded headers instead of having the managed proxy overwrite them. Applies to every entrypoint in Onebox's generated static configuration. Each entry is a canonical IPv4 or IPv6 prefix such as 192.0.2.0/24; a bare address, a prefix with host bits set, and 0.0.0.0/0 or ::/0 are refused. Requires a Onebox-managed proxy and cannot be combined with a project-owned traefik.yml or traefik.yaml.", + "description": "CIDR prefixes of the reverse proxies or CDN in front of the managed proxy. Requests whose peer address falls in one of them keep their X-Forwarded-For and related forwarded headers instead of having the managed proxy overwrite them. Applies to every entrypoint in Onebox's generated static configuration. Each entry is a canonical IPv4 or IPv6 prefix such as 192.0.2.0/24; a bare address, a prefix with host bits set, and an IPv4 prefix shorter than /8 or an IPv6 prefix shorter than /16 are refused. Trusted peers also control X-Forwarded-Proto and X-Forwarded-Host. Requires a Onebox-managed proxy and cannot be combined with a project-owned traefik.yml or traefik.yaml.", "examples": [ [ "192.0.2.0/24" diff --git a/site/src/content/docs/docs/reference/fields/proxy.mdx b/site/src/content/docs/docs/reference/fields/proxy.mdx index 575efef6..24b40853 100644 --- a/site/src/content/docs/docs/reference/fields/proxy.mdx +++ b/site/src/content/docs/docs/reference/fields/proxy.mdx @@ -33,6 +33,6 @@ cannot drift from what `ob validate` accepts. | `kind` | `TraefikDocker` · `None` | `TraefikDocker` | Proxy implementation, or none to disable routing. | | `managed` | boolean | — | Let Onebox converge the host-scoped proxy when routes are declared. | | `network` | string | `onebox-ingress` | External container network shared with routed workloads; default and Onebox's derived application and service network names are reserved. | -| `trustedProxies` | list | — | CIDR prefixes of the reverse proxies or CDN in front of the managed proxy. Requests whose peer address falls in one of them keep their X-Forwarded-For and related forwarded headers instead of having the managed proxy overwrite them. Applies to every entrypoint in Onebox's generated static configuration. Each entry is a canonical IPv4 or IPv6 prefix such as 192.0.2.0/24; a bare address, a prefix with host bits set, and 0.0.0.0/0 or ::/0 are refused. Requires a Onebox-managed proxy and cannot be combined with a project-owned traefik.yml or traefik.yaml. | +| `trustedProxies` | list | — | CIDR prefixes of the reverse proxies or CDN in front of the managed proxy. Requests whose peer address falls in one of them keep their X-Forwarded-For and related forwarded headers instead of having the managed proxy overwrite them. Applies to every entrypoint in Onebox's generated static configuration. Each entry is a canonical IPv4 or IPv6 prefix such as 192.0.2.0/24; a bare address, a prefix with host bits set, and an IPv4 prefix shorter than /8 or an IPv6 prefix shorter than /16 are refused. Trusted peers also control X-Forwarded-Proto and X-Forwarded-Host. Requires a Onebox-managed proxy and cannot be combined with a project-owned traefik.yml or traefik.yaml. | `*` marks a field that is required within its own object. diff --git a/site/src/content/docs/docs/reference/project-file.mdx b/site/src/content/docs/docs/reference/project-file.mdx index 84fac9e9..f2fc2ce7 100644 --- a/site/src/content/docs/docs/reference/project-file.mdx +++ b/site/src/content/docs/docs/reference/project-file.mdx @@ -386,7 +386,10 @@ address as `/32` or `/128`; a bare address is refused. A prefix with host bits set, such as `10.20.0.5/24`, is refused with the canonical form to write instead, because Onebox cannot tell whether you meant the one address or the whole network. `0.0.0.0/0` and `::/0` are refused outright: trusting every peer -lets any client write its own `X-Forwarded-For`. Onebox sorts the list and +lets any client write its own `X-Forwarded-For`. So is any IPv4 prefix shorter +than `/8` or IPv6 prefix shorter than `/16`, which keeps a pair such as +`0.0.0.0/1` and `128.0.0.0/1` from trusting everyone too; published CDN ranges +are far narrower, so list them individually. Onebox sorts the list and drops duplicates, so the order you write it in does not change the configuration. `ob preview` prints the effective list. @@ -406,6 +409,15 @@ its published ranges. If a client can reach the managed proxy directly from a listed range, or the front proxy forwards a client's `X-Forwarded-For` without replacing or appending to it correctly, that client can forge its address. +Trust covers every forwarded header, not only `X-Forwarded-For`. A listed peer +also decides `X-Forwarded-Proto` and `X-Forwarded-Host`, and Traefik acts on +them itself: a trusted peer that sends `X-Forwarded-Proto: https` to the `web` +entrypoint is treated as already secure, so the HTTP-to-HTTPS redirect does not +happen. Make sure the front proxy sets these headers from the request it +received rather than passing a client's values through. An application that +builds URLs or checks hosts from `X-Forwarded-Host` gets whatever the front +proxy put there. + Applications must read the header correctly too: - Walk `X-Forwarded-For` from right to left. The rightmost entry was written