Skip to content
Open
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
9 changes: 7 additions & 2 deletions auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down
32 changes: 32 additions & 0 deletions auth_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}