Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions api/application/v1alpha2/application.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -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 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"
]
],
"items": {
"type": "string"
},
"type": "array"
}
},
"type": "object"
Expand Down
19 changes: 17 additions & 2 deletions cmd/ob/preview.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
}
Expand Down
33 changes: 33 additions & 0 deletions cmd/ob/preview_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
135 changes: 135 additions & 0 deletions e2e/trusted_proxies_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
16 changes: 16 additions & 0 deletions internal/app/load.go
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,22 @@ 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") {
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", "",
"managed terminating wildcard routes require an ACME DNS challenge; declare proxy.dns_challenge and provide its credentials through proxy.config/.env")
Expand Down
103 changes: 103 additions & 0 deletions internal/app/trusted_proxies_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
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 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},
} {
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
want string
}{
{"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") || !strings.Contains(projectErr.Message, tc.want) {
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)
}
}
4 changes: 4 additions & 0 deletions internal/app/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 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 {
Expand Down
Loading
Loading