Skip to content

tailscale_auth leaks LocalAPI connections on every config reload, even with #140 or #146 #147

Open

Description

@anuragbanerjee

#140 and #146 stop the per-request connection leak in tailscale_auth, but a second leak remains: every config reload strands connections to tailscaled until Caddy exits. A small change fixes both.

Cause

On the system tailscaled path, each Auth module builds its own local.Client. Caddy provisions new modules on every config load, so a reload replaces them. local.Client has no Close, its default http.Transport has no IdleConnTimeout, and the transport's goroutines keep the idle connections alive after the module is gone.

Reproduction

Run this with Tailscale up and a Caddy build that includes #140 or #146:

IP=$(tailscale ip -4 | head -1)
cat > Caddyfile <<CONF
{
	admin localhost:20299
	auto_https off
}
http://$IP:28543 {
	bind $IP
	handle /a {
		tailscale_auth
		respond "ok"
	}
	handle /b {
		tailscale_auth
		respond "ok"
	}
	handle /c {
		tailscale_auth
		respond "ok"
	}
}
CONF
caddy run --config Caddyfile &
sleep 2
hit() { for r in a b c; do curl -s -o /dev/null "http://$IP:28543/$r"; done; }
conns() { curl -s 'localhost:20299/debug/pprof/goroutine?debug=2' | grep -c 'persistConn).readLoop'; }
hit; conns
for i in 1 2 3 4 5; do
	caddy reload --force --address localhost:20299 --config Caddyfile
	hit; conns
done
kill %1

It prints 3, 6, 9, 12, 15, 18: one more connection per route per reload. --force is needed because Caddy skips a reload when the config is unchanged.

Measurements

Caddy v2.11.4, caddy-tailscale de41b249af4f, tailscale.com v1.102.2, on macOS with Tailscale 1.104.1. 20 tailscale_auth routes and 380 authenticated requests, 200 of them concurrent. Each cell is that Caddy process's established LocalAPI connections, read from netstat.

Build Before reloads After 5 reloads
de41b249af4f 280 380
+ #140 20 120
+ #146 20 120
+ shared client only 1 1

Proposed fix

Use one process-wide client for the system tailscaled path:

var systemLocalClient = new(local.Client)
	if ta.localclient == nil {
		// default to the shared client that will talk to local tailscaled
		ta.localclient = systemLocalClient
	}

The last table row is this change alone on de41b249af4f, with no receiver change or mutex. client() returns the same client even when Authenticate runs on a copy of Auth, so it stops the per-request leak as well. The tsnet path already uses its server's client and is unchanged, though I only tested the system tailscaled path.

I'm opening a PR with this change.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions