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
27 changes: 27 additions & 0 deletions api/application/v1alpha2/application.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -2080,6 +2080,23 @@
}
}
},
{
"if": {
"required": [
"proxyProtocol"
]
},
"then": {
"properties": {
"protocol": {
"const": "tcp"
}
},
"required": [
"protocol"
]
}
},
{
"if": {
"properties": {
Expand Down Expand Up @@ -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.",
Expand Down
150 changes: 150 additions & 0 deletions e2e/proxy_protocol_test.go
Original file line number Diff line number Diff line change
@@ -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))
}
}
7 changes: 7 additions & 0 deletions internal/app/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"strings"
"time"

"github.com/labstack/onebox/internal/discovery"
"gopkg.in/yaml.v3"
)

Expand Down Expand Up @@ -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
}
Expand Down
8 changes: 8 additions & 0 deletions internal/app/jsonschema.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"},
Expand All @@ -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()},
Expand Down
1 change: 1 addition & 0 deletions internal/app/jsonschema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
11 changes: 11 additions & 0 deletions internal/app/load.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
Expand Down
4 changes: 4 additions & 0 deletions internal/app/load_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down
79 changes: 79 additions & 0 deletions internal/app/naming_scope_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading