From d6d8f9c6d491035af01b45dbb838b4c65810b7f3 Mon Sep 17 00:00:00 2001 From: Anurag Banerjee Date: Sat, 31 Oct 2026 02:45:56 -0700 Subject: [PATCH] auth: share one LocalAPI client across tailscale_auth modules Each Auth on the system tailscaled path built its own local.Client, and a client cannot close its idle connections. Authenticate's value receiver stranded one per request, and Caddy building new modules on each config load stranded one per reload. One process-wide client stops both. Fixes #147 Change-Id: Ib5ae8d26152e0b2a3a6d213064ed7ce4a39f34de Signed-off-by: Anurag Banerjee --- auth.go | 9 +++++++-- auth_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 auth_test.go diff --git a/auth.go b/auth.go index c84ac09..a0a097f 100644 --- a/auth.go +++ b/auth.go @@ -90,6 +90,11 @@ type wrappedListener interface { Unwrap() net.Listener } +// systemLocalClient talks to the local tailscaled on behalf of every Auth. Caddy +// builds new modules on each config load and a local.Client cannot close its idle +// connections, so a client per Auth would strand a connection pool at each reload. +var systemLocalClient = new(local.Client) + // client returns the tailscale LocalClient for the TailscaleAuth module. // If the LocalClient has not already been configured, the provided request will be used to // lookup the tailscale node that serviced the request, and get the associated LocalClient. @@ -112,8 +117,8 @@ func (ta *Auth) client(r *http.Request) (*local.Client, error) { } if ta.localclient == nil { - // default to empty client that will talk to local tailscaled - ta.localclient = new(local.Client) + // default to the shared client that will talk to local tailscaled + ta.localclient = systemLocalClient } return ta.localclient, nil diff --git a/auth_test.go b/auth_test.go new file mode 100644 index 0000000..a0b00b8 --- /dev/null +++ b/auth_test.go @@ -0,0 +1,32 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: Apache-2.0 + +package tscaddy + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + "github.com/caddyserver/caddy/v2/modules/caddyhttp" +) + +// Caddy provisions new modules on every config load, and Authenticate runs on a +// copy of Auth. Either way a new local.Client would strand its connections. +func TestAuthsShareSystemLocalClient(t *testing.T) { + r := httptest.NewRequest(http.MethodGet, "http://example.com/", nil) + r = r.WithContext(context.WithValue(r.Context(), caddyhttp.ServerCtxKey, &caddyhttp.Server{})) + + first, err := new(Auth).client(r) + if err != nil { + t.Fatal(err) + } + second, err := new(Auth).client(r) + if err != nil { + t.Fatal(err) + } + if first != second { + t.Fatal("each Auth built its own local.Client, leaking its connections") + } +}