cmd/k8s-operator,k8s-operator/reconciler: dedupe auth key reissuance

ProxyGroup, Recorder, and PeerRelay each carried a near-identical copy of
the auth key re-issuance state machine (in-flight tracking, per-parent rate
limiting, stale-device cleanup). A bug fix had to land in three places and
could silently drift.

Extract it into a shared tailscaled.Reissuer, alongside the other tailscaled
workload helpers (NewAuthKey, AuthKeyFromConfigSecret, DeviceIDFromStateSecret)
that the callers already use. It owns its own mutex, tracks in-flight reissues
per replica keyed by parent, and rate-limits re-issuance per parent; the three
reconcilers drive it via EnsureState/RemoveState/ShouldReissue. The device
deletion helper is shared too, so the reissue state machine and its tests now
live in one place.

Updates #20544

Signed-off-by: chaosinthecrd <[email protected]>
This commit is contained in:
chaosinthecrd authored and Tom Meadows committed 2026-08-12 14:57:28 +01:00
1 parent d200b3f18f
commit 0e93fdea5a
12 files changed
+613 -427

No files matched your search

+1 -1
View File
@@ -772,7 +772,7 @@ tailscale.com/cmd/k8s-operator dependencies: (generated by github.com/tailscale/
tailscale.com/k8s-operator/reconciler/proxyclass from tailscale.com/cmd/k8s-operator
tailscale.com/k8s-operator/reconciler/proxygrouppolicy from tailscale.com/cmd/k8s-operator
tailscale.com/k8s-operator/reconciler/tailnet from tailscale.com/cmd/k8s-operator
tailscale.com/k8s-operator/reconciler/tailscaled from tailscale.com/k8s-operator/reconciler/peerrelay
tailscale.com/k8s-operator/reconciler/tailscaled from tailscale.com/k8s-operator/reconciler/peerrelay+
tailscale.com/k8s-operator/sessionrecording from tailscale.com/k8s-operator/api-proxy
tailscale.com/k8s-operator/sessionrecording/spdy from tailscale.com/k8s-operator/sessionrecording
tailscale.com/k8s-operator/sessionrecording/tsrecorder from tailscale.com/k8s-operator/sessionrecording+
+9 -11
View File
@@ -20,7 +20,6 @@ import (
"github.com/go-logr/zapr"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"golang.org/x/time/rate"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
discoveryv1 "k8s.io/api/discovery/v1"
@@ -59,6 +58,7 @@ import (
"tailscale.com/k8s-operator/reconciler/proxyclass"
"tailscale.com/k8s-operator/reconciler/proxygrouppolicy"
"tailscale.com/k8s-operator/reconciler/tailnet"
"tailscale.com/k8s-operator/reconciler/tailscaled"
"tailscale.com/k8s-operator/tsclient"
"tailscale.com/kube/kubetypes"
"tailscale.com/tsnet"
@@ -704,14 +704,13 @@ func runReconcilers(opts reconcilerOpts) {
Watches(&rbacv1.Role{}, recorderFilter).
Watches(&rbacv1.RoleBinding{}, recorderFilter).
Complete(&RecorderReconciler{
recorder: eventRecorder,
tsNamespace: opts.tailscaleNamespace,
Client: mgr.GetClient(),
log: opts.log.Named("recorder-reconciler"),
clock: tstime.DefaultClock{},
clients: clients,
authKeyRateLimits: make(map[string]*rate.Limiter),
authKeyReissuing: make(map[string]bool),
recorder: eventRecorder,
tsNamespace: opts.tailscaleNamespace,
Client: mgr.GetClient(),
log: opts.log.Named("recorder-reconciler"),
clock: tstime.DefaultClock{},
clients: clients,
reissuer: tailscaled.NewReissuer(),
})
if err != nil {
startlog.Fatalf("could not create Recorder reconciler: %v", err)
@@ -777,8 +776,7 @@ func runReconcilers(opts reconcilerOpts) {
tsFirewallMode: opts.proxyFirewallMode,
defaultProxyClass: opts.defaultProxyClass,
loginServer: opts.tsServer.ControlURL,
authKeyRateLimits: make(map[string]*rate.Limiter),
authKeyReissuing: make(map[string]bool),
reissuer: tailscaled.NewReissuer(),
sharedACMEAccountKey: opts.sharedACMEAccountKey,
})
+20 -107
View File
@@ -15,12 +15,10 @@ import (
"sort"
"strings"
"sync"
"time"
dockerref "github.com/distribution/reference"
"go.uber.org/zap"
xslices "golang.org/x/exp/slices"
"golang.org/x/time/rate"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
@@ -32,11 +30,11 @@ import (
"k8s.io/client-go/tools/record"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"tailscale.com/client/tailscale/v2"
"tailscale.com/ipn"
tsoperator "tailscale.com/k8s-operator"
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
"tailscale.com/k8s-operator/reconciler/tailscaled"
"tailscale.com/k8s-operator/tsclient"
"tailscale.com/kube/egressservices"
"tailscale.com/kube/k8s-proxy/conf"
@@ -97,12 +95,12 @@ type ProxyGroupReconciler struct {
defaultProxyClass string
loginServer string
mu sync.Mutex // protects following
egressProxyGroups set.Slice[types.UID] // for egress proxygroups gauge
ingressProxyGroups set.Slice[types.UID] // for ingress proxygroups gauge
apiServerProxyGroups set.Slice[types.UID] // for kube-apiserver proxygroups gauge
authKeyRateLimits map[string]*rate.Limiter // per-ProxyGroup rate limiters for auth key re-issuance.
authKeyReissuing map[string]bool
reissuer *tailscaled.Reissuer
mu sync.Mutex // protects following
egressProxyGroups set.Slice[types.UID] // for egress proxygroups gauge
ingressProxyGroups set.Slice[types.UID] // for ingress proxygroups gauge
apiServerProxyGroups set.Slice[types.UID] // for kube-apiserver proxygroups gauge
// sharedACMEAccountKey is the operator-wide default for the
// shared-ACME-account feature. When true, every ProxyGroup uses the
@@ -671,7 +669,7 @@ func (r *ProxyGroupReconciler) cleanupDanglingResources(ctx context.Context, tsC
// Dangling resource, delete the config + state Secrets, as well as
// deleting the device from the tailnet.
if err := r.ensureDeviceDeleted(ctx, tsClient, m.tsID, logger); err != nil {
if err := tailscaled.EnsureDeviceDeleted(ctx, tsClient, logger, m.tsID); err != nil {
return err
}
if err := r.Delete(ctx, m.stateSecret); err != nil && !apierrors.IsNotFound(err) {
@@ -723,7 +721,7 @@ func (r *ProxyGroupReconciler) maybeCleanup(ctx context.Context, tsClient tsclie
}
for _, m := range metadata {
if err := r.ensureDeviceDeleted(ctx, tsClient, m.tsID, logger); err != nil {
if err := tailscaled.EnsureDeviceDeleted(ctx, tsClient, logger, m.tsID); err != nil {
return false, err
}
}
@@ -744,20 +742,6 @@ func (r *ProxyGroupReconciler) maybeCleanup(ctx context.Context, tsClient tsclie
return true, nil
}
func (r *ProxyGroupReconciler) ensureDeviceDeleted(ctx context.Context, tsClient tsclient.Client, id tailcfg.StableNodeID, logger *zap.SugaredLogger) error {
logger.Debugf("deleting device %s from control", string(id))
err := tsClient.Devices().Delete(ctx, string(id))
switch {
case tailscale.IsNotFound(err):
logger.Debugf("device %s not found, likely because it has already been deleted from control", string(id))
case err != nil:
return fmt.Errorf("error deleting device: %w", err)
}
logger.Debugf("device %s deleted from control", string(id))
return nil
}
func (r *ProxyGroupReconciler) ensureConfigSecretsCreated(
ctx context.Context,
tsClient tsclient.Client,
@@ -961,7 +945,13 @@ func (r *ProxyGroupReconciler) getAuthKey(ctx context.Context, tsClient tsclient
if !createAuthKey {
var err error
createAuthKey, err = r.shouldReissueAuthKey(ctx, tsClient, pg, stateSecret, cfgAuthKey)
createAuthKey, err = r.reissuer.ShouldReissue(ctx, tsClient, r.log, tailscaled.ReissueInput{
ParentName: pg.Name,
ReplicaName: stateSecret.Name,
Kind: tailscaled.KindProxyGroup,
StateSecret: stateSecret,
CfgAuthKey: cfgAuthKey,
})
if err != nil {
return nil, err
}
@@ -992,69 +982,6 @@ func (r *ProxyGroupReconciler) getAuthKey(ctx context.Context, tsClient tsclient
return authKey, nil
}
// shouldReissueAuthKey returns true if the proxy needs a new auth key. It
// tracks in-flight reissues via authKeyReissuing to avoid duplicate API calls
// across reconciles.
func (r *ProxyGroupReconciler) shouldReissueAuthKey(ctx context.Context, tsClient tsclient.Client, pg *tsapi.ProxyGroup, stateSecret *corev1.Secret, cfgAuthKey *string) (shouldReissue bool, err error) {
r.mu.Lock()
reissuing := r.authKeyReissuing[stateSecret.Name]
r.mu.Unlock()
if reissuing {
// Check if reissue is complete by seeing if request was cleared
_, requestStillPresent := stateSecret.Data[kubetypes.KeyReissueAuthkey]
if !requestStillPresent {
// Containerboot cleared the request, reissue is complete
r.mu.Lock()
r.authKeyReissuing[stateSecret.Name] = false
r.mu.Unlock()
r.log.Debugf("auth key reissue completed for %q", stateSecret.Name)
return false, nil
}
// Reissue still in-flight; waiting for containerboot to pick up new key
r.log.Debugf("auth key already in process of re-issuance, waiting for secret to be updated")
return false, nil
}
defer func() {
r.mu.Lock()
r.authKeyReissuing[stateSecret.Name] = shouldReissue
r.mu.Unlock()
}()
brokenAuthkey, ok := stateSecret.Data[kubetypes.KeyReissueAuthkey]
if !ok {
// reissue hasn't been requested since the key in the secret hasn't been populated
return false, nil
}
empty := cfgAuthKey == nil || *cfgAuthKey == ""
broken := cfgAuthKey != nil && *cfgAuthKey == string(brokenAuthkey)
// A new key has been written but the proxy hasn't picked it up yet.
if !empty && !broken {
return false, nil
}
lim := r.authKeyRateLimits[pg.Name]
if !lim.Allow() {
r.log.Debugf("auth key re-issuance rate limit exceeded, limit: %.2f, burst: %d, tokens: %.2f",
lim.Limit(), lim.Burst(), lim.Tokens())
return false, fmt.Errorf("auth key re-issuance rate limit exceeded for ProxyGroup %q, will retry with backoff", pg.Name)
}
r.log.Infof("Proxy failing to auth; attempting cleanup and new key")
if tsID := stateSecret.Data[kubetypes.KeyDeviceID]; len(tsID) > 0 {
id := tailcfg.StableNodeID(tsID)
if err = r.ensureDeviceDeleted(ctx, tsClient, id, r.log); err != nil {
return false, err
}
}
return true, nil
}
type FindStaticEndpointErr struct {
msg string
}
@@ -1175,7 +1102,7 @@ func getStaticEndpointAddress(a *corev1.NodeAddress, port uint16) *netip.AddrPor
}
// ensureStateAddedForProxyGroup ensures the gauge metric for the ProxyGroup resource is updated when the ProxyGroup
// is created, and initialises per-ProxyGroup rate limits on re-issuing auth keys. r.mu must be held.
// is created, and initialises per-ProxyGroup auth key re-issuance state. r.mu must be held.
func (r *ProxyGroupReconciler) ensureStateAddedForProxyGroup(pg *tsapi.ProxyGroup) {
switch pg.Spec.Type {
case tsapi.ProxyGroupTypeEgress:
@@ -1189,22 +1116,11 @@ func (r *ProxyGroupReconciler) ensureStateAddedForProxyGroup(pg *tsapi.ProxyGrou
gaugeIngressProxyGroupResources.Set(int64(r.ingressProxyGroups.Len()))
gaugeAPIServerProxyGroupResources.Set(int64(r.apiServerProxyGroups.Len()))
if _, ok := r.authKeyRateLimits[pg.Name]; !ok {
// Allow every replica to have its auth key re-issued quickly the first
// time, but with an overall limit of 1 every 30s after a burst.
r.authKeyRateLimits[pg.Name] = rate.NewLimiter(rate.Every(30*time.Second), int(pgReplicas(pg)))
}
for i := range pgReplicas(pg) {
rep := pgStateSecretName(pg.Name, i)
if _, ok := r.authKeyReissuing[rep]; !ok {
r.authKeyReissuing[rep] = false
}
}
r.reissuer.EnsureState(pg.Name, int(pgReplicas(pg)))
}
// ensureStateRemovedForProxyGroup ensures the gauge metric for the ProxyGroup resource type is updated when the
// ProxyGroup is deleted, and deletes the per-ProxyGroup rate limiter to free memory. r.mu must be held.
// ProxyGroup is deleted, and drops the per-ProxyGroup auth key re-issuance state to free memory. r.mu must be held.
func (r *ProxyGroupReconciler) ensureStateRemovedForProxyGroup(pg *tsapi.ProxyGroup) {
switch pg.Spec.Type {
case tsapi.ProxyGroupTypeEgress:
@@ -1217,10 +1133,7 @@ func (r *ProxyGroupReconciler) ensureStateRemovedForProxyGroup(pg *tsapi.ProxyGr
gaugeEgressProxyGroupResources.Set(int64(r.egressProxyGroups.Len()))
gaugeIngressProxyGroupResources.Set(int64(r.ingressProxyGroups.Len()))
gaugeAPIServerProxyGroupResources.Set(int64(r.apiServerProxyGroups.Len()))
delete(r.authKeyRateLimits, pg.Name)
for i := range pgReplicas(pg) {
delete(r.authKeyReissuing, pgStateSecretName(pg.Name, i))
}
r.reissuer.RemoveState(pg.Name)
}
func pgTailscaledConfig(pg *tsapi.ProxyGroup, loginServer string, pc *tsapi.ProxyClass, idx int32, authKey *string, staticEndpoints []netip.AddrPort, oldAdvertiseServices []string) (tailscaledConfigs, error) {
+49 -82
View File
@@ -6,19 +6,16 @@
package main
import (
"context"
"encoding/json"
"fmt"
"net/netip"
"reflect"
"slices"
"strings"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"go.uber.org/zap"
"golang.org/x/time/rate"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
@@ -36,6 +33,7 @@ import (
tsoperator "tailscale.com/k8s-operator"
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
"tailscale.com/k8s-operator/reconciler/proxyclass"
"tailscale.com/k8s-operator/reconciler/tailscaled"
"tailscale.com/k8s-operator/tsclient"
"tailscale.com/kube/k8s-proxy/conf"
"tailscale.com/kube/kubetypes"
@@ -642,12 +640,11 @@ func TestProxyGroupWithStaticEndpoints(t *testing.T) {
tsFirewallMode: "auto",
defaultProxyClass: "default-pc",
Client: fc,
clients: tsclient.NewProvider(tsClient),
recorder: fr,
clock: cl,
authKeyRateLimits: make(map[string]*rate.Limiter),
authKeyReissuing: make(map[string]bool),
Client: fc,
clients: tsclient.NewProvider(tsClient),
recorder: fr,
clock: cl,
reissuer: tailscaled.NewReissuer(),
}
for i, r := range tt.reconciles {
@@ -787,13 +784,12 @@ func TestProxyGroupWithStaticEndpoints(t *testing.T) {
tsFirewallMode: "auto",
defaultProxyClass: "default-pc",
Client: fc,
clients: tsclient.NewProvider(tsClient),
recorder: fr,
log: zl.Sugar().With("TestName", tt.name).With("Reconcile", "cleanup"),
clock: cl,
authKeyRateLimits: make(map[string]*rate.Limiter),
authKeyReissuing: make(map[string]bool),
Client: fc,
clients: tsclient.NewProvider(tsClient),
recorder: fr,
log: zl.Sugar().With("TestName", tt.name).With("Reconcile", "cleanup"),
clock: cl,
reissuer: tailscaled.NewReissuer(),
}
if err := fc.Delete(t.Context(), pg); err != nil {
@@ -934,13 +930,12 @@ func TestProxyGroup(t *testing.T) {
tsFirewallMode: "auto",
defaultProxyClass: "default-pc",
Client: fc,
clients: tsclient.NewProvider(tsClient),
recorder: fr,
log: zl.Sugar(),
clock: cl,
authKeyRateLimits: make(map[string]*rate.Limiter),
authKeyReissuing: make(map[string]bool),
Client: fc,
clients: tsclient.NewProvider(tsClient),
recorder: fr,
log: zl.Sugar(),
clock: cl,
reissuer: tailscaled.NewReissuer(),
}
crd := &apiextensionsv1.CustomResourceDefinition{ObjectMeta: metav1.ObjectMeta{Name: serviceMonitorCRD}}
@@ -1143,8 +1138,7 @@ func TestProxyGroupTypes(t *testing.T) {
log: zl.Sugar(),
clients: tsclient.NewProvider(&fakeTSClient{}),
clock: tstest.NewClock(tstest.ClockOpts{}),
authKeyRateLimits: make(map[string]*rate.Limiter),
authKeyReissuing: make(map[string]bool),
reissuer: tailscaled.NewReissuer(),
sharedACMEAccountKey: true,
}
@@ -1475,14 +1469,13 @@ func TestKubeAPIServerStatusConditionFlow(t *testing.T) {
WithStatusSubresource(pg).
Build()
r := &ProxyGroupReconciler{
tsNamespace: tsNamespace,
tsProxyImage: testProxyImage,
Client: fc,
log: zap.Must(zap.NewDevelopment()).Sugar(),
clients: tsclient.NewProvider(&fakeTSClient{}),
clock: tstest.NewClock(tstest.ClockOpts{}),
authKeyRateLimits: make(map[string]*rate.Limiter),
authKeyReissuing: make(map[string]bool),
tsNamespace: tsNamespace,
tsProxyImage: testProxyImage,
Client: fc,
log: zap.Must(zap.NewDevelopment()).Sugar(),
clients: tsclient.NewProvider(&fakeTSClient{}),
clock: tstest.NewClock(tstest.ClockOpts{}),
reissuer: tailscaled.NewReissuer(),
}
expectReconciled(t, r, "", pg.Name)
@@ -1530,14 +1523,13 @@ func TestKubeAPIServerType_DoesNotOverwriteServicesConfig(t *testing.T) {
Build()
reconciler := &ProxyGroupReconciler{
tsNamespace: tsNamespace,
tsProxyImage: testProxyImage,
Client: fc,
log: zap.Must(zap.NewDevelopment()).Sugar(),
clients: tsclient.NewProvider(&fakeTSClient{}),
clock: tstest.NewClock(tstest.ClockOpts{}),
authKeyRateLimits: make(map[string]*rate.Limiter),
authKeyReissuing: make(map[string]bool),
tsNamespace: tsNamespace,
tsProxyImage: testProxyImage,
Client: fc,
log: zap.Must(zap.NewDevelopment()).Sugar(),
clients: tsclient.NewProvider(&fakeTSClient{}),
clock: tstest.NewClock(tstest.ClockOpts{}),
reissuer: tailscaled.NewReissuer(),
}
pg := &tsapi.ProxyGroup{
@@ -1617,14 +1609,13 @@ func TestIngressAdvertiseServicesConfigPreserved(t *testing.T) {
WithStatusSubresource(&tsapi.ProxyGroup{}).
Build()
reconciler := &ProxyGroupReconciler{
tsNamespace: tsNamespace,
tsProxyImage: testProxyImage,
Client: fc,
log: zap.Must(zap.NewDevelopment()).Sugar(),
clients: tsclient.NewProvider(&fakeTSClient{}),
clock: tstest.NewClock(tstest.ClockOpts{}),
authKeyRateLimits: make(map[string]*rate.Limiter),
authKeyReissuing: make(map[string]bool),
tsNamespace: tsNamespace,
tsProxyImage: testProxyImage,
Client: fc,
log: zap.Must(zap.NewDevelopment()).Sugar(),
clients: tsclient.NewProvider(&fakeTSClient{}),
clock: tstest.NewClock(tstest.ClockOpts{}),
reissuer: tailscaled.NewReissuer(),
}
existingServices := []string{"svc1", "svc2"}
@@ -1890,13 +1881,12 @@ func TestProxyGroupGetAuthKey(t *testing.T) {
defaultTags: []string{"tag:test-tag"},
tsFirewallMode: "auto",
Client: fc,
clients: tsclient.NewProvider(tsClient),
recorder: fr,
log: zl.Sugar(),
clock: cl,
authKeyRateLimits: make(map[string]*rate.Limiter),
authKeyReissuing: make(map[string]bool),
Client: fc,
clients: tsclient.NewProvider(tsClient),
recorder: fr,
log: zl.Sugar(),
clock: cl,
reissuer: tailscaled.NewReissuer(),
}
reconciler.ensureStateAddedForProxyGroup(pg)
@@ -2006,36 +1996,14 @@ func TestProxyGroupGetAuthKey(t *testing.T) {
}
// Use the device deletion as a proxy for the fact the new auth key
// was due to a reissue.
// was due to a reissue. Rate-limit exhaustion is covered directly in
// the shared tailscaled.Reissuer test.
switch {
case tc.expectReissue && len(tsClient.deleted) != 1:
t.Errorf("expected 1 deleted device, got %v", tsClient.deleted)
case !tc.expectReissue && len(tsClient.deleted) != 0:
t.Errorf("expected no deleted devices, got %v", tsClient.deleted)
}
if tc.expectReissue {
// Trigger the rate limit in a tight loop. Up to 100 iterations
// to allow for CI that is extremely slow, but should happen on
// first try for any reasonable machine.
stateSecretName := pgStateSecretName(pg.Name, 0)
for range 100 {
//NOTE: (ChaosInTheCRD) we added some protection here to avoid
// trying to reissue when already reissung. This overrides it.
reconciler.mu.Lock()
reconciler.authKeyReissuing[stateSecretName] = false
reconciler.mu.Unlock()
_, err := reconciler.getAuthKey(context.Background(), tsClient, pg, cfgSecret, 0,
reconciler.log.With("TestName", t.Name()))
if err != nil {
if !strings.Contains(err.Error(), "rate limit exceeded") {
t.Fatalf("unexpected error getting auth key: %v", err)
}
return // Expected rate limit error.
}
}
t.Fatal("expected rate limit error, but got none")
}
})
}
}
@@ -2291,8 +2259,7 @@ func TestProxyGroupLetsEncryptStaging(t *testing.T) {
clients: tsclient.NewProvider(&fakeTSClient{}),
log: zl.Sugar(),
clock: cl,
authKeyRateLimits: make(map[string]*rate.Limiter),
authKeyReissuing: make(map[string]bool),
reissuer: tailscaled.NewReissuer(),
}
expectReconciled(t, reconciler, "", pg.Name)
+27 -105
View File
@@ -14,11 +14,9 @@ import (
"strconv"
"strings"
"sync"
"time"
"go.uber.org/zap"
xslices "golang.org/x/exp/slices"
"golang.org/x/time/rate"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
@@ -35,6 +33,7 @@ import (
tsoperator "tailscale.com/k8s-operator"
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
"tailscale.com/k8s-operator/reconciler/tailscaled"
"tailscale.com/k8s-operator/tsclient"
"tailscale.com/kube/kubetypes"
"tailscale.com/tailcfg"
@@ -51,6 +50,9 @@ const (
reasonRecorderTailnetUnavailable = "RecorderTailnetUnavailable"
currentProfileKey = "_current-profile"
// authKeySecretKey is the data key under which a Recorder replica's auth key is stored in its auth Secret.
authKeySecretKey = "authkey"
)
var gaugeRecorderResources = clientmetric.NewGauge(kubetypes.MetricRecorderCount)
@@ -59,15 +61,14 @@ var gaugeRecorderResources = clientmetric.NewGauge(kubetypes.MetricRecorderCount
// Recorder CRs.
type RecorderReconciler struct {
client.Client
log *zap.SugaredLogger
recorder record.EventRecorder
clock tstime.Clock
clients ClientProvider
tsNamespace string
authKeyRateLimits map[string]*rate.Limiter // per-Recorder rate limiters for auth key re-issuance.
authKeyReissuing map[string]bool
mu sync.Mutex // protects following
recorders set.Slice[types.UID] // for recorders gauge
log *zap.SugaredLogger
recorder record.EventRecorder
clock tstime.Clock
clients ClientProvider
tsNamespace string
reissuer *tailscaled.Reissuer
mu sync.Mutex // protects following
recorders set.Slice[types.UID] // for recorders gauge
}
func (r *RecorderReconciler) logger(name string) *zap.SugaredLogger {
@@ -175,16 +176,8 @@ func (r *RecorderReconciler) maybeProvision(ctx context.Context, tsClient tsclie
r.mu.Lock()
r.recorders.Add(tsr.UID)
gaugeRecorderResources.Set(int64(r.recorders.Len()))
if _, ok := r.authKeyRateLimits[tsr.Name]; !ok {
r.authKeyRateLimits[tsr.Name] = rate.NewLimiter(rate.Every(30*time.Second), int(replicas))
}
for replica := range replicas {
name := fmt.Sprintf("%s-%d", tsr.Name, replica)
if _, ok := r.authKeyReissuing[name]; !ok {
r.authKeyReissuing[name] = false
}
}
r.mu.Unlock()
r.reissuer.EnsureState(tsr.Name, int(replicas))
if err := r.ensureAuthSecretsCreated(ctx, tsClient, tsr); err != nil {
return fmt.Errorf("error creating secrets: %w", err)
@@ -435,11 +428,8 @@ func (r *RecorderReconciler) maybeCleanup(ctx context.Context, tsr *tsapi.Record
r.mu.Lock()
r.recorders.Remove(tsr.UID)
gaugeRecorderResources.Set(int64(r.recorders.Len()))
delete(r.authKeyRateLimits, tsr.Name)
for replica := range replicas {
delete(r.authKeyReissuing, fmt.Sprintf("%s-%d", tsr.Name, replica))
}
r.mu.Unlock()
r.reissuer.RemoveState(tsr.Name)
return true, nil
}
@@ -467,7 +457,18 @@ func (r *RecorderReconciler) ensureAuthSecretsCreated(ctx context.Context, tsCli
err := r.Get(ctx, key, existingSecret)
switch {
case err == nil:
reissue, err := r.shouldReissueAuthKey(ctx, tsClient, tsr, replica, existingSecret)
stateSecret, err := r.getStateSecret(ctx, tsr.Name, replica)
if err != nil {
return fmt.Errorf("error getting state Secret for replica %d: %w", replica, err)
}
cfgAuthKey := string(existingSecret.Data[authKeySecretKey])
reissue, err := r.reissuer.ShouldReissue(ctx, tsClient, r.log, tailscaled.ReissueInput{
ParentName: tsr.Name,
ReplicaName: fmt.Sprintf("%s-%d", tsr.Name, replica),
Kind: tailscaled.KindRecorder,
StateSecret: stateSecret,
CfgAuthKey: &cfgAuthKey,
})
if err != nil {
return fmt.Errorf("error checking auth key reissue for replica %d: %w", replica, err)
}
@@ -479,7 +480,7 @@ func (r *RecorderReconciler) ensureAuthSecretsCreated(ctx context.Context, tsCli
if err != nil {
return err
}
existingSecret.Data["authkey"] = []byte(authKey)
existingSecret.Data[authKeySecretKey] = []byte(authKey)
if err = r.Update(ctx, existingSecret); err != nil {
return err
}
@@ -500,85 +501,6 @@ func (r *RecorderReconciler) ensureAuthSecretsCreated(ctx context.Context, tsCli
return nil
}
// shouldReissueAuthKey returns true if the proxy needs a new auth key. It
// tracks in-flight reissues via authKeyReissuing to avoid duplicate API calls
// across reconciles.
func (r *RecorderReconciler) shouldReissueAuthKey(ctx context.Context, tsClient tsclient.Client, tsr *tsapi.Recorder, replica int32, authSecret *corev1.Secret) (shouldReissue bool, err error) {
stateSecret, err := r.getStateSecret(ctx, tsr.Name, replica)
if err != nil || stateSecret == nil {
return false, err
}
stateSecretName := fmt.Sprintf("%s-%d", tsr.Name, replica)
r.mu.Lock()
reissuing := r.authKeyReissuing[stateSecretName]
r.mu.Unlock()
if reissuing {
_, requestStillPresent := stateSecret.Data[kubetypes.KeyReissueAuthkey]
if !requestStillPresent {
r.mu.Lock()
r.authKeyReissuing[stateSecretName] = false
r.mu.Unlock()
r.log.Debugf("auth key reissue completed for %q", stateSecretName)
return false, nil
}
r.log.Debugf("auth key already in process of re-issuance for %q, waiting", stateSecretName)
return false, nil
}
defer func() {
r.mu.Lock()
r.authKeyReissuing[stateSecretName] = shouldReissue
r.mu.Unlock()
}()
brokenAuthkey, ok := stateSecret.Data[kubetypes.KeyReissueAuthkey]
if !ok {
return false, nil
}
cfgAuthKey := string(authSecret.Data["authkey"])
empty := cfgAuthKey == ""
broken := cfgAuthKey == string(brokenAuthkey)
if !empty && !broken {
return false, nil
}
lim := r.authKeyRateLimits[tsr.Name]
if !lim.Allow() {
r.log.Debugf("auth key re-issuance rate limit exceeded, limit: %.2f, burst: %d, tokens: %.2f",
lim.Limit(), lim.Burst(), lim.Tokens())
return false, fmt.Errorf("auth key re-issuance rate limit exceeded for Recorder %q, will retry with backoff", tsr.Name)
}
r.log.Infof("Recorder replica %s failing to auth; attempting cleanup and new key", stateSecretName)
if tsID := stateSecret.Data[kubetypes.KeyDeviceID]; len(tsID) > 0 {
id := tailcfg.StableNodeID(tsID)
if err := r.ensureDeviceDeleted(ctx, tsClient, id, r.log); err != nil {
return false, err
}
}
return true, nil
}
func (r *RecorderReconciler) ensureDeviceDeleted(ctx context.Context, tsClient tsclient.Client, id tailcfg.StableNodeID, logger *zap.SugaredLogger) error {
logger.Debugf("deleting device %s from control", string(id))
err := tsClient.Devices().Delete(ctx, string(id))
switch {
case tailscale.IsNotFound(err):
logger.Debugf("device %s not found, likely because it has already been deleted from control", string(id))
case err != nil:
return fmt.Errorf("error deleting device: %w", err)
default:
logger.Debugf("device %s deleted from control", string(id))
}
return nil
}
func (r *RecorderReconciler) validate(ctx context.Context, tsr *tsapi.Recorder) error {
if !tsr.Spec.EnableUI && tsr.Spec.Storage.S3 == nil {
return errors.New("must either enable UI or use S3 storage to ensure recordings are accessible")
+2 -2
View File
@@ -116,7 +116,7 @@ func tsrStatefulSet(tsr *tsapi.Recorder, namespace string, loginServer string) *
VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
SecretName: fmt.Sprintf("%s-auth-%d", tsr.Name, replica),
Items: []corev1.KeyToPath{{Key: "authkey", Path: "authkey"}},
Items: []corev1.KeyToPath{{Key: authKeySecretKey, Path: authKeySecretKey}},
},
},
})
@@ -223,7 +223,7 @@ func tsrAuthSecret(tsr *tsapi.Recorder, namespace string, authKey string, replic
OwnerReferences: tsrOwnerReference(tsr),
},
StringData: map[string]string{
"authkey": authKey,
authKeySecretKey: authKey,
},
}
}
+8 -9
View File
@@ -14,7 +14,6 @@ import (
"github.com/google/go-cmp/cmp"
"go.uber.org/zap"
"golang.org/x/time/rate"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
@@ -26,6 +25,7 @@ import (
tsoperator "tailscale.com/k8s-operator"
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
"tailscale.com/k8s-operator/reconciler/tailscaled"
"tailscale.com/k8s-operator/tsclient"
"tailscale.com/tstest"
)
@@ -56,14 +56,13 @@ func TestRecorder(t *testing.T) {
fr := record.NewFakeRecorder(2)
cl := tstest.NewClock(tstest.ClockOpts{})
reconciler := &RecorderReconciler{
tsNamespace: tsNamespace,
Client: fc,
clients: tsclient.NewProvider(tsClient),
recorder: fr,
log: zl.Sugar(),
clock: cl,
authKeyRateLimits: make(map[string]*rate.Limiter),
authKeyReissuing: make(map[string]bool),
tsNamespace: tsNamespace,
Client: fc,
clients: tsclient.NewProvider(tsClient),
recorder: fr,
log: zl.Sugar(),
clock: cl,
reissuer: tailscaled.NewReissuer(),
}
t.Run("invalid_spec_gives_an_error_condition", func(t *testing.T) {
+7 -77
View File
@@ -13,13 +13,9 @@ import (
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/types"
tailscaleclient "tailscale.com/client/tailscale/v2"
tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
"tailscale.com/k8s-operator/reconciler/tailscaled"
"tailscale.com/k8s-operator/tsclient"
"tailscale.com/kube/kubetypes"
"tailscale.com/tailcfg"
)
func (r *Reconciler) peerRelayTags(pr *tsapi.PeerRelay) []string {
@@ -60,7 +56,13 @@ func (r *Reconciler) getAuthKey(ctx context.Context, tsClient tsclient.Client, p
}
if !createAuthKey {
createAuthKey, err = r.shouldReissueAuthKey(ctx, tsClient, pr, idx, stateSecret, cfgAuthKey)
createAuthKey, err = r.reissuer.ShouldReissue(ctx, tsClient, r.logger, tailscaled.ReissueInput{
ParentName: pr.Name,
ReplicaName: replicaName(pr.Name, idx),
Kind: tailscaled.KindPeerRelay,
StateSecret: stateSecret,
CfgAuthKey: cfgAuthKey,
})
if err != nil {
return nil, err
}
@@ -84,75 +86,3 @@ func (r *Reconciler) getAuthKey(ctx context.Context, tsClient tsclient.Client, p
return authKey, nil
}
// shouldReissueAuthKey returns true if the replica needs a new auth key. It tracks in-flight
// reissues via authKeyReissuing to avoid duplicate API calls across reconciles.
func (r *Reconciler) shouldReissueAuthKey(ctx context.Context, tsClient tsclient.Client, pr *tsapi.PeerRelay, idx int32, stateSecret *corev1.Secret, cfgAuthKey *string) (shouldReissue bool, err error) {
name := replicaName(pr.Name, idx)
r.mu.Lock()
reissuing := r.authKeyReissuing[name]
r.mu.Unlock()
if reissuing {
_, requestStillPresent := stateSecret.Data[kubetypes.KeyReissueAuthkey]
if !requestStillPresent {
r.mu.Lock()
r.authKeyReissuing[name] = false
r.mu.Unlock()
r.logger.Debugf("auth key reissue completed for %q", name)
return false, nil
}
r.logger.Debugf("auth key already in process of re-issuance for %q, waiting", name)
return false, nil
}
defer func() {
r.mu.Lock()
r.authKeyReissuing[name] = shouldReissue
r.mu.Unlock()
}()
brokenAuthkey, ok := stateSecret.Data[kubetypes.KeyReissueAuthkey]
if !ok {
return false, nil
}
empty := cfgAuthKey == nil || *cfgAuthKey == ""
broken := cfgAuthKey != nil && *cfgAuthKey == string(brokenAuthkey)
// A new key has been written but the replica hasn't picked it up yet.
if !empty && !broken {
return false, nil
}
lim := r.authKeyRateLimits[pr.Name]
if !lim.Allow() {
r.logger.Debugf("auth key re-issuance rate limit exceeded, limit: %.2f, burst: %d, tokens: %.2f",
lim.Limit(), lim.Burst(), lim.Tokens())
return false, fmt.Errorf("auth key re-issuance rate limit exceeded for PeerRelay %q, will retry with backoff", pr.Name)
}
r.logger.Infof("PeerRelay replica %s failing to auth; attempting cleanup and new key", name)
if tsID := stateSecret.Data[kubetypes.KeyDeviceID]; len(tsID) > 0 {
if err = r.ensureDeviceDeleted(ctx, tsClient, tailcfg.StableNodeID(tsID)); err != nil {
return false, err
}
}
return true, nil
}
func (r *Reconciler) ensureDeviceDeleted(ctx context.Context, tsClient tsclient.Client, id tailcfg.StableNodeID) error {
r.logger.Debugf("deleting device %s from control", string(id))
err := tsClient.Devices().Delete(ctx, string(id))
switch {
case tailscaleclient.IsNotFound(err):
r.logger.Debugf("device %s not found, likely because it has already been deleted from control", string(id))
case err != nil:
return fmt.Errorf("error deleting device: %w", err)
default:
r.logger.Debugf("device %s deleted from control", string(id))
}
return nil
}
+4 -33
View File
@@ -17,11 +17,9 @@ import (
"net/netip"
"reflect"
"slices"
"sync"
"time"
"go.uber.org/zap"
"golang.org/x/time/rate"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
@@ -55,12 +53,9 @@ type (
resolver func(ctx context.Context, network, host string) ([]netip.Addr, error)
logger *zap.SugaredLogger
clock tstime.Clock
reissuer *tailscaled.Reissuer
tracker *reconciler.ResourceTracker
mu sync.Mutex // protects following
authKeyRateLimits map[string]*rate.Limiter // per-PeerRelay rate limiters for auth key re-issuance.
authKeyReissuing map[string]bool
}
// The ReconcilerOptions type contains configuration values for the Reconciler.
@@ -132,8 +127,7 @@ func NewReconciler(options ReconcilerOptions) *Reconciler {
logger: options.Logger.Named(reconcilerName),
clock: clock,
tracker: reconciler.NewResourceTracker(gaugePeerRelayResources),
authKeyRateLimits: make(map[string]*rate.Limiter),
authKeyReissuing: make(map[string]bool),
reissuer: tailscaled.NewReissuer(),
}
}
@@ -227,19 +221,7 @@ func (r *Reconciler) createOrUpdate(ctx context.Context, logger *zap.SugaredLogg
replicas = *pr.Spec.Replicas
}
r.mu.Lock()
if _, ok := r.authKeyRateLimits[pr.Name]; !ok {
// Allow every replica to have its auth key re-issued quickly the first
// time, but with an overall limit of 1 every 30s after a burst.
r.authKeyRateLimits[pr.Name] = rate.NewLimiter(rate.Every(30*time.Second), int(replicas))
}
for i := int32(0); i < replicas; i++ {
name := replicaName(pr.Name, i)
if _, ok := r.authKeyReissuing[name]; !ok {
r.authKeyReissuing[name] = false
}
}
r.mu.Unlock()
r.reissuer.EnsureState(pr.Name, int(replicas))
// Belt-and-braces: CEL on the CRD enforces this at admission, but we also validate here to guard against older
// clusters without CEL, resources created before the CRD schema landed, or hand-edited status paths. If the user
@@ -417,18 +399,7 @@ func (r *Reconciler) delete(ctx context.Context, logger *zap.SugaredLogger, pr *
}
r.tracker.Remove(pr.UID)
replicas := int32(1)
if pr.Spec.Replicas != nil {
replicas = *pr.Spec.Replicas
}
r.mu.Lock()
delete(r.authKeyRateLimits, pr.Name)
for i := int32(0); i < replicas; i++ {
delete(r.authKeyReissuing, replicaName(pr.Name, i))
}
r.mu.Unlock()
r.reissuer.RemoveState(pr.Name)
return reconcile.Result{}, nil
}
@@ -10,12 +10,14 @@ import (
"encoding/json"
"fmt"
"go.uber.org/zap"
corev1 "k8s.io/api/core/v1"
tailscaleclient "tailscale.com/client/tailscale/v2"
"tailscale.com/ipn"
"tailscale.com/k8s-operator/tsclient"
"tailscale.com/tailcfg"
)
// ClientProvider returns a Tailscale API client for the given tailnet name. A blank name should return the
@@ -39,6 +41,22 @@ func NewAuthKey(ctx context.Context, client tsclient.Client, tags []string) (str
return key.Key, nil
}
// EnsureDeviceDeleted deletes the tailnet device with the given stable node ID from control, treating a
// not-found response as success (the device was already gone).
func EnsureDeviceDeleted(ctx context.Context, client tsclient.Client, logger *zap.SugaredLogger, id tailcfg.StableNodeID) error {
logger.Debugf("deleting device %s from control", string(id))
err := client.Devices().Delete(ctx, string(id))
switch {
case tailscaleclient.IsNotFound(err):
logger.Debugf("device %s not found, likely because it has already been deleted from control", string(id))
case err != nil:
return fmt.Errorf("error deleting device: %w", err)
default:
logger.Debugf("device %s deleted from control", string(id))
}
return nil
}
// AuthKeyFromConfigSecret returns the auth key embedded in the tailscaled config file stored in secret, or nil if
// none is set. secret is expected to be a Secret produced by NewConfigSecret. The Data map may contain multiple
// versioned config files (cap-<n>.hujson); the first one to parse successfully and yield a non-empty AuthKey wins.
@@ -0,0 +1,179 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
//go:build !plan9
package tailscaled
import (
"context"
"fmt"
"sync"
"time"
"go.uber.org/zap"
"golang.org/x/time/rate"
corev1 "k8s.io/api/core/v1"
"tailscale.com/k8s-operator/tsclient"
"tailscale.com/kube/kubetypes"
"tailscale.com/tailcfg"
"tailscale.com/util/set"
)
// Reissuer manages auth key re-issuance for a CRD reconciler that runs one tailscaled replica per Secret. It
// tracks in-flight reissues per replica so duplicate reconciles don't mint duplicate keys, and rate limits
// re-issuance per parent resource so a replica that can never auth doesn't hammer the control plane.
type Reissuer struct {
mu sync.Mutex // protects following
reissuing map[string]set.Set[string] // parent name -> replica names with a reissue in flight
rateLimits map[string]*rate.Limiter // parent name -> re-issuance rate limiter
}
// NewReissuer returns a ready-to-use Reissuer.
func NewReissuer() *Reissuer {
return &Reissuer{
reissuing: make(map[string]set.Set[string]),
rateLimits: make(map[string]*rate.Limiter),
}
}
// EnsureState sets up the per-parent rate limiter, sized so every replica can have its key re-issued quickly the
// first time via the burst, then an overall limit of one every 30s. It is idempotent and safe to call on every
// reconcile. ShouldReissue also creates a limiter on demand (with a burst of 1) so it never panics if EnsureState
// hasn't run; EnsureState just fixes the burst to the replica count.
func (r *Reissuer) EnsureState(parentName string, replicas int) {
r.mu.Lock()
defer r.mu.Unlock()
r.limiterLocked(parentName, max(replicas, 1))
}
// RemoveState drops all per-parent state (rate limiter and every replica's in-flight marker) when the parent
// resource is deleted. It clears markers for all replicas the parent ever had, not just its current count, so
// replicas removed by an earlier scale-down don't strand entries.
func (r *Reissuer) RemoveState(parentName string) {
r.mu.Lock()
defer r.mu.Unlock()
delete(r.rateLimits, parentName)
delete(r.reissuing, parentName)
}
// limiterLocked returns the rate limiter for parentName, creating one with the given burst if absent. r.mu must be
// held. The burst only applies the first time a limiter is created for a parent; EnsureState seeds it with the
// replica count, but ShouldReissue can also reach this before EnsureState has run and passes a burst of 1.
func (r *Reissuer) limiterLocked(parentName string, burst int) *rate.Limiter {
lim, ok := r.rateLimits[parentName]
if !ok {
lim = rate.NewLimiter(rate.Every(30*time.Second), burst)
r.rateLimits[parentName] = lim
}
return lim
}
// setReissuingLocked records or clears the in-flight reissue marker for a replica. r.mu must be held. The
// per-parent set is created on first use and dropped once its last marker is cleared, so an idle parent holds no
// entry.
func (r *Reissuer) setReissuingLocked(parentName, replicaName string, reissuing bool) {
if reissuing {
s := r.reissuing[parentName]
if s == nil {
s = make(set.Set[string])
r.reissuing[parentName] = s
}
s.Add(replicaName)
return
}
s := r.reissuing[parentName]
s.Delete(replicaName)
if s.Len() == 0 {
delete(r.reissuing, parentName)
}
}
// Kind names of the CRDs that use a Reissuer, used only in its log and error messages.
const (
KindProxyGroup = "ProxyGroup"
KindRecorder = "Recorder"
KindPeerRelay = "PeerRelay"
)
// ReissueInput describes a single replica's re-issuance check.
type ReissueInput struct {
// ParentName is the owning CRD's name; it keys the rate limiter and appears in the rate-limit error.
ParentName string
// ReplicaName keys the in-flight marker and appears in log lines. Callers use the replica's state Secret name.
ReplicaName string
// Kind is the owning CRD kind, used only in log lines.
Kind string
// StateSecret is the replica's tailscaled state Secret. It may be nil or empty if the replica hasn't started
// yet.
StateSecret *corev1.Secret
// CfgAuthKey is the auth key currently stored in the replica's config, or nil if none. The caller extracts it
// from wherever it stores the key (a config Secret, a plain auth Secret, etc.).
CfgAuthKey *string
}
// ShouldReissue reports whether the replica needs a fresh auth key. It tracks in-flight reissues via an internal
// marker to avoid duplicate API calls across reconciles: once it returns true, subsequent calls return false until
// containerboot clears the reissue request from the state Secret. When a reissue is warranted it deletes the stale
// tailnet device before returning true so the new key registers a clean device.
func (r *Reissuer) ShouldReissue(ctx context.Context, tsClient tsclient.Client, logger *zap.SugaredLogger, in ReissueInput) (shouldReissue bool, err error) {
var stateData map[string][]byte
if in.StateSecret != nil {
stateData = in.StateSecret.Data
}
r.mu.Lock()
reissuing := r.reissuing[in.ParentName].Contains(in.ReplicaName)
r.mu.Unlock()
if reissuing {
_, requestStillPresent := stateData[kubetypes.KeyReissueAuthkey]
if !requestStillPresent {
r.mu.Lock()
r.setReissuingLocked(in.ParentName, in.ReplicaName, false)
r.mu.Unlock()
logger.Debugf("auth key reissue completed for %q", in.ReplicaName)
return false, nil
}
logger.Debugf("auth key already in process of re-issuance for %q, waiting", in.ReplicaName)
return false, nil
}
defer func() {
r.mu.Lock()
r.setReissuingLocked(in.ParentName, in.ReplicaName, shouldReissue)
r.mu.Unlock()
}()
brokenAuthkey, ok := stateData[kubetypes.KeyReissueAuthkey]
if !ok {
return false, nil
}
empty := in.CfgAuthKey == nil || *in.CfgAuthKey == ""
broken := in.CfgAuthKey != nil && *in.CfgAuthKey == string(brokenAuthkey)
// A new key has been written but the replica hasn't picked it up yet.
if !empty && !broken {
return false, nil
}
r.mu.Lock()
lim := r.limiterLocked(in.ParentName, 1)
r.mu.Unlock()
if !lim.Allow() {
logger.Debugf("auth key re-issuance rate limit exceeded, limit: %.2f, burst: %d, tokens: %.2f",
lim.Limit(), lim.Burst(), lim.Tokens())
return false, fmt.Errorf("auth key re-issuance rate limit exceeded for %s %q, will retry with backoff", in.Kind, in.ParentName)
}
logger.Infof("%s replica %s failing to auth; attempting cleanup and new key", in.Kind, in.ReplicaName)
if tsID := stateData[kubetypes.KeyDeviceID]; len(tsID) > 0 {
if err = EnsureDeviceDeleted(ctx, tsClient, logger, tailcfg.StableNodeID(tsID)); err != nil {
return false, err
}
}
return true, nil
}
@@ -0,0 +1,289 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
//go:build !plan9
package tailscaled_test
import (
"context"
"slices"
"strings"
"sync"
"testing"
"go.uber.org/zap"
corev1 "k8s.io/api/core/v1"
tailscaleclient "tailscale.com/client/tailscale/v2"
"tailscale.com/k8s-operator/reconciler/tailscaled"
"tailscale.com/k8s-operator/tsclient"
"tailscale.com/kube/kubetypes"
)
func TestReissuer_ShouldReissue(t *testing.T) {
existingAuthKey := "existing-auth-key"
for name, tc := range map[string]struct {
stateData map[string][]byte
cfgAuthKey *string
wantReissue bool
wantDeleted []string
}{
"no_state_no_request": {
cfgAuthKey: &existingAuthKey,
},
"no_reissue_request": {
stateData: map[string][]byte{kubetypes.KeyDeviceID: []byte("nodeid-0")},
cfgAuthKey: &existingAuthKey,
},
"reissue_requested_key_still_current_waits": {
// Reissue requested but the config's key differs from the broken
// one: a fresh key was already written and the replica hasn't
// picked it up yet.
stateData: map[string][]byte{
kubetypes.KeyReissueAuthkey: []byte("some-older-authkey"),
},
cfgAuthKey: &existingAuthKey,
},
"reissue_requested_broken_key_reissues": {
stateData: map[string][]byte{
kubetypes.KeyDeviceID: []byte("nodeid-0"),
kubetypes.KeyReissueAuthkey: []byte(existingAuthKey),
},
cfgAuthKey: &existingAuthKey,
wantReissue: true,
wantDeleted: []string{"nodeid-0"},
},
"reissue_requested_empty_key_reissues_no_device": {
// Reissue requested, config key empty, and no device_id yet: reissue
// but nothing to delete from control.
stateData: map[string][]byte{
kubetypes.KeyReissueAuthkey: []byte(""),
},
cfgAuthKey: nil,
wantReissue: true,
wantDeleted: nil,
},
} {
t.Run(name, func(t *testing.T) {
var stateSecret *corev1.Secret
if tc.stateData != nil {
stateSecret = &corev1.Secret{Data: tc.stateData}
}
tsc := &fakeReissueClient{}
r := tailscaled.NewReissuer()
r.EnsureState("pg", 1)
got, err := r.ShouldReissue(t.Context(), tsc, zap.NewNop().Sugar(), tailscaled.ReissueInput{
ParentName: "pg",
ReplicaName: "pg-0",
Kind: tailscaled.KindProxyGroup,
StateSecret: stateSecret,
CfgAuthKey: tc.cfgAuthKey,
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got != tc.wantReissue {
t.Errorf("shouldReissue = %v, want %v", got, tc.wantReissue)
}
if !slices.Equal(tsc.deleted, tc.wantDeleted) {
t.Errorf("deleted devices = %v, want %v", tsc.deleted, tc.wantDeleted)
}
})
}
}
// TestReissuer_InFlight verifies that once a reissue is triggered, subsequent
// checks return false until the replica clears the reissue request from its
// state Secret.
func TestReissuer_InFlight(t *testing.T) {
key := "broken-key"
tsc := &fakeReissueClient{}
r := tailscaled.NewReissuer()
r.EnsureState("pg", 1)
requested := &corev1.Secret{Data: map[string][]byte{
kubetypes.KeyDeviceID: []byte("nodeid-0"),
kubetypes.KeyReissueAuthkey: []byte(key),
}}
in := tailscaled.ReissueInput{ParentName: "pg", ReplicaName: "pg-0", Kind: tailscaled.KindProxyGroup, StateSecret: requested, CfgAuthKey: &key}
got, err := r.ShouldReissue(t.Context(), tsc, zap.NewNop().Sugar(), in)
if err != nil || !got {
t.Fatalf("first check: got %v, err %v; want true, nil", got, err)
}
// Request still present -> reissue is in-flight, don't reissue again.
got, err = r.ShouldReissue(t.Context(), tsc, zap.NewNop().Sugar(), in)
if err != nil || got {
t.Fatalf("in-flight check: got %v, err %v; want false, nil", got, err)
}
// Request cleared by containerboot -> in-flight marker resets, no reissue.
cleared := &corev1.Secret{Data: map[string][]byte{kubetypes.KeyDeviceID: []byte("nodeid-1")}}
got, err = r.ShouldReissue(t.Context(), tsc, zap.NewNop().Sugar(), tailscaled.ReissueInput{
ParentName: "pg", ReplicaName: "pg-0", Kind: tailscaled.KindProxyGroup, StateSecret: cleared, CfgAuthKey: &key,
})
if err != nil || got {
t.Fatalf("cleared check: got %v, err %v; want false, nil", got, err)
}
}
// TestReissuer_RateLimit verifies that the per-parent rate limiter, shared
// across replicas, blocks re-issuance once its burst is exhausted.
func TestReissuer_RateLimit(t *testing.T) {
key := "broken-key"
tsc := &fakeReissueClient{}
r := tailscaled.NewReissuer()
// Burst of 1: the first replica's reissue consumes the only token.
r.EnsureState("pg", 1)
brokenState := func() *corev1.Secret {
return &corev1.Secret{Data: map[string][]byte{
kubetypes.KeyDeviceID: []byte("nodeid"),
kubetypes.KeyReissueAuthkey: []byte(key),
}}
}
if got, err := r.ShouldReissue(t.Context(), tsc, zap.NewNop().Sugar(), tailscaled.ReissueInput{
ParentName: "pg", ReplicaName: "pg-0", Kind: tailscaled.KindProxyGroup, StateSecret: brokenState(), CfgAuthKey: &key,
}); err != nil || !got {
t.Fatalf("first replica: got %v, err %v; want true, nil", got, err)
}
// A second replica sharing the parent's limiter finds the bucket empty.
_, err := r.ShouldReissue(t.Context(), tsc, zap.NewNop().Sugar(), tailscaled.ReissueInput{
ParentName: "pg", ReplicaName: "pg-1", Kind: tailscaled.KindProxyGroup, StateSecret: brokenState(), CfgAuthKey: &key,
})
if err == nil || !strings.Contains(err.Error(), "rate limit exceeded") {
t.Fatalf("second replica: expected rate limit error, got %v", err)
}
}
// TestReissuer_ShouldReissue_NoEnsureState verifies ShouldReissue creates the
// rate limiter on demand, so a caller that reaches it without a prior
// EnsureState reissues instead of panicking on a nil limiter.
func TestReissuer_ShouldReissue_NoEnsureState(t *testing.T) {
key := "broken-key"
tsc := &fakeReissueClient{}
r := tailscaled.NewReissuer()
broken := &corev1.Secret{Data: map[string][]byte{
kubetypes.KeyDeviceID: []byte("nodeid-0"),
kubetypes.KeyReissueAuthkey: []byte(key),
}}
got, err := r.ShouldReissue(t.Context(), tsc, zap.NewNop().Sugar(), tailscaled.ReissueInput{
ParentName: "pg", ReplicaName: "pg-0", Kind: tailscaled.KindProxyGroup, StateSecret: broken, CfgAuthKey: &key,
})
if err != nil || !got {
t.Fatalf("got %v, err %v; want true, nil", got, err)
}
if !slices.Equal(tsc.deleted, []string{"nodeid-0"}) {
t.Errorf("deleted devices = %v, want [nodeid-0]", tsc.deleted)
}
}
// TestReissuer_RemoveState verifies that after RemoveState the in-flight marker
// is cleared, so a later reissue request for the same replica triggers afresh.
func TestReissuer_RemoveState(t *testing.T) {
key := "broken-key"
tsc := &fakeReissueClient{}
r := tailscaled.NewReissuer()
r.EnsureState("pg", 1)
broken := func() *corev1.Secret {
return &corev1.Secret{Data: map[string][]byte{
kubetypes.KeyDeviceID: []byte("nodeid-0"),
kubetypes.KeyReissueAuthkey: []byte(key),
}}
}
in := tailscaled.ReissueInput{ParentName: "pg", ReplicaName: "pg-0", Kind: tailscaled.KindProxyGroup, StateSecret: broken(), CfgAuthKey: &key}
if got, err := r.ShouldReissue(t.Context(), tsc, zap.NewNop().Sugar(), in); err != nil || !got {
t.Fatalf("first check: got %v, err %v; want true, nil", got, err)
}
// Same request still present: in-flight marker suppresses a second reissue.
if got, err := r.ShouldReissue(t.Context(), tsc, zap.NewNop().Sugar(), in); err != nil || got {
t.Fatalf("in-flight check: got %v, err %v; want false, nil", got, err)
}
// RemoveState drops the in-flight marker (and the rate limiter), so the next
// call is treated as a fresh reissue rather than an in-flight one.
r.RemoveState("pg")
if got, err := r.ShouldReissue(t.Context(), tsc, zap.NewNop().Sugar(), in); err != nil || !got {
t.Fatalf("after RemoveState: got %v, err %v; want true, nil", got, err)
}
}
// TestReissuer_RemoveState_AfterScaleDown verifies RemoveState clears markers
// for every replica the parent ever had, not just its current count, so a
// parent scaled down then deleted doesn't strand in-flight entries.
func TestReissuer_RemoveState_AfterScaleDown(t *testing.T) {
key := "broken-key"
tsc := &fakeReissueClient{}
r := tailscaled.NewReissuer()
r.EnsureState("pg", 2)
broken := func(replica string) tailscaled.ReissueInput {
return tailscaled.ReissueInput{
ParentName: "pg",
ReplicaName: replica,
Kind: tailscaled.KindProxyGroup,
StateSecret: &corev1.Secret{Data: map[string][]byte{
kubetypes.KeyDeviceID: []byte("nodeid"),
kubetypes.KeyReissueAuthkey: []byte(key),
}},
CfgAuthKey: &key,
}
}
// Both replicas start a reissue, then the parent scales down to one.
if got, err := r.ShouldReissue(t.Context(), tsc, zap.NewNop().Sugar(), broken("pg-0")); err != nil || !got {
t.Fatalf("pg-0: got %v, err %v; want true, nil", got, err)
}
if got, err := r.ShouldReissue(t.Context(), tsc, zap.NewNop().Sugar(), broken("pg-1")); err != nil || !got {
t.Fatalf("pg-1: got %v, err %v; want true, nil", got, err)
}
// Deleting the parent must clear pg-1's marker too, even though the caller
// no longer knows about the scaled-away replica. A fresh Reissuer with the
// same parent must see pg-1 as not in-flight; we assert via RemoveState then
// a reissue that succeeds (an uncleared marker would suppress it).
r.RemoveState("pg")
if got, err := r.ShouldReissue(t.Context(), tsc, zap.NewNop().Sugar(), broken("pg-1")); err != nil || !got {
t.Fatalf("pg-1 after RemoveState: got %v, err %v; want true, nil", got, err)
}
}
type fakeReissueClient struct {
tsclient.Client
mu sync.Mutex
deleted []string
}
func (c *fakeReissueClient) Devices() tsclient.DeviceResource { return (*fakeReissueDevices)(c) }
type fakeReissueDevices fakeReissueClient
func (d *fakeReissueDevices) Delete(_ context.Context, id string) error {
c := (*fakeReissueClient)(d)
c.mu.Lock()
defer c.mu.Unlock()
c.deleted = append(c.deleted, id)
return nil
}
func (d *fakeReissueDevices) List(_ context.Context, _ ...tailscaleclient.ListDevicesOptions) ([]tailscaleclient.Device, error) {
return nil, nil
}
func (d *fakeReissueDevices) Get(_ context.Context, _ string) (*tailscaleclient.Device, error) {
return nil, nil
}