diff --git a/api/application/v1alpha2/application.schema.json b/api/application/v1alpha2/application.schema.json index b3bd3f37..5cebd30d 100644 --- a/api/application/v1alpha2/application.schema.json +++ b/api/application/v1alpha2/application.schema.json @@ -2080,6 +2080,23 @@ } } }, + { + "if": { + "required": [ + "proxyProtocol" + ] + }, + "then": { + "properties": { + "protocol": { + "const": "tcp" + } + }, + "required": [ + "protocol" + ] + } + }, { "if": { "properties": { @@ -2158,6 +2175,16 @@ ], "type": "string" }, + "proxyProtocol": { + "description": "PROXY protocol version the proxy sends to the backend at the start of each connection, so a TCP route's backend can read the client address. Only 2 is accepted. Requires protocol tcp and the Onebox-managed proxy; the backend must expect the header, because it otherwise reads it as data.", + "enum": [ + 2 + ], + "examples": [ + 2 + ], + "type": "integer" + }, "scheme": { "default": "http", "description": "Backend connection scheme for HTTP routes: http, https, or h2c.", diff --git a/e2e/proxy_protocol_test.go b/e2e/proxy_protocol_test.go new file mode 100644 index 00000000..28e44c78 --- /dev/null +++ b/e2e/proxy_protocol_test.go @@ -0,0 +1,150 @@ +package e2e + +import ( + "context" + "crypto/tls" + "fmt" + "net" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/labstack/onebox/internal/app" + "github.com/labstack/onebox/internal/discovery" + "github.com/labstack/onebox/internal/proxy" + "gopkg.in/yaml.v3" +) + +// A TCP passthrough route with proxyProtocol: 2 makes the real Traefik image +// open each backend connection with a PROXY v2 header before the client's TLS +// bytes. The route's labels come from the rendered release and the dynamic +// document from discovery, loaded by Traefik's file provider exactly as +// written, so this proves the generated servers transport and the plain-name +// reference resolve, which the unit tests can only assert as YAML. +func TestTCPRouteSendsProxyProtocolV2(t *testing.T) { + gate(t) + ctx := context.Background() + application := fmt.Sprintf("obpp%d", os.Getpid()) + network := application + "_default" + backend, traefik := application+"-backend", application+"-traefik" + + 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: device.example.com, port: 7581, protocol: tcp, tls: Passthrough, proxyProtocol: 2} +`, application) + project, err := app.LoadBytes([]byte(body), filepath.Join(t.TempDir(), "ob.yml")) + if err != nil { + t.Fatal(err) + } + resolved, err := project.Resolve("production") + if err != nil { + t.Fatal(err) + } + rendered, err := resolved.Render("production", "R1", nil) + if err != nil { + t.Fatal(err) + } + var compose struct { + Services map[string]struct { + Labels map[string]string `yaml:"labels"` + } `yaml:"services"` + } + if err := yaml.Unmarshal(rendered.Bytes, &compose); err != nil { + t.Fatal(err) + } + labels := compose.Services["web"].Labels + if len(labels) == 0 { + t.Fatalf("the rendered web service has no labels:\n%s", rendered.Bytes) + } + + docker := func(args ...string) string { + t.Helper() + out, err := exec.CommandContext(ctx, "docker", args...).CombinedOutput() + if err != nil { + t.Fatalf("docker %s: %v\n%s", strings.Join(args, " "), err, out) + } + return strings.TrimSpace(string(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() + }) + docker("network", "create", network) + // The backend records the first bytes of its first connection as hex. + docker("run", "-d", "--name", backend, "--network", network, + "busybox:1.37", "sh", "-c", "nc -l -p 7581 | head -c 16 | od -An -tx1") + backendIP := docker("inspect", "-f", "{{(index .NetworkSettings.Networks \""+network+"\").IPAddress}}", backend) + + document, err := discovery.Build([]discovery.Container{{ + ID: backend, Created: time.Now(), Running: true, Health: "healthy", + Labels: labels, Networks: map[string]string{network: backendIP}, + }}, network) + if err != nil { + t.Fatal(err) + } + dynamicBody, err := yaml.Marshal(document) + if err != nil { + t.Fatal(err) + } + dynamic := t.TempDir() + if err := os.WriteFile(filepath.Join(dynamic, "onebox.yml"), dynamicBody, 0o644); err != nil { + t.Fatal(err) + } + // The route's entrypoint is whatever the release rendered; the test proxy + // defines that one name and publishes it on an ephemeral loopback port. + entrypoint := "" + for key, value := range labels { + if strings.HasPrefix(key, "traefik.tcp.routers.") && strings.HasSuffix(key, ".entrypoints") { + entrypoint = value + } + } + if entrypoint == "" { + t.Fatalf("no TCP router entrypoint in the rendered labels: %v", labels) + } + docker("run", "-d", "--name", traefik, "--network", network, + "-p", "127.0.0.1::8443", "-v", dynamic+":/dynamic:ro", proxy.DefaultImage, + "--providers.file.directory=/dynamic", "--entrypoints."+entrypoint+".address=:8443") + address := docker("port", traefik, "8443/tcp") + if i := strings.IndexByte(address, '\n'); i >= 0 { + address = address[:i] + } + + // Retry until Traefik has loaded the route and the backend has a capture. + deadline := time.Now().Add(60 * time.Second) + var capture string + for time.Now().Before(deadline) { + dialer := net.Dialer{Timeout: time.Second} + if conn, err := dialer.DialContext(ctx, "tcp", address); err == nil { + hello, cancel := context.WithTimeout(ctx, 2*time.Second) + // The backend is not TLS, so the handshake fails; only the bytes + // Traefik forwards matter. + _ = tls.Client(conn, &tls.Config{ServerName: "device.example.com"}).HandshakeContext(hello) + cancel() + _ = conn.Close() + } + capture = strings.Join(strings.Fields(docker("logs", backend)), " ") + if capture != "" { + break + } + time.Sleep(time.Second) + } + // v2 signature, then version 2 + PROXY command (0x21), TCP over IPv4 (0x11). + const want = "0d 0a 0d 0a 00 0d 0a 51 55 49 54 0a 21 11" + if !strings.HasPrefix(capture, want) { + t.Fatalf("backend's first bytes = %q, want a PROXY v2 TCPv4 header %q\ndynamic:\n%s\ntraefik:\n%s", + capture, want, dynamicBody, docker("logs", traefik)) + } +} diff --git a/internal/app/generate.go b/internal/app/generate.go index f7f56790..c2d02f4e 100644 --- a/internal/app/generate.go +++ b/internal/app/generate.go @@ -8,6 +8,7 @@ import ( "strings" "time" + "github.com/labstack/onebox/internal/discovery" "gopkg.in/yaml.v3" ) @@ -595,6 +596,12 @@ func (p *Spec) routeLabels(n Names, name string, w Workload) map[string]any { if kind == "http" && r.Scheme != "" && r.Scheme != "http" { out[sp+"scheme"] = r.Scheme } + // The discovery controller defines this transport beside the routes it + // publishes; validation admits proxy_protocol only on a managed TCP + // route, so no operator-owned proxy is asked to resolve the name. + if kind == "tcp" && r.ProxyProtocol == 2 { + out[fmt.Sprintf("traefik.tcp.services.%s.loadbalancer.serverstransport", svcName)] = discovery.ProxyProtocolV2Transport + } } return out } diff --git a/internal/app/jsonschema.go b/internal/app/jsonschema.go index d7e9c4af..40351446 100644 --- a/internal/app/jsonschema.go +++ b/internal/app/jsonschema.go @@ -477,6 +477,13 @@ var schemaConstraints = []struct { "properties": map[string]any{"protocol": map[string]any{"const": "http"}}, }, }, + map[string]any{ + "if": map[string]any{"required": []any{"proxy_protocol"}}, + "then": map[string]any{ + "required": []any{"protocol"}, + "properties": map[string]any{"protocol": map[string]any{"const": "tcp"}}, + }, + }, map[string]any{ "if": map[string]any{ "required": []any{"tls"}, @@ -502,6 +509,7 @@ var schemaConstraints = []struct { {[]string{"workloads", "*", "routes", "items", "scheme"}, enum(eRouteScheme)}, {[]string{"workloads", "*", "routes", "items", "tls"}, enum(eRouteTLS)}, {[]string{"workloads", "*", "routes", "items", "middlewares", "items"}, pattern(gMiddlewareRef)}, + {[]string{"workloads", "*", "routes", "items", "proxy_protocol"}, map[string]any{"enum": []any{2}}}, {[]string{"workloads", "*", "volumes", "items", "name"}, pattern(gIdent)}, {[]string{"workloads", "*", "volumes", "items", "path"}, pattern(gAbsPath)}, {[]string{"workloads", "*", "volumes", "items", "source"}, bindSourceConstraint()}, diff --git a/internal/app/jsonschema_test.go b/internal/app/jsonschema_test.go index db3bc77c..956621e2 100644 --- a/internal/app/jsonschema_test.go +++ b/internal/app/jsonschema_test.go @@ -68,6 +68,7 @@ var beyondJSONSchema = map[string]string{ // Two structures have to agree, which a schema evaluates independently. "proxy kind none with a route": "a route needs something to route it, which is a fact about the proxy block", "managed route middleware without proxy config": "managed middleware references require configuration from the separate proxy block", + "operator proxy with PROXY protocol": "PROXY protocol requires the managed proxy declared in the separate proxy block", "workload and service share a name": "an identifier is unique across workloads and services, which are separate objects", // Facts about values that only resolution knows. diff --git a/internal/app/load.go b/internal/app/load.go index f3808009..576ac76a 100644 --- a/internal/app/load.go +++ b/internal/app/load.go @@ -513,6 +513,17 @@ func crossFieldRules(p *Spec) error { if err := checkRouteCollisions(p); err != nil { return err } + if !p.Proxy.Managed { + for _, name := range sortedKeys(p.Workloads) { + for i, route := range p.Workloads[name].Routes { + if route.ProxyProtocol != 0 { + return errf("project_invalid", indexed("workloads."+name+".routes", i)+".proxy_protocol", "", + "proxyProtocol requires a Onebox-managed proxy, which defines the servers transport it selects; "+ + "an operator-owned proxy enables PROXY protocol in its own configuration") + } + } + } + } 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") } diff --git a/internal/app/load_test.go b/internal/app/load_test.go index 42740f9c..7903d98c 100644 --- a/internal/app/load_test.go +++ b/internal/app/load_test.go @@ -251,6 +251,10 @@ spec: {"operator proxy owns route middleware", wl("w: {image: nginx, routes: [{hostname: x, port: 8080, middlewares: [auth@file]}]}") + "proxy: {managed: false}\n", true}, {"bad protocol", wl("w: {image: nginx, routes: [{hostname: x, port: 1, protocol: udp}]}"), false}, {"http route with TLS passthrough", wl("w: {image: nginx, routes: [{hostname: x, port: 443, tls: passthrough}]}"), false}, + {"tcp route with PROXY protocol", wl("w: {image: nginx, routes: [{hostname: x, port: 7581, protocol: tcp, tls: passthrough, proxy_protocol: 2}]}"), true}, + {"http route with PROXY protocol", wl("w: {image: nginx, routes: [{hostname: x, port: 8080, proxy_protocol: 2}]}"), false}, + {"PROXY protocol version 1", wl("w: {image: nginx, routes: [{hostname: x, port: 7581, protocol: tcp, proxy_protocol: 1}]}"), false}, + {"operator proxy with PROXY protocol", wl("w: {image: nginx, routes: [{hostname: x, port: 7581, protocol: tcp, proxy_protocol: 2}]}") + "proxy: {managed: false}\n", false}, {"absolute compose ref", wl("w: {compose: \"/etc/compose.yml#web\"}"), false}, {"relative compose ref", wl("w: {compose: \"compose.yaml#web\"}"), true}, {"absolute env_file", min + "runtime: {env_files: [/etc/x.env]}\n", false}, diff --git a/internal/app/naming_scope_test.go b/internal/app/naming_scope_test.go index c8b6dba7..25610066 100644 --- a/internal/app/naming_scope_test.go +++ b/internal/app/naming_scope_test.go @@ -3,6 +3,8 @@ package app import ( "strings" "testing" + + "github.com/labstack/onebox/internal/discovery" ) // 8.5 — every name derived from the author's workloads carries the @@ -137,6 +139,83 @@ spec: } } +// A TCP route with proxyProtocol selects the PROXY protocol v2 transport the +// discovery controller defines; every other route stays on Traefik's default +// transport, so enabling it on one route cannot reach another backend. +func TestTCPRouteProxyProtocolSelectsManagedTransport(t *testing.T) { + body := `apiVersion: onebox.run/v1alpha2 +kind: Application +metadata: + name: shop +spec: + environments: {production: {server: root@203.0.113.10}} + workloads: + web: + image: nginx + routes: + - {hostname: shop.example.com, port: 3000} + - {hostname: device.example.com, port: 7581, protocol: tcp, tls: Passthrough, proxyProtocol: 2} + - {hostname: db.example.com, port: 5432, protocol: tcp, tls: Passthrough} +` + r, err := loadText(t, body).Resolve("production") + if err != nil { + t.Fatal(err) + } + canonical, err := r.Canonical() + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(canonical), "proxyProtocol: 2") { + t.Errorf("the canonical form lost proxyProtocol:\n%s", canonical) + } + rendered, err := r.Render("production", "R1", nil) + if err != nil { + t.Fatal(err) + } + runtime := string(rendered.Bytes) + want := "traefik.tcp.services.onebox_web_r1.loadbalancer.serverstransport: " + discovery.ProxyProtocolV2Transport + if !strings.Contains(runtime, want) { + t.Fatalf("the generated runtime is missing:\n %s\n%s", want, runtime) + } + if got := strings.Count(runtime, "serverstransport"); got != 1 { + t.Fatalf("serverstransport appears %d times; only the proxyProtocol route selects a transport:\n%s", got, runtime) + } + if strings.Contains(runtime, "proxyprotocol") { + t.Fatal("the deprecated per-service loadbalancer.proxyprotocol label must not be generated") + } +} + +func TestProxyProtocolRefusals(t *testing.T) { + project := func(route, proxy string) string { + return `apiVersion: onebox.run/v1alpha2 +kind: Application +metadata: + name: shop +spec: + environments: {production: {server: root@203.0.113.10}} + workloads: + web: + image: nginx + routes: + - ` + route + ` +` + proxy + } + for _, tc := range []struct { + name, route, proxy, want string + }{ + {"http route", "{hostname: shop.example.com, port: 3000, proxyProtocol: 2}", "", "X-Forwarded-For"}, + {"version 1", "{hostname: device.example.com, port: 7581, protocol: tcp, proxyProtocol: 1}", "", "version 1 is not supported"}, + {"operator-owned proxy", "{hostname: device.example.com, port: 7581, protocol: tcp, proxyProtocol: 2}", " proxy: {managed: false}\n", "Onebox-managed proxy"}, + } { + t.Run(tc.name, func(t *testing.T) { + _, err := loadFixtureBytes([]byte(project(tc.route, tc.proxy)), "ob.yml") + if err == nil || !strings.Contains(err.Error(), tc.want) || !strings.Contains(err.Error(), "routes[0].proxyProtocol") { + t.Fatalf("error = %v, want %q at routes[0].proxyProtocol", err, tc.want) + } + }) + } +} + func TestRouteMiddlewareOrderPreservesRepetition(t *testing.T) { body := `apiVersion: onebox.run/v1alpha2 kind: Application diff --git a/internal/app/testdata/contract-verdicts.json b/internal/app/testdata/contract-verdicts.json index 72541d25..ed952515 100644 --- a/internal/app/testdata/contract-verdicts.json +++ b/internal/app/testdata/contract-verdicts.json @@ -1,4 +1,9 @@ [ + { + "case": "conformance/PROXY protocol version 1", + "loads": false, + "code": "project_invalid" + }, { "case": "conformance/a near-miss field name", "loads": false, @@ -184,6 +189,11 @@ "loads": false, "code": "project_invalid" }, + { + "case": "conformance/http route with PROXY protocol", + "loads": false, + "code": "project_invalid" + }, { "case": "conformance/http route with TLS passthrough", "loads": false, @@ -294,6 +304,11 @@ "loads": true, "digest": "93ba8c0a7344004feaa711ef682e2fe31c226768397069613a0a723e58177782" }, + { + "case": "conformance/operator proxy with PROXY protocol", + "loads": false, + "code": "project_invalid" + }, { "case": "conformance/persistence block with no mode still refuses replicas", "loads": false, @@ -419,6 +434,11 @@ "loads": false, "code": "project_invalid" }, + { + "case": "conformance/tcp route with PROXY protocol", + "loads": true, + "digest": "3358914ef8410317e0161494dfbf6f0b923c624ac738de3e177cfcac74ac2f9e" + }, { "case": "conformance/the withdrawn secrets block", "loads": false, diff --git a/internal/app/types.go b/internal/app/types.go index a7c99988..01ce2dab 100644 --- a/internal/app/types.go +++ b/internal/app/types.go @@ -206,6 +206,9 @@ type Route struct { Scheme string `json:"scheme" description:"Backend connection scheme for HTTP routes: http, https, or h2c." default:"http"` TLS string `json:"tls" description:"TLS handling: terminate, passthrough, or none." default:"terminate"` Middlewares []MiddlewareRef `json:"middlewares,omitempty" description:"Ordered provider-qualified middleware references applied to this route."` + // ProxyProtocol is a version number rather than a switch so the field does + // not have to change shape if another version is ever admitted. + ProxyProtocol int `json:"proxy_protocol,omitempty" description:"PROXY protocol version the proxy sends to the backend at the start of each connection, so a TCP route's backend can read the client address. Only 2 is accepted. Requires protocol tcp and the Onebox-managed proxy; the backend must expect the header, because it otherwise reads it as data." example:"2"` } // MiddlewareRef names dynamic proxy configuration without opening the diff --git a/internal/app/validate.go b/internal/app/validate.go index a2026617..d15b3ead 100644 --- a/internal/app/validate.go +++ b/internal/app/validate.go @@ -343,6 +343,19 @@ func validateWorkload(w Workload, path string) error { "%q requires protocol %q: an http route terminates TLS in order to read the request it routes on", "passthrough", "tcp") } + if r.ProxyProtocol != 0 { + if r.ProxyProtocol != 2 { + return errf("project_invalid", rp+".proxy_protocol", "", + "PROXY protocol version %d is not supported; use 2", r.ProxyProtocol) + } + // An HTTP route already forwards the client address in + // X-Forwarded-For. A PROXY header in front of the request would + // reach an HTTP backend as garbage before the request line. + if r.Protocol != "tcp" { + return errf("project_invalid", rp+".proxy_protocol", "", + "proxyProtocol requires protocol %q: an http route forwards the client address in X-Forwarded-For", "tcp") + } + } } if err := validateHealth(w.Health, path+".health"); err != nil { return err diff --git a/internal/discovery/discovery.go b/internal/discovery/discovery.go index 78a47888..a6e5baf9 100644 --- a/internal/discovery/discovery.go +++ b/internal/discovery/discovery.go @@ -35,8 +35,24 @@ type HTTP struct { } type TCP struct { - Routers map[string]TCPRouter `json:"routers,omitempty" yaml:"routers,omitempty"` - Services map[string]TCPService `json:"services,omitempty" yaml:"services,omitempty"` + Routers map[string]TCPRouter `json:"routers,omitempty" yaml:"routers,omitempty"` + Services map[string]TCPService `json:"services,omitempty" yaml:"services,omitempty"` + ServersTransports map[string]TCPServersTransport `json:"serversTransports,omitempty" yaml:"serversTransports,omitempty"` +} + +// ProxyProtocolV2Transport is the one TCP servers transport discovery defines. +// A TCP service selects it with the serverstransport label, and Traefik then +// writes a PROXY protocol v2 header naming the client before the connection's +// first byte. Traefik v3.5.2 deprecated the per-service +// loadBalancer.proxyProtocol option in favour of this transport setting. +const ProxyProtocolV2Transport = "onebox-proxy-protocol-v2" + +type TCPServersTransport struct { + ProxyProtocol *ProxyProtocol `json:"proxyProtocol,omitempty" yaml:"proxyProtocol,omitempty"` +} + +type ProxyProtocol struct { + Version int `json:"version" yaml:"version"` } type HTTPRouter struct { @@ -87,7 +103,8 @@ type TCPService struct { } type TCPLoadBalancer struct { - Servers []TCPServer `json:"servers" yaml:"servers"` + Servers []TCPServer `json:"servers" yaml:"servers"` + ServersTransport string `json:"serversTransport,omitempty" yaml:"serversTransport,omitempty"` } type TCPServer struct { @@ -106,6 +123,16 @@ type tcpCandidate struct { router TCPRouter } +// tcpBackend is one container's server for a TCP service, with the transport +// that container's labels ask for. The transport belongs to the service, not +// to a server, so the servers of one service must agree on it. +type tcpBackend struct { + created time.Time + id string + address string + transport string +} + // Build converts healthy containers on network into Traefik's file-provider // model. A container without a healthcheck is eligible once running; a // container with one is eligible only while Docker reports it healthy. That is @@ -115,7 +142,7 @@ func Build(containers []Container, networkName string) (Dynamic, error) { httpRouters := map[string]httpCandidate{} tcpRouters := map[string]tcpCandidate{} httpServers := map[string]map[string]struct{}{} - tcpServers := map[string]map[string]struct{}{} + tcpBackends := map[string][]tcpBackend{} for _, container := range containers { if !eligible(container) || !enabled(container.Labels) { @@ -128,7 +155,7 @@ func Build(containers []Container, networkName string) (Dynamic, error) { if err := collectHTTP(container, ip, httpRouters, httpServers); err != nil { return Dynamic{}, err } - if err := collectTCP(container, ip, tcpRouters, tcpServers); err != nil { + if err := collectTCP(container, ip, tcpRouters, tcpBackends); err != nil { return Dynamic{}, err } } @@ -148,18 +175,19 @@ func Build(containers []Container, networkName string) (Dynamic, error) { out.HTTP.Services[name] = HTTPService{LoadBalancer: HTTPLoadBalancer{Servers: items}} } } - if len(tcpRouters) > 0 || len(tcpServers) > 0 { + if len(tcpRouters) > 0 || len(tcpBackends) > 0 { out.TCP = &TCP{Routers: map[string]TCPRouter{}, Services: map[string]TCPService{}} for name, candidate := range tcpRouters { out.TCP.Routers[name] = candidate.router } - for name, servers := range tcpServers { - values := sortedSet(servers) - items := make([]TCPServer, 0, len(values)) - for _, value := range values { - items = append(items, TCPServer{Address: value}) + for name, backends := range tcpBackends { + service := tcpService(backends) + if service.LoadBalancer.ServersTransport == ProxyProtocolV2Transport { + out.TCP.ServersTransports = map[string]TCPServersTransport{ + ProxyProtocolV2Transport: {ProxyProtocol: &ProxyProtocol{Version: 2}}, + } } - out.TCP.Services[name] = TCPService{LoadBalancer: TCPLoadBalancer{Servers: items}} + out.TCP.Services[name] = service } } return out, nil @@ -218,7 +246,33 @@ func collectHTTP(container Container, ip string, routers map[string]httpCandidat return nil } -func collectTCP(container Container, ip string, routers map[string]tcpCandidate, servers map[string]map[string]struct{}) error { +// tcpService takes the transport from the newest backend, as routers are +// taken from the newest container, and keeps only the servers that agree with +// it. During a rolling switch that changes the transport, the old containers +// leave the service as soon as the first new one is healthy rather than being +// sent a PROXY header they do not expect, or sending none to one that does. +func tcpService(backends []tcpBackend) TCPService { + newest := backends[0] + for _, backend := range backends[1:] { + if newer(backend.created, backend.id, newest.created, newest.id) { + newest = backend + } + } + addresses := map[string]struct{}{} + for _, backend := range backends { + if backend.transport == newest.transport { + addresses[backend.address] = struct{}{} + } + } + values := sortedSet(addresses) + items := make([]TCPServer, 0, len(values)) + for _, value := range values { + items = append(items, TCPServer{Address: value}) + } + return TCPService{LoadBalancer: TCPLoadBalancer{Servers: items, ServersTransport: newest.transport}} +} + +func collectTCP(container Container, ip string, routers map[string]tcpCandidate, backends map[string][]tcpBackend) error { for _, name := range routerNames(container.Labels, "tcp") { prefix := "traefik.tcp.routers." + name + "." service := container.Labels[prefix+"service"] @@ -230,7 +284,14 @@ func collectTCP(container Container, ip string, routers map[string]tcpCandidate, if err != nil { return fmt.Errorf("container %s tcp router %s: %w", shortID(container.ID), name, err) } - addServer(servers, service, net.JoinHostPort(ip, strconv.Itoa(port))) + transport := container.Labels["traefik.tcp.services."+service+".loadbalancer.serverstransport"] + if transport != "" && transport != ProxyProtocolV2Transport { + return fmt.Errorf("container %s tcp service %s: unsupported servers transport %q", shortID(container.ID), service, transport) + } + backends[service] = append(backends[service], tcpBackend{ + created: container.Created, id: container.ID, + address: net.JoinHostPort(ip, strconv.Itoa(port)), transport: transport, + }) router := TCPRouter{ Rule: rule, EntryPoints: splitList(container.Labels[prefix+"entrypoints"]), Middlewares: splitList(container.Labels[prefix+"middlewares"]), Service: service, diff --git a/internal/discovery/discovery_test.go b/internal/discovery/discovery_test.go index 3f768209..8be3085b 100644 --- a/internal/discovery/discovery_test.go +++ b/internal/discovery/discovery_test.go @@ -125,6 +125,106 @@ func TestBuildTCPPassthrough(t *testing.T) { } } +func deviceLabels(proxyProtocol bool) map[string]string { + labels := map[string]string{ + "traefik.tcp.routers.app_device_r0.rule": "HostSNI(`device.example.com`)", + "traefik.tcp.routers.app_device_r0.entrypoints": "websecure", + "traefik.tcp.routers.app_device_r0.service": "app_device", + "traefik.tcp.routers.app_device_r0.tls": "true", + "traefik.tcp.routers.app_device_r0.tls.passthrough": "true", + "traefik.tcp.services.app_device.loadbalancer.server.port": "7581", + } + if proxyProtocol { + labels["traefik.tcp.services.app_device.loadbalancer.serverstransport"] = ProxyProtocolV2Transport + } + return labels +} + +func TestBuildTCPProxyProtocolDefinesAndSelectsTransport(t *testing.T) { + document, err := Build([]Container{routedContainer("device", time.Now(), "healthy", "172.20.0.2", deviceLabels(true))}, "onebox-ingress") + if err != nil { + t.Fatal(err) + } + if got := document.TCP.Services["app_device"].LoadBalancer.ServersTransport; got != ProxyProtocolV2Transport { + t.Fatalf("service servers transport = %q", got) + } + transport, ok := document.TCP.ServersTransports[ProxyProtocolV2Transport] + if !ok || transport.ProxyProtocol == nil || transport.ProxyProtocol.Version != 2 { + t.Fatalf("servers transports = %+v", document.TCP.ServersTransports) + } + body, err := yaml.Marshal(document) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{ + "serversTransports:\n " + ProxyProtocolV2Transport + ":\n proxyProtocol:\n version: 2", + "serversTransport: " + ProxyProtocolV2Transport, + } { + if !strings.Contains(string(body), want) { + t.Fatalf("generated YAML lacks %q:\n%s", want, body) + } + } +} + +func TestBuildTCPWithoutProxyProtocolDefinesNoTransport(t *testing.T) { + document, err := Build([]Container{routedContainer("device", time.Now(), "healthy", "172.20.0.2", deviceLabels(false))}, "onebox-ingress") + if err != nil { + t.Fatal(err) + } + if got := document.TCP.Services["app_device"].LoadBalancer.ServersTransport; got != "" { + t.Fatalf("service servers transport = %q", got) + } + if document.TCP.ServersTransports != nil { + t.Fatalf("servers transports = %+v", document.TCP.ServersTransports) + } +} + +// A transport is a service setting, so old and new containers cannot share a +// service while they disagree on it. The newest healthy container decides, and +// only the containers that agree with it stay in rotation. +func TestBuildTCPProxyProtocolChangeKeepsOnlyAgreeingServers(t *testing.T) { + base := time.Date(2026, 8, 1, 0, 0, 0, 0, time.UTC) + for _, tc := range []struct { + name string + oldPP, newPP bool + wantTransport string + }{ + {"enable", false, true, ProxyProtocolV2Transport}, + {"disable", true, false, ""}, + } { + t.Run(tc.name, func(t *testing.T) { + document, err := Build([]Container{ + routedContainer("old-1", base, "healthy", "172.20.0.2", deviceLabels(tc.oldPP)), + routedContainer("old-2", base, "healthy", "172.20.0.3", deviceLabels(tc.oldPP)), + routedContainer("new-1", base.Add(time.Minute), "healthy", "172.20.0.4", deviceLabels(tc.newPP)), + routedContainer("new-2", base.Add(2*time.Minute), "starting", "172.20.0.5", deviceLabels(tc.newPP)), + }, "onebox-ingress") + if err != nil { + t.Fatal(err) + } + service := document.TCP.Services["app_device"].LoadBalancer + if service.ServersTransport != tc.wantTransport { + t.Fatalf("servers transport = %q, want %q", service.ServersTransport, tc.wantTransport) + } + if len(service.Servers) != 1 || service.Servers[0].Address != "172.20.0.4:7581" { + t.Fatalf("servers = %+v, want only the new healthy container", service.Servers) + } + if _, defined := document.TCP.ServersTransports[ProxyProtocolV2Transport]; defined != tc.newPP { + t.Fatalf("transport defined = %v, want %v", defined, tc.newPP) + } + }) + } +} + +func TestBuildRejectsUnknownTCPServersTransport(t *testing.T) { + labels := deviceLabels(false) + labels["traefik.tcp.services.app_device.loadbalancer.serverstransport"] = "custom@file" + _, err := Build([]Container{routedContainer("device", time.Now(), "healthy", "172.20.0.2", labels)}, "onebox-ingress") + if err == nil || !strings.Contains(err.Error(), "unsupported servers transport") { + t.Fatalf("unknown transport error = %v", err) + } +} + func TestBuildRejectsInvalidGeneratedBackend(t *testing.T) { _, err := Build([]Container{routedContainer("bad", time.Now(), "healthy", "172.20.0.2", map[string]string{ "traefik.http.routers.app_web_r0.rule": "Host(`app.example.com`)", diff --git a/internal/proxy/proxy.go b/internal/proxy/proxy.go index 40cea0a6..0c215739 100644 --- a/internal/proxy/proxy.go +++ b/internal/proxy/proxy.go @@ -32,6 +32,7 @@ import ( "github.com/compose-spec/compose-go/v2/dotenv" "github.com/labstack/onebox/internal/app" "github.com/labstack/onebox/internal/buildinfo" + "github.com/labstack/onebox/internal/discovery" "github.com/pelletier/go-toml/v2" "gopkg.in/yaml.v3" ) @@ -696,6 +697,12 @@ func validateDynamicOwnership(name string, body []byte) error { } } } + if protocol == "tcp" { + transports, _ := section["serversTransports"].(map[string]any) + if _, exists := transports[discovery.ProxyProtocolV2Transport]; exists { + return fmt.Errorf("tcp.serversTransports.%s is reserved for Onebox-managed PROXY protocol; rename the custom object", discovery.ProxyProtocolV2Transport) + } + } if protocol == "http" { middlewares, _ := section["middlewares"].(map[string]any) if _, exists := middlewares[managedCompressionMiddleware]; exists { diff --git a/internal/proxy/proxy_test.go b/internal/proxy/proxy_test.go index bfda262b..fd70fbcd 100644 --- a/internal/proxy/proxy_test.go +++ b/internal/proxy/proxy_test.go @@ -20,6 +20,7 @@ import ( "time" "github.com/labstack/onebox/internal/app" + "github.com/labstack/onebox/internal/discovery" "gopkg.in/yaml.v3" ) @@ -434,6 +435,13 @@ func TestStageDynamicExtensionRejectsManagedDefaultCollisions(t *testing.T) { }, want: managedCompressionMiddleware, }, + { + name: "reserved PROXY protocol transport", + files: map[string]string{ + "extension.yml": "tcp:\n serversTransports:\n " + discovery.ProxyProtocolV2Transport + ":\n proxyProtocol: {version: 1}\n", + }, + want: discovery.ProxyProtocolV2Transport, + }, } { t.Run(tc.name, func(t *testing.T) { _, err := Stage(writeCfg(t, tc.files), t.TempDir(), "", "", nil, false) diff --git a/site/public/schemas/application/v1alpha2/application.schema.json b/site/public/schemas/application/v1alpha2/application.schema.json index b3bd3f37..5cebd30d 100644 --- a/site/public/schemas/application/v1alpha2/application.schema.json +++ b/site/public/schemas/application/v1alpha2/application.schema.json @@ -2080,6 +2080,23 @@ } } }, + { + "if": { + "required": [ + "proxyProtocol" + ] + }, + "then": { + "properties": { + "protocol": { + "const": "tcp" + } + }, + "required": [ + "protocol" + ] + } + }, { "if": { "properties": { @@ -2158,6 +2175,16 @@ ], "type": "string" }, + "proxyProtocol": { + "description": "PROXY protocol version the proxy sends to the backend at the start of each connection, so a TCP route's backend can read the client address. Only 2 is accepted. Requires protocol tcp and the Onebox-managed proxy; the backend must expect the header, because it otherwise reads it as data.", + "enum": [ + 2 + ], + "examples": [ + 2 + ], + "type": "integer" + }, "scheme": { "default": "http", "description": "Backend connection scheme for HTTP routes: http, https, or h2c.", diff --git a/site/src/content/docs/docs/reference/fields/workloads.mdx b/site/src/content/docs/docs/reference/fields/workloads.mdx index 4d5d30d2..8d3cf81f 100644 --- a/site/src/content/docs/docs/reference/fields/workloads.mdx +++ b/site/src/content/docs/docs/reference/fields/workloads.mdx @@ -23,7 +23,7 @@ cannot drift from what `ob validate` accepts. ## Fields on this page -`args` · `attempts` · `backoff` · `bind` · `build` · `catchUp` · `command` · `compose` · `condition` · `container` · `context` · `cpus` · `cron` · `dataEffect` · `default` · `deployLock` · `deploymentPhase` · `description` · `dockerfile` · `drain` · `driver` · `entrypoint` · `enum` · `env` · `envFiles` · `exec` · `extraHosts` · `file` · `grace` · `health` · `host` · `hostname` · `http` · `image` · `init` · `inputs` · `interval` · `labels` · `logging` · `maxBackoff` · `memory` · `middlewares` · `mode` · `name` · `needs` · `notify` · `operatorRun` · `options` · `path` · `pattern` · `persistence` · `port` · `protocol` · `provider` · `publishedPorts` · `pull` · `reference` · `replicas` · `resources` · `retries` · `retry` · `role` · `routes` · `schedule` · `scheme` · `shutdownGrace` · `signal` · `source` · `startPeriod` · `stdinOpen` · `strategy` · `target` · `tcp` · `timeout` · `timezone` · `tls` · `tty` · `user` · `volumes` · `wait` · `within` · `workingDir` +`args` · `attempts` · `backoff` · `bind` · `build` · `catchUp` · `command` · `compose` · `condition` · `container` · `context` · `cpus` · `cron` · `dataEffect` · `default` · `deployLock` · `deploymentPhase` · `description` · `dockerfile` · `drain` · `driver` · `entrypoint` · `enum` · `env` · `envFiles` · `exec` · `extraHosts` · `file` · `grace` · `health` · `host` · `hostname` · `http` · `image` · `init` · `inputs` · `interval` · `labels` · `logging` · `maxBackoff` · `memory` · `middlewares` · `mode` · `name` · `needs` · `notify` · `operatorRun` · `options` · `path` · `pattern` · `persistence` · `port` · `protocol` · `provider` · `proxyProtocol` · `publishedPorts` · `pull` · `reference` · `replicas` · `resources` · `retries` · `retry` · `role` · `routes` · `schedule` · `scheme` · `shutdownGrace` · `signal` · `source` · `startPeriod` · `stdinOpen` · `strategy` · `target` · `tcp` · `timeout` · `timezone` · `tls` · `tty` · `user` · `volumes` · `wait` · `within` · `workingDir` ## Reference @@ -96,6 +96,7 @@ cannot drift from what `ob validate` accepts. | `.routes[].path` | string | `/` | URL path prefix matched by an HTTP route. Expects a path beginning with /. | | `.routes[].port` | integer | — | Container port receiving routed traffic. | | `.routes[].protocol` | `http` · `tcp` | `http` | Routing protocol: http or tcp. | +| `.routes[].proxyProtocol` | `2` | — | PROXY protocol version the proxy sends to the backend at the start of each connection, so a TCP route's backend can read the client address. Only 2 is accepted. Requires protocol tcp and the Onebox-managed proxy; the backend must expect the header, because it otherwise reads it as data. | | `.routes[].scheme` | `http` · `https` · `h2c` | `http` | Backend connection scheme for HTTP routes: http, https, or h2c. | | `.routes[].tls` | `Terminate` · `Passthrough` · `None` | `Terminate` | TLS handling: terminate, passthrough, or none. | | `.schedule` | object | — | Host-resident recurring schedule and run policy for a job, independent of its deployment phase and operator-run policy. | diff --git a/site/src/content/docs/docs/reference/project-file.mdx b/site/src/content/docs/docs/reference/project-file.mdx index f18d4c29..a84af00a 100644 --- a/site/src/content/docs/docs/reference/project-file.mdx +++ b/site/src/content/docs/docs/reference/project-file.mdx @@ -189,7 +189,7 @@ but not `TRAEFIK_*` static overrides. In both modes, the filenames `onebox.yml`, `onebox.yaml`, and `onebox-managed.yml`, the `dynamic/` mountpoint, the `onebox-compress` -middleware, and HTTP or TCP router or service names beginning with the derived +middleware, the `onebox-proxy-protocol-v2` TCP servers transport, and HTTP or TCP router or service names beginning with the derived `_` prefix are reserved for generated output. `ob deploy`, `ob bootstrap`, and `ob proxy apply` refuse an incompatible configuration with migration guidance, preventing a proxy from starting with missing or stale routes. @@ -313,6 +313,51 @@ resources instead. Onebox preserves list order when it attaches the chain to the generated router. HTTP and TCP routes both support middleware references; the referenced middleware must match the route's protocol. +### PROXY protocol on TCP routes + +A TCP route forwards the connection's bytes, so the backend's socket peer is +the proxy for every client. Set `proxyProtocol: 2` when the backend needs the +client's address, for example to rate-limit by address behind TLS passthrough: + +```yaml +workloads: + api: + image: ghcr.io/acme/device-api:1.0.0 + routes: + - hostname: device.example.com + port: 7581 + protocol: tcp + tls: passthrough + proxyProtocol: 2 +``` + +The managed proxy then writes a +[PROXY protocol](https://www.haproxy.org/download/2.0/doc/proxy-protocol.txt) +version 2 header naming the client before the first byte of each connection, +ahead of the TLS handshake on a passthrough route. Onebox's discovery +controller defines a TCP servers transport named `onebox-proxy-protocol-v2` +with `proxyProtocol.version: 2` and selects it from that route's service, the +form [Traefik documents](https://doc.traefik.io/traefik/reference/routing-configuration/tcp/serverstransport/) +in place of the per-service `loadBalancer.proxyProtocol` option it deprecated +in v3.5.2. Other routes keep Traefik's default transport. `ob preview` shows +the selection as the +`traefik.tcp.services..loadbalancer.serverstransport` label. + +Only version `2` is accepted, and only on a `protocol: tcp` route: an HTTP +route already passes the client address in `X-Forwarded-For`. The field +requires a Onebox-managed proxy; with `proxy.managed: false` the +operator-owned proxy enables PROXY protocol in its own configuration. + +The backend must expect the header. A backend that does not reads it as the +start of the stream and fails the connection, and one that requires it fails +every connection that lacks it, so change the route and the backend's setting +in the same deploy. During a rolling deploy that turns the setting on or off, +the proxy routes the service only to containers that agree with the newest +healthy one: old containers leave rotation as soon as the first new container +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. + :::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