From 5d59160eb40741a3922cecfe4e4983c6fea902e7 Mon Sep 17 00:00:00 2001 From: Mohammad Date: Mon, 16 Nov 2026 12:17:42 +0330 Subject: [PATCH 1/2] feat: support private node backends behind external TLS termination --- .env.example | 7 +- .github/workflows/run-tests.yml | 4 + README.md | 2 + cmd/node/listeners_test.go | 128 +++++++++++ cmd/node/main.go | 10 +- cmd/node/proxy_test.go | 200 +++++++++++++++++ config/config.go | 35 ++- config/config_test.go | 38 ++++ controller/rest/service.go | 10 +- controller/rpc/service.go | 15 +- docker-compose.yml | 4 + docs/node-tls.md | 163 ++++++++++++++ examples/nginx/grpc.conf | 32 +++ examples/nginx/rest.conf | 36 ++++ node-tls-migration-plan.md | 372 ++++++++++++++++++++++++++++++++ pkg/tlsutil/tls.go | 19 ++ 16 files changed, 1063 insertions(+), 12 deletions(-) create mode 100644 cmd/node/listeners_test.go create mode 100644 cmd/node/proxy_test.go create mode 100644 docs/node-tls.md create mode 100644 examples/nginx/grpc.conf create mode 100644 examples/nginx/rest.conf create mode 100644 node-tls-migration-plan.md diff --git a/.env.example b/.env.example index 5539cced..06427fb4 100644 --- a/.env.example +++ b/.env.example @@ -1,5 +1,10 @@ SERVICE_PORT = 62050 -NODE_HOST = "0.0.0.0" +# Defaults to 0.0.0.0 with TLS; 127.0.0.1 with TLS_ENABLED=false. +# NODE_HOST = "0.0.0.0" + +# Disable only behind a TLS-terminating web server. API-key authentication stays required. +# Plaintext NODE_HOST must be a literal loopback, RFC1918 IPv4, or IPv6 ULA address. +# TLS_ENABLED = true # use absolute path diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index 84ac7fe9..5aac2907 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -43,9 +43,13 @@ jobs: make generate_server_cert make generate_client_cert + - name: Install nginx for TLS frontend integration coverage + run: sudo apt-get update && sudo apt-get install -y nginx + - name: Run regular test suite env: MTPROTO_TELEMT_BIN: /usr/local/bin/telemt + NODE_TEST_NGINX: /usr/sbin/nginx run: TEST_INTEGRATION=true go test ./... -v -p 1 - name: Check Xray process status races diff --git a/README.md b/README.md index 3166ec26..43a65d8d 100644 --- a/README.md +++ b/README.md @@ -231,3 +231,5 @@ Thanks to the all contributors who have helped improve PasarGuard Node:

Made with contrib.rocks

+ +See [Node TLS](docs/node-tls.md) for certificates, renewal and private TLS backends. diff --git a/cmd/node/listeners_test.go b/cmd/node/listeners_test.go new file mode 100644 index 00000000..86de42cb --- /dev/null +++ b/cmd/node/listeners_test.go @@ -0,0 +1,128 @@ +package main + +import ( + "context" + "crypto/tls" + "net" + "net/http" + "testing" + "time" + + "github.com/google/uuid" + "github.com/pasarguard/node/common" + "github.com/pasarguard/node/config" + "github.com/pasarguard/node/controller/rest" + "github.com/pasarguard/node/controller/rpc" + "github.com/pasarguard/node/pkg/tlsutil" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +func listenerAddress(t *testing.T) string { + t.Helper() + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + addr := l.Addr().String() + l.Close() + return addr +} + +func TestListenerTransports(t *testing.T) { + for _, enabled := range []bool{true, false} { + name := "private backend" + if enabled { + name = "TLS" + } + t.Run(name, func(t *testing.T) { + cfg := &config.Config{TLSEnabled: enabled, ApiKey: uuid.New(), GeneratedConfigPath: t.TempDir(), LogBufferSize: 10} + var serverTLS *tls.Config + client := &http.Client{Timeout: 3 * time.Second} + scheme := "http" + var creds credentials.TransportCredentials = insecure.NewCredentials() + if enabled { + var err error + serverTLS, err = tlsutil.LoadTLSCredentials("../../certs/ssl_cert.pem", "../../certs/ssl_key.pem") + if err != nil { + t.Fatal(err) + } + pool, err := tlsutil.LoadClientPool("../../certs/ssl_cert.pem") + if err != nil { + t.Fatal(err) + } + client.Transport = &http.Transport{TLSClientConfig: &tls.Config{RootCAs: pool}} + creds = credentials.NewTLS(&tls.Config{RootCAs: pool}) + scheme = "https" + } + addr := listenerAddress(t) + stop, service, err := rest.StartHttpListener(serverTLS, addr, cfg) + if err != nil { + t.Fatal(err) + } + defer service.Disconnect() + defer stop(context.Background()) + for _, auth := range []bool{false, true} { + req, _ := http.NewRequest("GET", scheme+"://"+addr+"/info", nil) + if auth { + req.Header.Set("x-api-key", cfg.ApiKey.String()) + } + resp, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + want := http.StatusUnauthorized + if auth { + want = http.StatusOK + } + if resp.StatusCode != want { + t.Fatalf("REST auth=%v: got %d", auth, resp.StatusCode) + } + } + client.CloseIdleConnections() + addr = listenerAddress(t) + stopRPC, serviceRPC, err := rpc.StartGRPCListener(serverTLS, addr, cfg) + if err != nil { + t.Fatal(err) + } + defer serviceRPC.Disconnect() + defer stopRPC(context.Background()) + conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(creds)) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + c := common.NewNodeServiceClient(conn) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + if _, err := c.GetBaseInfo(ctx, &common.Empty{}); status.Code(err) != codes.Unauthenticated { + t.Fatalf("gRPC missing key: %v", err) + } + authCtx := metadata.NewOutgoingContext(ctx, metadata.Pairs("x-api-key", cfg.ApiKey.String())) + if _, err := c.GetBaseInfo(authCtx, &common.Empty{}); err != nil { + t.Fatal(err) + } + }) + } +} + +func TestListenersRejectUnsafePlaintext(t *testing.T) { + for _, enabled := range []bool{true, false} { + cfg := &config.Config{TLSEnabled: enabled} + addr := "0.0.0.0:0" + if enabled { + addr = "127.0.0.1:0" + } + if _, _, err := rest.StartHttpListener(nil, addr, cfg); err == nil { + t.Fatal("REST allowed unsafe plaintext") + } + if _, _, err := rpc.StartGRPCListener(nil, addr, cfg); err == nil { + t.Fatal("gRPC allowed unsafe plaintext") + } + } +} diff --git a/cmd/node/main.go b/cmd/node/main.go index 7ddd2016..91c3f630 100644 --- a/cmd/node/main.go +++ b/cmd/node/main.go @@ -2,6 +2,7 @@ package main import ( "context" + "crypto/tls" "log" "net" "os" @@ -25,9 +26,12 @@ func main() { addr := net.JoinHostPort(cfg.NodeHost, strconv.Itoa(cfg.ServicePort)) - tlsConfig, err := tlsutil.LoadTLSCredentials(cfg.SslCertFile, cfg.SslKeyFile) - if err != nil { - log.Fatal(err) + var tlsConfig *tls.Config + if cfg.TLSEnabled { + tlsConfig, err = tlsutil.LoadTLSCredentials(cfg.SslCertFile, cfg.SslKeyFile) + if err != nil { + log.Fatal(err) + } } log.Printf("Starting Node: v%s", controller.NodeVersion) diff --git a/cmd/node/proxy_test.go b/cmd/node/proxy_test.go new file mode 100644 index 00000000..84d3b1e5 --- /dev/null +++ b/cmd/node/proxy_test.go @@ -0,0 +1,200 @@ +package main + +import ( + "bufio" + "context" + "crypto/tls" + "fmt" + "net" + "net/http" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/pasarguard/node/common" + "github.com/pasarguard/node/pkg/tlsutil" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +// Exercise the shipped nginx snippets in CI, including HTTP streaming and gRPC +// server streaming. Direct node listeners are covered by TestListenerTransports. +func TestNginxTLSFrontends(t *testing.T) { + nginx := os.Getenv("NODE_TEST_NGINX") + if nginx == "" { + t.Skip("set NODE_TEST_NGINX to enable the nginx deployment tests") + } + for _, protocol := range []string{"rest", "grpc"} { + t.Run(protocol, func(t *testing.T) { + backendAddr, maintenanceAddr := listenerAddress(t), listenerAddress(t) + frontendAddr, maintenanceFrontend := listenerAddress(t), listenerAddress(t) + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("x-api-key") != "proxy-test-key" { + http.Error(w, "missing key", 401) + return + } + if r.URL.Path == "/logs" { + fmt.Fprintln(w, "stream ready") + w.(http.Flusher).Flush() + <-r.Context().Done() + return + } + fmt.Fprintln(w, `{"status":"ok"}`) + }) + startHTTP := func(addr string) { + l, err := net.Listen("tcp", addr) + if err != nil { + t.Fatal(err) + } + s := &http.Server{Handler: handler} + go s.Serve(l) + t.Cleanup(func() { s.Close() }) + } + startHTTP(maintenanceAddr) + if protocol == "rest" { + startHTTP(backendAddr) + } else { + l, err := net.Listen("tcp", backendAddr) + if err != nil { + t.Fatal(err) + } + s := grpc.NewServer() + common.RegisterNodeServiceServer(s, proxyStreamService{}) + go s.Serve(l) + t.Cleanup(s.Stop) + } + snippet, err := os.ReadFile("../../examples/nginx/" + protocol + ".conf") + if err != nil { + t.Fatal(err) + } + cert, _ := filepath.Abs("../../certs/ssl_cert.pem") + key, _ := filepath.Abs("../../certs/ssl_key.pem") + _, frontendPort, _ := net.SplitHostPort(frontendAddr) + _, maintenancePort, _ := net.SplitHostPort(maintenanceFrontend) + snippetText := strings.NewReplacer( + "127.0.0.1:62150", backendAddr, "127.0.0.1:62151", maintenanceAddr, + "listen 62050 ", "listen 127.0.0.1:"+frontendPort+" ", + "listen 62051 ", "listen 127.0.0.1:"+maintenancePort+" ", + "/etc/pg-node-tls/fullchain.pem", cert, "/etc/pg-node-tls/privkey.pem", key, + ).Replace(string(snippet)) + dir := t.TempDir() + configPath := filepath.Join(dir, "nginx.conf") + configText := "daemon off; master_process off; error_log stderr; pid " + dir + "/nginx.pid; events {} http { access_log off; client_body_temp_path " + dir + "/body; proxy_temp_path " + dir + "/proxy; " + snippetText + " }" + if err := os.WriteFile(configPath, []byte(configText), 0600); err != nil { + t.Fatal(err) + } + logFile, err := os.Create(filepath.Join(dir, "nginx.log")) + if err != nil { + t.Fatal(err) + } + defer logFile.Close() + cmd := exec.Command(nginx, "-p", dir, "-c", configPath) + cmd.Stdout, cmd.Stderr = logFile, logFile + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { cmd.Process.Kill(); cmd.Wait() }) + deadline := time.Now().Add(5 * time.Second) + for { + conn, err := net.DialTimeout("tcp", maintenanceFrontend, 100*time.Millisecond) + if err == nil { + conn.Close() + break + } + if time.Now().After(deadline) { + data, _ := os.ReadFile(logFile.Name()) + t.Fatalf("nginx did not start: %s", data) + } + time.Sleep(20 * time.Millisecond) + } + pool, err := tlsutil.LoadClientPool(cert) + if err != nil { + t.Fatal(err) + } + client := &http.Client{Timeout: 3 * time.Second, Transport: &http.Transport{TLSClientConfig: &tls.Config{RootCAs: pool}}} + defer client.CloseIdleConnections() + checkHTTP := func(addr, path string, auth bool) { + req, _ := http.NewRequest("GET", "https://"+addr+path, nil) + if auth { + req.Header.Set("x-api-key", "proxy-test-key") + } + resp, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + want := 401 + if auth { + want = 200 + } + if resp.StatusCode != want { + t.Fatalf("HTTP %s: %d", path, resp.StatusCode) + } + if path == "/logs" && auth { + line, err := bufio.NewReader(resp.Body).ReadString('\n') + if err != nil || line != "stream ready\n" { + t.Fatalf("stream buffering: %q %v", line, err) + } + } + } + checkHTTP(maintenanceFrontend, "/", false) + checkHTTP(maintenanceFrontend, "/", true) + if protocol == "rest" { + checkHTTP(frontendAddr, "/", false) + checkHTTP(frontendAddr, "/", true) + checkHTTP(frontendAddr, "/logs", true) + } else { + conn, err := grpc.NewClient(frontendAddr, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{RootCAs: pool}))) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + client := common.NewNodeServiceClient(conn) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + stream, err := client.GetLogs(ctx, &common.Empty{}) + if err != nil { + t.Fatal(err) + } + if _, err := stream.Recv(); status.Code(err) != codes.Unauthenticated { + t.Fatalf("gRPC stream auth: %v", err) + } + authCtx := metadata.NewOutgoingContext(ctx, metadata.Pairs("x-api-key", "proxy-test-key")) + stream, err = client.GetLogs(authCtx, &common.Empty{}) + if err != nil { + t.Fatal(err) + } + for i := 0; i < 3; i++ { + log, err := stream.Recv() + if err != nil || log.Detail != fmt.Sprint(i) { + t.Fatalf("gRPC stream %d: %v %v", i, log, err) + } + } + } + }) + } +} + +type proxyStreamService struct { + common.UnimplementedNodeServiceServer +} + +func (proxyStreamService) GetLogs(_ *common.Empty, stream common.NodeService_GetLogsServer) error { + md, _ := metadata.FromIncomingContext(stream.Context()) + keys := md.Get("x-api-key") + if len(keys) == 0 || keys[0] != "proxy-test-key" { + return status.Error(codes.Unauthenticated, "missing key") + } + for i := 0; i < 3; i++ { + if err := stream.Send(&common.Log{Detail: fmt.Sprint(i)}); err != nil { + return err + } + } + return nil +} diff --git a/config/config.go b/config/config.go index 6be786ac..4e83e2e9 100644 --- a/config/config.go +++ b/config/config.go @@ -14,6 +14,7 @@ import ( ) type Config struct { + TLSEnabled bool ServicePort int NodeHost string XrayExecutablePath string @@ -46,6 +47,7 @@ func Load() (*Config, error) { } cfg := &Config{ + TLSEnabled: true, ServicePort: GetEnvAsInt("SERVICE_PORT", 62050), XrayExecutablePath: GetEnv("XRAY_EXECUTABLE_PATH", "/usr/local/bin/xray"), TelemtExecutablePath: GetEnv("TELEMT_EXECUTABLE_PATH", "/usr/local/bin/telemt"), @@ -89,9 +91,38 @@ func Load() (*Config, error) { apiKeyErr = fmt.Errorf("invalid API_KEY: %w", apiKeyErr) } - cfg.NodeHost = parseNodeHost(GetEnv("NODE_HOST", "0.0.0.0")) + var tlsErr error + if value, exists := os.LookupEnv("TLS_ENABLED"); exists { + cfg.TLSEnabled, tlsErr = strconv.ParseBool(value) + if tlsErr != nil { + tlsErr = fmt.Errorf("invalid TLS_ENABLED %q: expected a boolean", value) + } + } + defaultHost := "0.0.0.0" + if !cfg.TLSEnabled { + defaultHost = "127.0.0.1" + } + host := GetEnv("NODE_HOST", defaultHost) + var hostErr error + if cfg.TLSEnabled { + cfg.NodeHost = parseNodeHost(host) + } else { + cfg.NodeHost, hostErr = PrivateBackendHost(host) + } + return cfg, errors.Join(apiKeyErr, tlsErr, hostErr) +} - return cfg, apiKeyErr +// PrivateBackendHost permits only literal loopback, RFC1918 and IPv6 ULA +// addresses. Do not resolve hostnames: DNS changes must never expose a backend. +func PrivateBackendHost(value string) (string, error) { + addr, err := netip.ParseAddr(strings.TrimSpace(value)) + if err == nil && addr.Zone() == "" { + addr = addr.Unmap() + if addr.IsLoopback() || addr.IsPrivate() { + return addr.String(), nil + } + } + return "", fmt.Errorf("TLS_ENABLED=false requires NODE_HOST to be a loopback, RFC1918 IPv4 or IPv6 unique-local address; got %q", value) } // parseNodeHost returns the IPv4 or IPv6 address to listen on; "localhost" means 127.0.0.1. diff --git a/config/config_test.go b/config/config_test.go index 39717e84..8a59dd7f 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -64,6 +64,44 @@ func TestLoadAcceptsValidAPIKey(t *testing.T) { } } +func TestLoadTLSSettings(t *testing.T) { + t.Setenv("API_KEY", "3fa85f64-5717-4562-b3fc-2c963f66afa6") + unsetEnv(t, "TLS_ENABLED") + unsetEnv(t, "NODE_HOST") + cfg, err := Load() + if err != nil || !cfg.TLSEnabled || cfg.NodeHost != "0.0.0.0" { + t.Fatalf("TLS defaults: %+v, %v", cfg, err) + } + t.Setenv("TLS_ENABLED", "false") + cfg, err = Load() + if err != nil || cfg.TLSEnabled || cfg.NodeHost != "127.0.0.1" { + t.Fatalf("backend defaults: %+v, %v", cfg, err) + } + for _, value := range []string{"", "yes", "disabled", " true "} { + t.Setenv("TLS_ENABLED", value) + if _, err := Load(); err == nil { + t.Fatalf("accepted invalid TLS_ENABLED=%q", value) + } + } +} + +func TestPrivateBackendHosts(t *testing.T) { + t.Setenv("API_KEY", "3fa85f64-5717-4562-b3fc-2c963f66afa6") + t.Setenv("TLS_ENABLED", "false") + for _, host := range []string{"127.0.0.1", "127.255.255.254", "::1", "10.0.0.1", "172.16.0.1", "172.31.255.254", "192.168.1.1", "fc00::1", "fdff::1", "::ffff:192.168.1.2"} { + t.Setenv("NODE_HOST", host) + if _, err := Load(); err != nil { + t.Errorf("rejected %q: %v", host, err) + } + } + for _, host := range []string{"", "localhost", "invalid", "0.0.0.0", "::", "8.8.8.8", "100.64.0.1", "169.254.1.1", "172.15.0.1", "172.32.0.1", "192.0.0.1", "192.0.2.1", "198.18.0.1", "224.0.0.1", "255.255.255.255", "2001:db8::1", "fe80::1", "ff02::1", "::ffff:8.8.8.8", "fd00::1%eth0", "[::1]"} { + t.Setenv("NODE_HOST", host) + if _, err := Load(); err == nil { + t.Errorf("accepted unsafe NODE_HOST=%q", host) + } + } +} + func TestLoadAcceptsNodeHostIPsAndLocalhost(t *testing.T) { cases := map[string]string{ "0.0.0.0": "0.0.0.0", diff --git a/controller/rest/service.go b/controller/rest/service.go index d4867922..24bbe34e 100644 --- a/controller/rest/service.go +++ b/controller/rest/service.go @@ -5,6 +5,7 @@ import ( "crypto/tls" "errors" "log" + "net" "net/http" "github.com/go-chi/chi/v5" @@ -12,6 +13,7 @@ import ( "github.com/pasarguard/node/config" "github.com/pasarguard/node/controller" + "github.com/pasarguard/node/pkg/tlsutil" ) func New(cfg *config.Config) *Service { @@ -75,6 +77,9 @@ type Service struct { } func StartHttpListener(tlsConfig *tls.Config, addr string, cfg *config.Config) (func(ctx context.Context) error, controller.Service, error) { + if err := tlsutil.ValidateListener(tlsConfig, addr, cfg); err != nil { + return nil, nil, err + } s := New(cfg) httpServer := &http.Server{ @@ -84,10 +89,13 @@ func StartHttpListener(tlsConfig *tls.Config, addr string, cfg *config.Config) ( } // Test if we can listen on the port before starting the goroutine - listener, err := tls.Listen("tcp", addr, tlsConfig) + listener, err := net.Listen("tcp", addr) if err != nil { return nil, nil, err } + if tlsConfig != nil { + listener = tls.NewListener(listener, tlsConfig) + } go func() { log.Println("HTTP Server listening on", addr) diff --git a/controller/rpc/service.go b/controller/rpc/service.go index d633c412..0375ebed 100644 --- a/controller/rpc/service.go +++ b/controller/rpc/service.go @@ -10,6 +10,7 @@ import ( "github.com/pasarguard/node/common" "github.com/pasarguard/node/config" "github.com/pasarguard/node/controller" + "github.com/pasarguard/node/pkg/tlsutil" "google.golang.org/grpc" "google.golang.org/grpc/credentials" ) @@ -26,20 +27,24 @@ func New(cfg *config.Config) *Service { } func StartGRPCListener(tlsConfig *tls.Config, addr string, cfg *config.Config) (func(ctx context.Context) error, controller.Service, error) { + if err := tlsutil.ValidateListener(tlsConfig, addr, cfg); err != nil { + return nil, nil, err + } s := New(cfg) - creds := credentials.NewTLS(tlsConfig) - // Create the gRPC server with conditional middleware // Set max message size to 64MB to handle large configs and user data const maxMsgSize = 64 * 1024 * 1024 // 64MB - grpcServer := grpc.NewServer( - grpc.Creds(creds), + opts := []grpc.ServerOption{ grpc.MaxRecvMsgSize(maxMsgSize), grpc.MaxSendMsgSize(maxMsgSize), grpc.UnaryInterceptor(ConditionalMiddleware(s)), grpc.StreamInterceptor(ConditionalStreamMiddleware(s)), - ) + } + if tlsConfig != nil { + opts = append(opts, grpc.Creds(credentials.NewTLS(tlsConfig))) + } + grpcServer := grpc.NewServer(opts...) // Register the service common.RegisterNodeServiceServer(grpcServer, s) diff --git a/docker-compose.yml b/docker-compose.yml index 3348aff9..8529e650 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -13,6 +13,10 @@ services: environment: SERVICE_PORT: 62050 SERVICE_PROTOCOL: "grpc" + # External TLS termination: set TLS_ENABLED=false and NODE_HOST=127.0.0.1. + # Keep the backend private; the panel always connects to the TLS frontend. + # TLS_ENABLED: "true" + # NODE_HOST: "0.0.0.0" # Linux: enable runtime IPv4 forwarding and install scoped nftables NAT/forwarding rules. # NAT egress is auto-detected (ip route / /proc/net/route); set PG_NODE_WG_NAT_OUTPUT_INTERFACE to override (e.g. eth0, ens192). # For Xray TUN egress (no NAT) set PG_NODE_WG_NAT_DISABLE=1 and PG_NODE_WG_ROUTE_TABLE / PG_NODE_WG_ROUTE_OUT_INTERFACE (e.g. xray0). See .env.example. diff --git a/docs/node-tls.md b/docs/node-tls.md new file mode 100644 index 00000000..04ac4d14 --- /dev/null +++ b/docs/node-tls.md @@ -0,0 +1,163 @@ +# Node TLS and certificate management + +The panel connects to the node and maintenance service over TLS. Direct node +listeners retain TLS by default, including existing installations without a +`TLS_ENABLED` setting. Both listeners read `SSL_CERT_FILE` and `SSL_KEY_FILE`. +API-key authentication remains required with either listener configuration. + +## Installation + +The node installer in `PasarGuard/scripts` offers these certificate choices: + +1. Let's Encrypt IP certificate (default). +2. Let's Encrypt domain certificate. +3. Custom certificate and private key paths. +4. Self-signed certificate. +5. External TLS termination by a web server. + +For IP certificates, interactive installation proposes the detected public IPv4 +and accepts a correction and optional IPv6. Unattended installation requires an +explicit IPv4 identifier: + +```sh +pg-node install -y --ssl-ip YOUR_PUBLIC_IPV4 +pg-node install -y --ssl-ip YOUR_PUBLIC_IPV4 --ssl-ipv6 YOUR_PUBLIC_IPV6 +pg-node install -y --ssl-domain node.example.com +pg-node install -y --cert-path /path/fullchain.pem --key-path /path/privkey.pem +pg-node install -y --self-signed --san-entries DNS:node.example.com,IP:YOUR_PUBLIC_IPV4 +pg-node install -y --no-ssl +``` + +Choose one certificate source. `--cert-path` and `--key-path` must be used +together. `--ssl-ipv6` requires `--ssl-ip`. Old unattended commands that relied +on implicit self-signed generation must add `--self-signed`. + +ACME uses HTTP-01. Public TCP port 80 must reach the challenge listener. Use +`--ssl-http-port PORT` (alias `--ssl-port`) when forwarding public port 80 to +another local port. The installer reports occupied ports and does not stop other +services. Issuance failures stop installation; retry explicitly after correcting +the problem. There is no automatic certificate or transport fallback. + +New managed files use `fullchain.pem` and `privkey.pem` under the instance's data +directory: + +| Source | Directory | +| --- | --- | +| IP ACME | `certs/ip/` | +| Domain ACME | `certs//` | +| Custom | `certs/custom/` | +| Self-signed | Existing `certs/ssl_cert.pem` and `certs/ssl_key.pem` paths | + +`certs/source.json` records the installer certificate source and ACME identifiers. +It does not select the panel's verification policy. Certificates are validated +for parsing, matching keys, valid dates, SAN presence, and ACME identifier matches +before replacing active files. Full chains are preserved and private keys are +restricted to their owner. The node container mounts the same data path used by +the host maintenance service, so both read the same active pair. + +Routine `update` commands preserve the existing certificate files and configured +paths. `pg-node show-cert` displays the source, identity, validity, leaf DER +SHA-256 fingerprint, and PEM for older panels. + +## Panel verification and renewal + +Use a panel and bridge release supporting the new verification fields before +clearing PEM or configuring fingerprints. Upgrade all panel workers first. + +| Certificate | Recommended panel fields | +| --- | --- | +| Publicly trusted certificate | Empty `server_ca`, null `certificate_sha256` | +| Self-signed certificate | Empty `server_ca`, trusted leaf DER `certificate_sha256` | +| Older panel | Preserve its existing PEM verification configuration | + +A pin takes precedence over PEM when both fields are populated. Clearing a pin +with PEM retained restores PEM verification; clear both to select system trust. +Pin verification also checks dates and SANs. Obtain the fingerprint through a +trusted channel and use an address included in the certificate SANs. + +`pg-node renew-cert` follows the saved source: + +- ACME: renew using acme.sh. Its scheduled renewal deploys to staging, validates + against the saved identifiers, activates the files, and restarts the instance's + Compose service and installed maintenance systemd unit. RSA and ECC deployments + are supported. Restart failures are reported. +- Self-signed: regenerate explicitly and display the new fingerprint. Update the + panel pin before reconnecting. +- Custom: validate the current replacement files and restart both services. + Renew the files externally and preserve the full chain. Keep the previous pair + in an operator backup before replacing them. +- External TLS: manage and renew the certificate on the web server. + +Older installations without source metadata retain their configured paths. +Explicit renewal recognizes self-signed certificates; other legacy certificates +are validated and remain the operator's renewal responsibility. Validated +installer deployments retain the previous active pair in `.previous` files. + +ACME's cron scheduling is required during setup. Short-lived IP certificates use +the Let's Encrypt `shortlived` profile. Normal system-trust verification allows +renewal without changing panel fields. Monitor renewal and restart failures; +mocked CI does not replace controlled ACME staging issuance on a reachable public +host before rollout. + +## External TLS termination + +Set up the web server and certificate before changing the panel endpoints. Use +one of the nginx snippets below inside its `http {}` configuration: + +- [REST and maintenance](../examples/nginx/rest.conf). +- [gRPC and maintenance](../examples/nginx/grpc.conf). + +The snippets keep separate public service and maintenance ports (62050 and 62051) +and forward to private ports 62150 and 62151. Configure the node environment: + +```dotenv +TLS_ENABLED=false +NODE_HOST=127.0.0.1 +SERVICE_PORT=62150 +API_PORT=62151 +SERVICE_PROTOCOL=grpc +# Keep the existing API_KEY. Use SERVICE_PROTOCOL=rest with rest.conf. +``` + +Set the frontend certificate paths and server name in the snippet, then validate +and reload nginx using your deployment's normal procedure. Its two TLS listeners +must present the same leaf certificate when the panel uses a pin. Configure the +panel with the TLS frontend's address, service port, and maintenance port. Keep +the existing endpoints at `/`; endpoint-specific hostnames and arbitrary base +paths are not supported. + +The examples preserve API-key headers, long-running responses, HTTP/2 gRPC, +request streaming, and the node's 64 MiB gRPC limit. The maintenance body limit +is 1 MiB. No client certificate is required merely because the server's +certificate is CA-signed. The shell maintenance implementation requires `socat` +and `python3` for its private plaintext listener. + +With TLS disabled, certificate files are not loaded. A missing `NODE_HOST` +defaults to `127.0.0.1`. Explicit values must be literal addresses from IPv4 +loopback, `::1`, RFC1918 IPv4, or IPv6 unique-local ranges. IPv4-mapped IPv6 is +normalized first. Public, wildcard, link-local, multicast, scoped, malformed, +and other special-use addresses are rejected. Hostnames, including `localhost`, +are rejected in plaintext mode. Invalid `TLS_ENABLED` values fail startup. + +The example Compose deployment uses host networking, so a web server on that +host can reach loopback. With separate containers, arrange private backend +networking and bind to an allowed private address reachable from the frontend. +Do not publish backend ports on public interfaces. Review firewall rules, NAT, +and container publishing: a private listener cannot prevent another component +from forwarding it publicly. Expose only the frontend TLS ports to panel clients. +Web-server installation and certificate provisioning are managed externally. + +## Rollback and CI + +Keep the old PEM and certificate pair in an operator backup before migrating. +Verify both normal and maintenance operations after each transition. Restore +usable PEM before using an older panel; restore node TLS before using older +node or maintenance binaries. The legacy `server_ca` field remains supported by +the migration design. + +Node CI runs direct TLS/private listener tests and the actual nginx snippets, +including REST streaming and gRPC streaming. Installer CI uses mocked ACME +commands and real local certificates without contacting an ACME issuer. The +maintenance repositories test startup, strict bindings, and authenticated HTTP +and TLS connections. Live public ACME staging issuance remains a deployment +integration check because it needs operator-controlled identifiers and routing. diff --git a/examples/nginx/grpc.conf b/examples/nginx/grpc.conf new file mode 100644 index 00000000..704cadc3 --- /dev/null +++ b/examples/nginx/grpc.conf @@ -0,0 +1,32 @@ +# Include inside nginx's http {} block. Change certificate paths and ports together. +server { + listen 62050 ssl http2; + server_name node.example.com; + ssl_certificate /etc/pg-node-tls/fullchain.pem; + ssl_certificate_key /etc/pg-node-tls/privkey.pem; + ssl_protocols TLSv1.2 TLSv1.3; + client_max_body_size 64m; + location / { + grpc_pass grpc://127.0.0.1:62150; + grpc_set_header Host $host; + grpc_read_timeout 3600s; + grpc_send_timeout 3600s; + } +} +server { + listen 62051 ssl; + server_name node.example.com; + ssl_certificate /etc/pg-node-tls/fullchain.pem; + ssl_certificate_key /etc/pg-node-tls/privkey.pem; + ssl_protocols TLSv1.2 TLSv1.3; + client_max_body_size 1m; + location / { + proxy_pass http://127.0.0.1:62151; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header Connection ""; + proxy_buffering off; + proxy_read_timeout 3600s; + proxy_send_timeout 3600s; + } +} diff --git a/examples/nginx/rest.conf b/examples/nginx/rest.conf new file mode 100644 index 00000000..90d83bf7 --- /dev/null +++ b/examples/nginx/rest.conf @@ -0,0 +1,36 @@ +# Include inside nginx's http {} block. Change certificate paths and ports together. +server { + listen 62050 ssl; + server_name node.example.com; + ssl_certificate /etc/pg-node-tls/fullchain.pem; + ssl_certificate_key /etc/pg-node-tls/privkey.pem; + ssl_protocols TLSv1.2 TLSv1.3; + client_max_body_size 64m; + location / { + proxy_pass http://127.0.0.1:62150; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header Connection ""; + proxy_buffering off; + proxy_request_buffering off; + proxy_read_timeout 3600s; + proxy_send_timeout 3600s; + } +} +server { + listen 62051 ssl; + server_name node.example.com; + ssl_certificate /etc/pg-node-tls/fullchain.pem; + ssl_certificate_key /etc/pg-node-tls/privkey.pem; + ssl_protocols TLSv1.2 TLSv1.3; + client_max_body_size 1m; + location / { + proxy_pass http://127.0.0.1:62151; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header Connection ""; + proxy_buffering off; + proxy_read_timeout 3600s; + proxy_send_timeout 3600s; + } +} diff --git a/node-tls-migration-plan.md b/node-tls-migration-plan.md new file mode 100644 index 00000000..6e00df19 --- /dev/null +++ b/node-tls-migration-plan.md @@ -0,0 +1,372 @@ +# Node TLS and certificate management migration + + +This replaces the previous plan. No file has been written while this session remains in Plan mode. + +## 1. Goals and confirmed decisions + +- The panel always uses TLS for node communication, including maintenance requests. +- New node installations default to a valid Let’s Encrypt IP certificate. +- Certificate installation follows the existing `pasarguard.sh` workflow. +- Existing PEM-based configurations continue working unchanged. +- Self-signed certificates support SHA-256 fingerprint verification, valid-date checks, and matching SANs. +- No `tls_mode` database column or API field is introduced. +- The panel/bridge determines verification from configured fields. +- Optional plaintext node listeners exist only as private backends behind a TLS-terminating web server. +- API-key authentication remains mandatory. + +```text +Default: +Panel ── TLS ──> Node + +Advanced: +Panel ── TLS ──> Web server ── private plaintext ──> Node +``` + +## 2. Automatic verification selection + +Use this exact precedence: + +| Saved configuration | Effective verification | +|---|---| +| Nonempty `certificate_sha256` | Pinned certificate | +| Otherwise, nonempty `server_ca` | Existing PEM-based verification | +| Neither present | System certificate trust | + +This is configuration-based detection, not trial-and-error fallback. + +A configured fingerprint must match even if the certificate is publicly trusted. A failed pin, PEM validation, or system-trust check must fail the connection without trying a weaker policy. + +When both fields are populated, the fingerprint takes precedence. PEM remains inactive until the fingerprint is explicitly cleared. + +### Certificate fingerprint + +`certificate_sha256` contains SHA-256 of the complete leaf certificate’s DER encoding—not the public key or PEM file. + +Accept contiguous hexadecimal or colon-separated byte pairs, case-insensitively. Normalize to 64 lowercase hexadecimal characters. + +Use one fingerprint per node. Main and maintenance endpoints must present the same leaf certificate when pinned, including reverse-proxy deployments. + +## 3. Database and API changes + +### Database + +Add only: + +```text +certificate_sha256: nullable string, length 64 +``` + +Keep the existing `server_ca` column and stored values unchanged. + +Do not add a mode column, contact nodes during migration, or automatically convert PEM certificates into pins. + +### API fields and validation + +- Make `server_ca` optional on creation, defaulting to an empty string. +- Add optional `certificate_sha256`, defaulting to null. +- Keep response `server_ca` values as strings. +- Reject malformed nonempty fingerprints and invalid nonempty PEM. +- Normalize whitespace-only PEM to an empty string. +- Permit both fields together, with documented fingerprint precedence. +- Creating a node without either field selects system trust. +- Existing create requests with PEM preserve legacy behavior. + +For updates: + +- Omitted fields retain their saved values. +- `certificate_sha256: null` or an empty string explicitly clears the pin. +- `server_ca: ""` explicitly clears PEM. +- Preserve existing `server_ca: null` update behavior as a no-op for compatibility. +- Validate the resulting merged configuration. +- Process fingerprint clearing explicitly rather than discarding it through `exclude_none=True`. + +Examples: + +| Desired transition | Update | +|---|---| +| Legacy → pinned | Set fingerprint; dashboard also clears PEM | +| Pinned → system trust | Clear fingerprint and PEM | +| Legacy → system trust | Clear PEM and any pin | +| System trust → legacy | Set PEM; clear any pin | +| Update unrelated settings | Omit both fields | + +Because verification depends on fields, retaining PEM while clearing a pin intentionally returns to legacy verification. The dashboard must clear both fields when selecting system trust. + +### Propagation + +Update CRUD, responses, bulk operations, cloning, imports/exports, bridge construction, worker synchronization, OpenAPI, and generated dashboard types. + +Add the fingerprint to the connection signature. Changes to either verification field must recreate connections and pools. + +## 4. Bridge implementation + +Preserve existing positional constructor compatibility. Add `certificate_sha256` as an optional keyword-only argument, and allow absent/empty PEM. + +Implement one shared policy resolver using the precedence above. The bridge independently validates configuration so direct library consumers receive the same behavior as panel users. + +All REST and maintenance URLs remain HTTPS. All panel gRPC connections remain TLS-enabled. + +Apply verification consistently to: + +- gRPC. +- REST. +- Maintenance operations. +- Streaming and reconnects. +- Supported proxy connections. + +### Pinned verification + +On the actual connection carrying application traffic: + +1. Obtain the peer leaf certificate. +2. Compare its DER SHA-256 fingerprint. +3. Check validity dates. +4. Match the configured domain/IP against SANs. +5. Only then allow API keys, metadata, and request bodies to be sent. + +Do not use Common Name fallback in this new verification path. + +Do not verify a separate probe connection and then send application traffic through another unverified connection. + +### Other verification + +- Nonempty PEM without a pin preserves current trust-store and hostname behavior. +- Empty PEM without a pin uses the runtime system trust store and standard certificate identity verification. +- Preserve separate HTTP/2 and HTTP/1.1 ALPN handling. +- Disable automatic node-request redirects. +- Close failed connections. +- Invalidate pools after verification changes. +- Prevent pinned connections from remaining reusable beyond certificate expiry. + +Report distinct failures for fingerprint mismatch, invalid dates, identity mismatch, and untrusted issuer. Never downgrade verification or transport. + +## 5. Dashboard behavior + +A UI-only verification selector may remain for usability: + +- Trusted certificate — default. +- SHA-256 fingerprint. +- Legacy PEM certificate. + +It is not stored or submitted as a mode field. + +Infer its initial selection using the same field precedence as the bridge. + +On save: + +| UI selection | Submitted fields | +|---|---| +| Trusted certificate | Empty PEM, null fingerprint | +| SHA-256 fingerprint | Fingerprint, empty PEM | +| Legacy PEM certificate | PEM, null fingerprint | + +If an existing API-created record contains both fields, display fingerprint verification and explain that the saved PEM is inactive. Saving through the fingerprint form normalizes the record by clearing PEM. + +Preserve effective verification during cloning, bulk actions, and form resets. + +Do not offer plaintext panel connections or “ignore certificate errors.” + +For reverse-proxy deployments, explain that the address and ports identify the TLS frontend. + +## 6. Node-only TLS termination setting + +Introduce: + +```text +TLS_ENABLED=true +``` + +Missing settings preserve current TLS operation. Invalid values fail startup. + +### TLS enabled + +- Load configured certificate/key files. +- Keep TLS REST and gRPC listeners. +- Use the same active certificate pair for maintenance. + +### TLS disabled + +This is exclusively an external-web-server backend option: + +- Skip certificate loading. +- Serve REST and maintenance over HTTP. +- Serve gRPC over cleartext HTTP/2. +- Preserve API-key authentication. +- Default binding to `127.0.0.1`. + +Allow explicit bindings only to: + +- IPv4 loopback and `::1`. +- RFC1918 IPv4. +- IPv6 unique-local addresses. + +Normalize IPv4-mapped IPv6 before checking. Reject public, wildcard, link-local, multicast, malformed, and other special-use addresses. + +Use `NODE_HOST` consistently for main and maintenance listeners. Reject `0.0.0.0` and `::` in plaintext backend mode. + +The bridge receives no plaintext option. + +## 7. Certificate installation and renewal + +### Installation menu + +Model the flow on `pasarguard.sh`: + +1. **Let’s Encrypt IP certificate — default.** +2. Let’s Encrypt domain certificate. +3. Custom certificate/key paths. +4. Self-signed certificate. +5. External web server terminates TLS — advanced. + +For interactive IP issuance, propose detected public IPv4 and permit correction; support optional IPv6. + +For unattended default IP issuance, require an explicit IP identifier. Fail with instructions when absent; do not silently generate self-signed certificates. + +Preserve explicit `--self-signed`, `--cert-path`, and `--key-path` options. + +Add: + +- `--ssl-ip IPV4` +- `--ssl-ipv6 IPV6`, requiring `--ssl-ip` +- `--ssl-domain DOMAIN` +- `--ssl-http-port PORT`, with `--ssl-port` alias +- `--no-ssl`, documented as external TLS termination only + +Reject conflicting selections. Document that old unattended commands relying on implicit self-signed generation must add `--self-signed`. + +### ACME workflow + +Adapt the panel installer’s existing helpers for dependencies, `acme.sh`, domain/IP issuance, short-lived IP certificates, RSA/ECC deployment, renewal scheduling, and restart hooks. + +Keep node-specific helpers in the node installer; do not source the executable panel installer or refactor it in this task. + +Report challenge-port conflicts without stopping unrelated services. Explain external challenge routing when a nondefault local port is selected. + +### Paths and certificate source + +Preserve existing paths on upgrade. + +For new managed certificates: + +- IP: `$DATA_DIR/certs/ip/` +- Domain: `$DATA_DIR/certs//` +- Custom: `$DATA_DIR/certs/custom/` +- Self-signed: existing node paths + +Use `fullchain.pem` and `privkey.pem` in new managed directories. + +Update `SSL_CERT_FILE`, `SSL_KEY_FILE`, and container mappings so both listeners use the active pair. + +Persist installer-side certificate source metadata: `acme_ip`, `acme_domain`, `custom`, `self_signed`, or `external_tls`. This metadata belongs to node certificate management, not the panel database or verification policy. + +### Validation and failure behavior + +Before activation, validate certificate parsing, matching key, dates, and expected SANs. Preserve full chains and restrictive key permissions. + +Stage replacements and retain working files on failure. + +Issuance failure stops or offers an explicit retry. Never silently switch to self-signed or plaintext operation. + +### Renewal + +Make `renew-cert` source-aware: + +- ACME: renew, validate, deploy, restart both listeners. +- Self-signed: explicitly regenerate and display the new fingerprint. +- Custom: validate replacements and document external renewal responsibility. +- External TLS: direct certificate management to the web server. + +Use deployment-specific restart targets and report failures. + +ACME certificates should normally use system trust—both panel verification fields empty—so renewal requires no panel changes. + +Retain PEM-display commands for older panels. Print certificate identity, expiry, source, fingerprint, and recommended panel fields after installation. + +Routine upgrades must not regenerate certificates. + +## 8. Maintenance and reverse-proxy deployment + +Make the maintenance script honor `TLS_ENABLED` and the same binding restrictions. + +Use its existing HTTP handler behind a bound plaintext TCP listener when externally terminated; require `socat` for that path. + +Separate client-certificate authentication from server certificate issuer classification. Keep API-key authentication. + +Provide tested web-server examples for: + +- HTTPS to private REST. +- TLS gRPC to private cleartext gRPC. +- HTTPS to private maintenance HTTP. + +Preserve credentials, streaming, HTTP/2, timeouts, and message limits. + +Retain the existing panel address and separate service/maintenance ports; do not introduce arbitrary base paths or endpoint-specific hostnames. + +The panel verifies the frontend certificate. Pinned frontends must present the same leaf certificate on both ports. + +Document firewall, NAT, and container publishing requirements. Private binding alone cannot prevent another component from exposing the backend. + +Automatic web-server installation is outside scope. + +## 9. Migration and rollback + +Release: + +1. Backward-compatible bridge. +2. Node and maintenance listener support. +3. Installer and renewal changes. +4. Panel additive migration, dependency update, API, and dashboard. +5. Tested deployment documentation. + +Upgrade all panel workers before configuring fingerprints. + +Existing PEM records continue selecting legacy verification automatically. + +Migration is explicit: + +- To pinned: obtain a trusted fingerprint and set it. +- To system trust: clear both certificate fields after confirming the server’s trusted certificate and identity. +- To external termination: configure the web server first, then point the panel at its TLS endpoints. + +Verify main and maintenance operations after each transition. + +A field-based design cannot retain PEM in the same active record while selecting system trust. Preserve old PEM in an operator backup if rollback is needed. + +Before running older panel versions, restore usable PEM and remove reliance on fingerprint-only or system-trust-only configuration. Restore node TLS before running older node/scripts when necessary. + +Retain `server_ca`; removal requires a later breaking release. + +## 10. Tests and acceptance criteria + +### Automatic selection + +- Pin only selects pinned verification. +- PEM only preserves legacy verification. +- Neither selects system trust. +- Both select pinned verification. +- Wrong pin fails even with a trusted certificate or valid PEM. +- Clearing a pin with PEM retained restores legacy verification. +- Clearing both selects system trust. +- Omitted fields do not alter policy. +- No mode column or API field is introduced. + +### Transport and panel + +Test real TLS connections for fingerprint, date, SAN, and trust-chain success/failure across all transports, reconnects, and supported proxies. + +Verify credentials are withheld until verification succeeds, policy changes close old pools, and TLS never falls back to plaintext. + +Cover partial updates, explicit clearing, cloning, bulk operations, dashboard normalization, and legacy constructors. + +### Node and reverse proxy + +Verify TLS defaults, strict private backend bindings, authentication, operation without backend certificate files, and TLS frontend connections for REST, gRPC, maintenance, and streaming. + +### Installer and renewal + +Test the IP-certificate default, explicit legacy flags, unattended identifiers, ACME scheduling, RSA/ECC deployment, failure preservation, source-aware renewal, both listener restart targets, and unchanged upgrade paths. + +Use mocked ACME calls for automated tests and controlled staging issuance for integration validation. + +Acceptance requires unchanged legacy operation, deterministic field-based verification, reliable valid-IP issuance and renewal, TLS on every panel connection, and plaintext restricted to explicitly configured private web-server backends. \ No newline at end of file diff --git a/pkg/tlsutil/tls.go b/pkg/tlsutil/tls.go index e8934a54..43962e82 100644 --- a/pkg/tlsutil/tls.go +++ b/pkg/tlsutil/tls.go @@ -4,11 +4,30 @@ import ( "crypto/tls" "crypto/x509" "fmt" + "net" "net/http" "os" "time" + + "github.com/pasarguard/node/config" ) +// ValidateListener also guards direct callers that bypass config.Load. +func ValidateListener(tlsConfig *tls.Config, addr string, cfg *config.Config) error { + if tlsConfig != nil { + return nil + } + if cfg.TLSEnabled { + return fmt.Errorf("TLS_ENABLED=true requires TLS credentials") + } + host, _, err := net.SplitHostPort(addr) + if err != nil { + return err + } + _, err = config.PrivateBackendHost(host) + return err +} + func LoadTLSCredentials(cert, key string) (*tls.Config, error) { serverCert, err := tls.LoadX509KeyPair(cert, key) if err != nil { From 108d57e12467ee726aaf3f6c0262e3140d69d896 Mon Sep 17 00:00:00 2001 From: Mohammad Date: Mon, 16 Nov 2026 18:02:37 +0330 Subject: [PATCH 2/2] fix(nginx): remove whole-stream body limit on grpc frontend Set client_max_body_size to 0 in the gRPC frontend nginx snippet to prevent Nginx from imposing an aggregate stream body limit, while retaining the separate 1 MiB maintenance limit and backend 64 MiB per-message enforcement. Add client-streaming regression tests covering streams exceeding 64 MiB. --- cmd/node/proxy_test.go | 164 +++++++++++++++++++++++++++++++++++++-- examples/nginx/grpc.conf | 2 +- 2 files changed, 160 insertions(+), 6 deletions(-) diff --git a/cmd/node/proxy_test.go b/cmd/node/proxy_test.go index 84d3b1e5..0370e1a4 100644 --- a/cmd/node/proxy_test.go +++ b/cmd/node/proxy_test.go @@ -4,7 +4,9 @@ import ( "bufio" "context" "crypto/tls" + "errors" "fmt" + "io" "net" "net/http" "os" @@ -19,12 +21,14 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" + "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) -// Exercise the shipped nginx snippets in CI, including HTTP streaming and gRPC -// server streaming. Direct node listeners are covered by TestListenerTransports. +// Exercise the shipped nginx snippets in CI, including HTTP streaming, gRPC +// server streaming, and gRPC client streaming. Direct node listeners are covered +// by TestListenerTransports. func TestNginxTLSFrontends(t *testing.T) { nginx := os.Getenv("NODE_TEST_NGINX") if nginx == "" { @@ -64,7 +68,11 @@ func TestNginxTLSFrontends(t *testing.T) { if err != nil { t.Fatal(err) } - s := grpc.NewServer() + const maxMsgSize = 64 * 1024 * 1024 + s := grpc.NewServer( + grpc.MaxRecvMsgSize(maxMsgSize), + grpc.MaxSendMsgSize(maxMsgSize), + ) common.RegisterNodeServiceServer(s, proxyStreamService{}) go s.Serve(l) t.Cleanup(s.Stop) @@ -150,13 +158,21 @@ func TestNginxTLSFrontends(t *testing.T) { checkHTTP(frontendAddr, "/", true) checkHTTP(frontendAddr, "/logs", true) } else { - conn, err := grpc.NewClient(frontendAddr, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{RootCAs: pool}))) + const maxMsgSize = 64 * 1024 * 1024 + conn, err := grpc.NewClient( + frontendAddr, + grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{RootCAs: pool})), + grpc.WithDefaultCallOptions( + grpc.MaxCallRecvMsgSize(maxMsgSize), + grpc.MaxCallSendMsgSize(maxMsgSize), + ), + ) if err != nil { t.Fatal(err) } defer conn.Close() client := common.NewNodeServiceClient(conn) - ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() stream, err := client.GetLogs(ctx, &common.Empty{}) if err != nil { @@ -176,11 +192,125 @@ func TestNginxTLSFrontends(t *testing.T) { t.Fatalf("gRPC stream %d: %v %v", i, log, err) } } + + // Regression case: client streaming whose total request size + // exceeds 64 MiB while each message remains within the 64 MiB limit. + uploadStream, err := client.SyncUsersChunked(ctx) + if err != nil { + t.Fatal(err) + } + if _, err := uploadStream.CloseAndRecv(); status.Code(err) != codes.Unauthenticated { + t.Fatalf("gRPC client stream auth: %v", err) + } + uploadAuthCtx := metadata.NewOutgoingContext(ctx, metadata.Pairs("x-api-key", "proxy-test-key")) + uploadStream, err = client.SyncUsersChunked(uploadAuthCtx) + if err != nil { + t.Fatal(err) + } + const ( + chunkSize = 8 * 1024 * 1024 + chunkCount = 9 + ) + chunk := &common.UsersChunk{ + Users: []*common.User{ + {Email: strings.Repeat("a", chunkSize)}, + }, + } + for i := 0; i < chunkCount; i++ { + if err := uploadStream.Send(chunk); err != nil { + t.Fatalf("gRPC client stream send %d: %v", i, err) + } + } + if _, err := uploadStream.CloseAndRecv(); err != nil { + t.Fatalf("gRPC client stream close: %v", err) + } } }) } } +// Exercise backend per-message limit and multi-message stream behavior directly. +func TestGRPCClientStreamingLimits(t *testing.T) { + backendAddr := listenerAddress(t) + l, err := net.Listen("tcp", backendAddr) + if err != nil { + t.Fatal(err) + } + const maxMsgSize = 64 * 1024 * 1024 + s := grpc.NewServer( + grpc.MaxRecvMsgSize(maxMsgSize), + grpc.MaxSendMsgSize(maxMsgSize), + ) + common.RegisterNodeServiceServer(s, proxyStreamService{}) + go s.Serve(l) + t.Cleanup(s.Stop) + + conn, err := grpc.NewClient( + backendAddr, + grpc.WithTransportCredentials(insecure.NewCredentials()), + grpc.WithDefaultCallOptions( + grpc.MaxCallRecvMsgSize(maxMsgSize), + grpc.MaxCallSendMsgSize(maxMsgSize), + ), + ) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + + client := common.NewNodeServiceClient(conn) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + authCtx := metadata.NewOutgoingContext(ctx, metadata.Pairs("x-api-key", "proxy-test-key")) + + // Total stream size > 64 MiB with each message within limit succeeds. + stream, err := client.SyncUsersChunked(authCtx) + if err != nil { + t.Fatal(err) + } + chunk := &common.UsersChunk{ + Users: []*common.User{ + {Email: strings.Repeat("a", 8*1024*1024)}, + }, + } + for i := 0; i < 9; i++ { + if err := stream.Send(chunk); err != nil { + t.Fatalf("stream send %d: %v", i, err) + } + } + if _, err := stream.CloseAndRecv(); err != nil { + t.Fatalf("stream close: %v", err) + } + + // Single message exceeding the 64 MiB backend limit is rejected. + oversizedConn, err := grpc.NewClient( + backendAddr, + grpc.WithTransportCredentials(insecure.NewCredentials()), + grpc.WithDefaultCallOptions( + grpc.MaxCallSendMsgSize(70 * 1024 * 1024), + ), + ) + if err != nil { + t.Fatal(err) + } + defer oversizedConn.Close() + + oversizedClient := common.NewNodeServiceClient(oversizedConn) + overStream, err := oversizedClient.SyncUsersChunked(authCtx) + if err != nil { + t.Fatal(err) + } + oversizedChunk := &common.UsersChunk{ + Users: []*common.User{ + {Email: strings.Repeat("b", 65*1024*1024)}, + }, + } + _ = overStream.Send(oversizedChunk) + if _, err := overStream.CloseAndRecv(); status.Code(err) != codes.ResourceExhausted { + t.Fatalf("expected ResourceExhausted for message >64 MiB, got: %v", err) + } +} + type proxyStreamService struct { common.UnimplementedNodeServiceServer } @@ -198,3 +328,27 @@ func (proxyStreamService) GetLogs(_ *common.Empty, stream common.NodeService_Get } return nil } + +func (proxyStreamService) SyncUsersChunked(stream common.NodeService_SyncUsersChunkedServer) error { + md, _ := metadata.FromIncomingContext(stream.Context()) + keys := md.Get("x-api-key") + if len(keys) == 0 || keys[0] != "proxy-test-key" { + return status.Error(codes.Unauthenticated, "missing key") + } + var totalBytes int + for { + chunk, err := stream.Recv() + if errors.Is(err, io.EOF) { + if totalBytes <= 64*1024*1024 { + return status.Errorf(codes.InvalidArgument, "total stream size %d does not exceed 64 MiB", totalBytes) + } + return stream.SendAndClose(&common.Empty{}) + } + if err != nil { + return err + } + for _, u := range chunk.GetUsers() { + totalBytes += len(u.GetEmail()) + } + } +} diff --git a/examples/nginx/grpc.conf b/examples/nginx/grpc.conf index 704cadc3..7bc6a398 100644 --- a/examples/nginx/grpc.conf +++ b/examples/nginx/grpc.conf @@ -5,7 +5,7 @@ server { ssl_certificate /etc/pg-node-tls/fullchain.pem; ssl_certificate_key /etc/pg-node-tls/privkey.pem; ssl_protocols TLSv1.2 TLSv1.3; - client_max_body_size 64m; + client_max_body_size 0; location / { grpc_pass grpc://127.0.0.1:62150; grpc_set_header Host $host;