summaryrefslogtreecommitdiffhomepage
path: root/cmd/k8s-operator/proxygroup.go
blob: 4bd0157013e94cb0831362544cd7f6fcfa347220 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause

//go:build !plan9

package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net/netip"
	"slices"
	"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"
	apiequality "k8s.io/apimachinery/pkg/api/equality"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/apimachinery/pkg/util/intstr"
	"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/tsclient"
	"tailscale.com/kube/egressservices"
	"tailscale.com/kube/k8s-proxy/conf"
	"tailscale.com/kube/kubetypes"
	"tailscale.com/tailcfg"
	"tailscale.com/tstime"
	"tailscale.com/types/opt"
	"tailscale.com/util/clientmetric"
	"tailscale.com/util/mak"
	"tailscale.com/util/set"
)

const (
	reasonProxyGroupCreationFailed     = "ProxyGroupCreationFailed"
	reasonProxyGroupReady              = "ProxyGroupReady"
	reasonProxyGroupAvailable          = "ProxyGroupAvailable"
	reasonProxyGroupCreating           = "ProxyGroupCreating"
	reasonProxyGroupInvalid            = "ProxyGroupInvalid"
	reasonProxyGroupTailnetUnavailable = "ProxyGroupTailnetUnavailable"

	// Copied from k8s.io/apiserver/pkg/registry/generic/registry/store.go@cccad306d649184bf2a0e319ba830c53f65c445c
	optimisticLockErrorMsg  = "the object has been modified; please apply your changes to the latest version and try again"
	staticEndpointsMaxAddrs = 2

	// The minimum tailcfg.CapabilityVersion that deployed clients are expected
	// to support to be compatible with the current ProxyGroup controller.
	// If the controller needs to depend on newer client behaviour, it should
	// maintain backwards compatible logic for older capability versions for 3
	// stable releases, as per documentation on supported version drift:
	// https://tailscale.com/kb/1236/kubernetes-operator#supported-versions
	//
	// tailcfg.CurrentCapabilityVersion was 106 when the ProxyGroup controller was
	// first introduced.
	pgMinCapabilityVersion = 106
)

var (
	gaugeEgressProxyGroupResources    = clientmetric.NewGauge(kubetypes.MetricProxyGroupEgressCount)
	gaugeIngressProxyGroupResources   = clientmetric.NewGauge(kubetypes.MetricProxyGroupIngressCount)
	gaugeAPIServerProxyGroupResources = clientmetric.NewGauge(kubetypes.MetricProxyGroupAPIServerCount)
)

// ProxyGroupReconciler ensures cluster resources for a ProxyGroup definition.
type ProxyGroupReconciler struct {
	client.Client
	log      *zap.SugaredLogger
	recorder record.EventRecorder
	clock    tstime.Clock
	clients  ClientProvider

	// User-specified defaults from the helm installation.
	tsNamespace       string
	tsProxyImage      string
	k8sProxyImage     string
	defaultTags       []string
	tsFirewallMode    string
	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
}

func (r *ProxyGroupReconciler) logger(name string) *zap.SugaredLogger {
	return r.log.With("ProxyGroup", name)
}

func (r *ProxyGroupReconciler) Reconcile(ctx context.Context, req reconcile.Request) (_ reconcile.Result, err error) {
	logger := r.logger(req.Name)
	logger.Debugf("starting reconcile")
	defer logger.Debugf("reconcile finished")

	pg := new(tsapi.ProxyGroup)
	err = r.Get(ctx, req.NamespacedName, pg)
	if apierrors.IsNotFound(err) {
		logger.Debugf("ProxyGroup not found, assuming it was deleted")
		return reconcile.Result{}, nil
	} else if err != nil {
		return reconcile.Result{}, fmt.Errorf("failed to get tailscale.com ProxyGroup: %w", err)
	}

	tsClient, err := r.clients.For(pg.Spec.Tailnet)
	if err != nil {
		oldPGStatus := pg.Status.DeepCopy()
		nrr := &notReadyReason{
			reason:  reasonProxyGroupTailnetUnavailable,
			message: fmt.Errorf("failed to get tailscale client and loginUrl: %w", err).Error(),
		}

		return reconcile.Result{}, errors.Join(err, r.maybeUpdateStatus(ctx, logger, pg, oldPGStatus, nrr, make(map[string][]netip.AddrPort)))
	}

	if markedForDeletion(pg) {
		logger.Debugf("ProxyGroup is being deleted, cleaning up resources")
		ix := xslices.Index(pg.Finalizers, FinalizerName)
		if ix < 0 {
			logger.Debugf("no finalizer, nothing to do")
			return reconcile.Result{}, nil
		}

		if done, err := r.maybeCleanup(ctx, tsClient, pg); err != nil {
			if strings.Contains(err.Error(), optimisticLockErrorMsg) {
				logger.Infof("optimistic lock error, retrying: %s", err)
				return reconcile.Result{}, nil
			}
			return reconcile.Result{}, err
		} else if !done {
			logger.Debugf("ProxyGroup resource cleanup not yet finished, will retry...")
			return reconcile.Result{RequeueAfter: shortRequeue}, nil
		}

		pg.Finalizers = slices.Delete(pg.Finalizers, ix, ix+1)
		if err := r.Update(ctx, pg); err != nil {
			return reconcile.Result{}, err
		}
		return reconcile.Result{}, nil
	}

	oldPGStatus := pg.Status.DeepCopy()
	staticEndpoints, nrr, err := r.reconcilePG(ctx, tsClient, pg, logger)
	return reconcile.Result{}, errors.Join(err, r.maybeUpdateStatus(ctx, logger, pg, oldPGStatus, nrr, staticEndpoints))
}

// reconcilePG handles all reconciliation of a ProxyGroup that is not marked
// for deletion. It is separated out from Reconcile to make a clear separation
// between reconciling the ProxyGroup, and posting the status of its created
// resources onto the ProxyGroup status field.
func (r *ProxyGroupReconciler) reconcilePG(ctx context.Context, tsClient tsclient.Client, pg *tsapi.ProxyGroup, logger *zap.SugaredLogger) (map[string][]netip.AddrPort, *notReadyReason, error) {
	if !slices.Contains(pg.Finalizers, FinalizerName) {
		// This log line is printed exactly once during initial provisioning,
		// because once the finalizer is in place this block gets skipped. So,
		// this is a nice place to log that the high level, multi-reconcile
		// operation is underway.
		logger.Infof("ensuring ProxyGroup is set up")
		pg.Finalizers = append(pg.Finalizers, FinalizerName)
		if err := r.Update(ctx, pg); err != nil {
			return r.notReadyErrf(pg, logger, "error adding finalizer: %w", err)
		}
	}

	proxyClassName := r.defaultProxyClass
	if pg.Spec.ProxyClass != "" {
		proxyClassName = pg.Spec.ProxyClass
	}

	var proxyClass *tsapi.ProxyClass
	if proxyClassName != "" {
		proxyClass = new(tsapi.ProxyClass)
		err := r.Get(ctx, types.NamespacedName{Name: proxyClassName}, proxyClass)
		if apierrors.IsNotFound(err) {
			msg := fmt.Sprintf("the ProxyGroup's ProxyClass %q does not (yet) exist", proxyClassName)
			logger.Info(msg)
			return notReady(reasonProxyGroupCreating, msg)
		}
		if err != nil {
			return r.notReadyErrf(pg, logger, "error getting ProxyGroup's ProxyClass %q: %w", proxyClassName, err)
		}
		if !tsoperator.ProxyClassIsReady(proxyClass) {
			msg := fmt.Sprintf("the ProxyGroup's ProxyClass %q is not yet in a ready state, waiting...", proxyClassName)
			logger.Info(msg)
			return notReady(reasonProxyGroupCreating, msg)
		}
	}

	if err := r.validate(ctx, pg, proxyClass, logger); err != nil {
		return notReady(reasonProxyGroupInvalid, fmt.Sprintf("invalid ProxyGroup spec: %v", err))
	}

	staticEndpoints, nrr, err := r.maybeProvision(ctx, tsClient, pg, proxyClass)
	if err != nil {
		return nil, nrr, err
	}

	return staticEndpoints, nrr, nil
}

func (r *ProxyGroupReconciler) validate(ctx context.Context, pg *tsapi.ProxyGroup, pc *tsapi.ProxyClass, logger *zap.SugaredLogger) error {
	// Our custom logic for ensuring minimum downtime ProxyGroup update rollouts relies on the local health check
	// beig accessible on the replica Pod IP:9002. This address can also be modified by users, via
	// TS_LOCAL_ADDR_PORT env var.
	//
	// Currently TS_LOCAL_ADDR_PORT controls Pod's health check and metrics address. _Probably_ there is no need for
	// users to set this to a custom value. Users who want to consume metrics, should integrate with the metrics
	// Service and/or ServiceMonitor, rather than Pods directly. The health check is likely not useful to integrate
	// directly with for operator proxies (and we should aim for unified lifecycle logic in the operator, users
	// shouldn't need to set their own).
	//
	// TODO(irbekrm): maybe disallow configuring this env var in future (in Tailscale 1.84 or later).
	if pg.Spec.Type == tsapi.ProxyGroupTypeEgress && hasLocalAddrPortSet(pc) {
		msg := fmt.Sprintf("ProxyClass %s applied to an egress ProxyGroup has TS_LOCAL_ADDR_PORT env var set to a custom value."+
			"This will disable the ProxyGroup graceful failover mechanism, so you might experience downtime when ProxyGroup pods are restarted."+
			"In future we will remove the ability to set custom TS_LOCAL_ADDR_PORT for egress ProxyGroups."+
			"Please raise an issue if you expect that this will cause issues for your workflow.", pc.Name)
		logger.Warn(msg)
	}

	// image is the value of pc.Spec.StatefulSet.Pod.TailscaleContainer.Image or ""
	// imagePath is a slash-delimited path ending with the image name, e.g.
	// "tailscale/tailscale" or maybe "k8s-proxy" if hosted at example.com/k8s-proxy.
	var image, imagePath string
	if pc != nil &&
		pc.Spec.StatefulSet != nil &&
		pc.Spec.StatefulSet.Pod != nil &&
		pc.Spec.StatefulSet.Pod.TailscaleContainer != nil &&
		pc.Spec.StatefulSet.Pod.TailscaleContainer.Image != "" {
		image, err := dockerref.ParseNormalizedNamed(pc.Spec.StatefulSet.Pod.TailscaleContainer.Image)
		if err != nil {
			// Shouldn't be possible as the ProxyClass won't be marked ready
			// without successfully parsing the image.
			return fmt.Errorf("error parsing %q as a container image reference: %w", pc.Spec.StatefulSet.Pod.TailscaleContainer.Image, err)
		}
		imagePath = dockerref.Path(image)
	}

	var errs []error
	if isAuthAPIServerProxy(pg) {
		// Validate that the static ServiceAccount already exists.
		sa := &corev1.ServiceAccount{}
		if err := r.Get(ctx, types.NamespacedName{Namespace: r.tsNamespace, Name: authAPIServerProxySAName}, sa); err != nil {
			if !apierrors.IsNotFound(err) {
				return fmt.Errorf("error validating that ServiceAccount %q exists: %w", authAPIServerProxySAName, err)
			}

			errs = append(errs, fmt.Errorf("the ServiceAccount %q used for the API server proxy in auth mode does not exist but "+
				"should have been created during operator installation; use apiServerProxyConfig.allowImpersonation=true "+
				"in the helm chart, or authproxy-rbac.yaml from the static manifests", authAPIServerProxySAName))
		}
	} else {
		// Validate that the ServiceAccount we create won't overwrite the static one.
		// TODO(tomhjp): This doesn't cover other controllers that could create a
		// ServiceAccount. Perhaps should have some guards to ensure that an update
		// would never change the ownership of a resource we expect to already be owned.
		if pgServiceAccountName(pg) == authAPIServerProxySAName {
			errs = append(errs, fmt.Errorf("the name of the ProxyGroup %q conflicts with the static ServiceAccount used for the API server proxy in auth mode", pg.Name))
		}
	}

	if pg.Spec.Type == tsapi.ProxyGroupTypeKubernetesAPIServer {
		if strings.HasSuffix(imagePath, "tailscale") {
			errs = append(errs, fmt.Errorf("the configured ProxyClass %q specifies to use image %q but expected a %q image for ProxyGroup of type %q", pc.Name, image, "k8s-proxy", pg.Spec.Type))
		}

		if pc != nil && pc.Spec.StatefulSet != nil && pc.Spec.StatefulSet.Pod != nil && pc.Spec.StatefulSet.Pod.TailscaleInitContainer != nil {
			errs = append(errs, fmt.Errorf("the configured ProxyClass %q specifies Tailscale init container config, but ProxyGroups of type %q do not use init containers", pc.Name, pg.Spec.Type))
		}
	} else {
		if strings.HasSuffix(imagePath, "k8s-proxy") {
			errs = append(errs, fmt.Errorf("the configured ProxyClass %q specifies to use image %q but expected a %q image for ProxyGroup of type %q", pc.Name, image, "tailscale", pg.Spec.Type))
		}
	}

	return errors.Join(errs...)
}

func (r *ProxyGroupReconciler) maybeProvision(ctx context.Context, tsClient tsclient.Client, pg *tsapi.ProxyGroup, proxyClass *tsapi.ProxyClass) (map[string][]netip.AddrPort, *notReadyReason, error) {
	logger := r.logger(pg.Name)
	r.mu.Lock()
	r.ensureStateAddedForProxyGroup(pg)
	r.mu.Unlock()

	svcToNodePorts := make(map[string]uint16)
	var tailscaledPort *uint16
	if proxyClass != nil && proxyClass.Spec.StaticEndpoints != nil {
		var err error
		svcToNodePorts, tailscaledPort, err = r.ensureNodePortServiceCreated(ctx, pg, proxyClass)
		if err != nil {
			if _, ok := errors.AsType[*allocatePortsErr](err); ok {
				reason := reasonProxyGroupCreationFailed
				msg := fmt.Sprintf("error provisioning NodePort Services for static endpoints: %v", err)
				r.recorder.Event(pg, corev1.EventTypeWarning, reason, msg)
				return notReady(reason, msg)
			}
			return r.notReadyErrf(pg, logger, "error provisioning NodePort Services for static endpoints: %w", err)
		}
	}

	staticEndpoints, err := r.ensureConfigSecretsCreated(ctx, tsClient, pg, proxyClass, svcToNodePorts)
	if err != nil {
		if _, ok := errors.AsType[*FindStaticEndpointErr](err); ok {
			reason := reasonProxyGroupCreationFailed
			msg := fmt.Sprintf("error provisioning config Secrets: %v", err)
			r.recorder.Event(pg, corev1.EventTypeWarning, reason, msg)
			return notReady(reason, msg)
		}
		return r.notReadyErrf(pg, logger, "error provisioning config Secrets: %w", err)
	}

	// State secrets are precreated so we can use the ProxyGroup CR as their owner ref.
	stateSecrets := pgStateSecrets(pg, r.tsNamespace)
	for _, sec := range stateSecrets {
		if _, err := createOrUpdate(ctx, r.Client, r.tsNamespace, sec, func(s *corev1.Secret) {
			s.ObjectMeta.Labels = sec.ObjectMeta.Labels
			s.ObjectMeta.Annotations = sec.ObjectMeta.Annotations
			s.ObjectMeta.OwnerReferences = sec.ObjectMeta.OwnerReferences
		}); err != nil {
			return r.notReadyErrf(pg, logger, "error provisioning state Secrets: %w", err)
		}
	}

	// auth mode kube-apiserver ProxyGroups use a statically created
	// ServiceAccount to keep ClusterRole creation permissions limited to the
	// helm chart installer.
	if !isAuthAPIServerProxy(pg) {
		sa := pgServiceAccount(pg, r.tsNamespace)
		if _, err := createOrUpdate(ctx, r.Client, r.tsNamespace, sa, func(s *corev1.ServiceAccount) {
			s.ObjectMeta.Labels = sa.ObjectMeta.Labels
			s.ObjectMeta.Annotations = sa.ObjectMeta.Annotations
			s.ObjectMeta.OwnerReferences = sa.ObjectMeta.OwnerReferences
		}); err != nil {
			return r.notReadyErrf(pg, logger, "error provisioning ServiceAccount: %w", err)
		}
	}

	role := pgRole(pg, r.tsNamespace)
	if _, err := createOrUpdate(ctx, r.Client, r.tsNamespace, role, func(r *rbacv1.Role) {
		r.ObjectMeta.Labels = role.ObjectMeta.Labels
		r.ObjectMeta.Annotations = role.ObjectMeta.Annotations
		r.ObjectMeta.OwnerReferences = role.ObjectMeta.OwnerReferences
		r.Rules = role.Rules
	}); err != nil {
		return r.notReadyErrf(pg, logger, "error provisioning Role: %w", err)
	}

	roleBinding := pgRoleBinding(pg, r.tsNamespace)
	if _, err := createOrUpdate(ctx, r.Client, r.tsNamespace, roleBinding, func(r *rbacv1.RoleBinding) {
		r.ObjectMeta.Labels = roleBinding.ObjectMeta.Labels
		r.ObjectMeta.Annotations = roleBinding.ObjectMeta.Annotations
		r.ObjectMeta.OwnerReferences = roleBinding.ObjectMeta.OwnerReferences
		r.RoleRef = roleBinding.RoleRef
		r.Subjects = roleBinding.Subjects
	}); err != nil {
		return r.notReadyErrf(pg, logger, "error provisioning RoleBinding: %w", err)
	}

	if pg.Spec.Type == tsapi.ProxyGroupTypeEgress {
		cm, hp := pgEgressCM(pg, r.tsNamespace)
		if _, err := createOrUpdate(ctx, r.Client, r.tsNamespace, cm, func(existing *corev1.ConfigMap) {
			existing.ObjectMeta.Labels = cm.ObjectMeta.Labels
			existing.ObjectMeta.OwnerReferences = cm.ObjectMeta.OwnerReferences
			mak.Set(&existing.BinaryData, egressservices.KeyHEPPings, hp)
		}); err != nil {
			return r.notReadyErrf(pg, logger, "error provisioning egress ConfigMap %q: %w", cm.Name, err)
		}
	}

	if pg.Spec.Type == tsapi.ProxyGroupTypeIngress {
		cm := pgIngressCM(pg, r.tsNamespace)
		if _, err := createOrUpdate(ctx, r.Client, r.tsNamespace, cm, func(existing *corev1.ConfigMap) {
			existing.ObjectMeta.Labels = cm.ObjectMeta.Labels
			existing.ObjectMeta.OwnerReferences = cm.ObjectMeta.OwnerReferences
		}); err != nil {
			return r.notReadyErrf(pg, logger, "error provisioning ingress ConfigMap %q: %w", cm.Name, err)
		}
	}

	defaultImage := r.tsProxyImage
	if pg.Spec.Type == tsapi.ProxyGroupTypeKubernetesAPIServer {
		defaultImage = r.k8sProxyImage
	}
	ss, err := pgStatefulSet(pg, r.tsNamespace, defaultImage, r.tsFirewallMode, tailscaledPort, proxyClass)
	if err != nil {
		return r.notReadyErrf(pg, logger, "error generating StatefulSet spec: %w", err)
	}
	cfg := &tailscaleSTSConfig{
		proxyType: string(pg.Spec.Type),
	}
	ss = applyProxyClassToStatefulSet(proxyClass, ss, cfg, logger)

	if _, err := createOrUpdate(ctx, r.Client, r.tsNamespace, ss, func(s *appsv1.StatefulSet) {
		s.Spec = ss.Spec
		s.ObjectMeta.Labels = ss.ObjectMeta.Labels
		s.ObjectMeta.Annotations = ss.ObjectMeta.Annotations
		s.ObjectMeta.OwnerReferences = ss.ObjectMeta.OwnerReferences
	}); err != nil {
		return r.notReadyErrf(pg, logger, "error provisioning StatefulSet: %w", err)
	}

	mo := &metricsOpts{
		tsNamespace:  r.tsNamespace,
		proxyStsName: pg.Name,
		proxyLabels:  pgLabels(pg.Name, nil),
		proxyType:    "proxygroup",
	}
	if err := reconcileMetricsResources(ctx, logger, mo, proxyClass, r.Client); err != nil {
		return r.notReadyErrf(pg, logger, "error reconciling metrics resources: %w", err)
	}

	if err := r.cleanupDanglingResources(ctx, tsClient, pg, proxyClass); err != nil {
		return r.notReadyErrf(pg, logger, "error cleaning up dangling resources: %w", err)
	}

	logger.Info("ProxyGroup resources synced")

	return staticEndpoints, nil, nil
}

func (r *ProxyGroupReconciler) maybeUpdateStatus(ctx context.Context, logger *zap.SugaredLogger, pg *tsapi.ProxyGroup, oldPGStatus *tsapi.ProxyGroupStatus, nrr *notReadyReason, endpoints map[string][]netip.AddrPort) (err error) {
	defer func() {
		if !apiequality.Semantic.DeepEqual(*oldPGStatus, pg.Status) {
			if updateErr := r.Client.Status().Update(ctx, pg); updateErr != nil {
				if strings.Contains(updateErr.Error(), optimisticLockErrorMsg) {
					logger.Infof("optimistic lock error updating status, retrying: %s", updateErr)
					updateErr = nil
				}
				err = errors.Join(err, updateErr)
			}
		}
	}()

	devices, err := r.getRunningProxies(ctx, pg, endpoints)
	if err != nil {
		return fmt.Errorf("failed to list running proxies: %w", err)
	}

	pg.Status.Devices = devices

	desiredReplicas := int(pgReplicas(pg))

	// Set ProxyGroupAvailable condition.
	status := metav1.ConditionFalse
	reason := reasonProxyGroupCreating
	message := fmt.Sprintf("%d/%d ProxyGroup pods running", len(devices), desiredReplicas)
	if len(devices) > 0 {
		status = metav1.ConditionTrue
		if len(devices) == desiredReplicas {
			reason = reasonProxyGroupAvailable
		}
	}
	tsoperator.SetProxyGroupCondition(pg, tsapi.ProxyGroupAvailable, status, reason, message, 0, r.clock, logger)

	// Set ProxyGroupReady condition.
	tsSvcValid, tsSvcSet := tsoperator.KubeAPIServerProxyValid(pg)
	status = metav1.ConditionFalse
	reason = reasonProxyGroupCreating
	switch {
	case nrr != nil:
		// If we failed earlier, that reason takes precedence.
		reason = nrr.reason
		message = nrr.message
	case pg.Spec.Type == tsapi.ProxyGroupTypeKubernetesAPIServer && tsSvcSet && !tsSvcValid:
		reason = reasonProxyGroupInvalid
		message = "waiting for config in spec.kubeAPIServer to be marked valid"
	case len(devices) < desiredReplicas:
	case len(devices) > desiredReplicas:
		message = fmt.Sprintf("waiting for %d ProxyGroup pods to shut down", len(devices)-desiredReplicas)
	case pg.Spec.Type == tsapi.ProxyGroupTypeKubernetesAPIServer && !tsoperator.KubeAPIServerProxyConfigured(pg):
		reason = reasonProxyGroupCreating
		message = "waiting for proxies to start advertising the kube-apiserver proxy's hostname"
	default:
		status = metav1.ConditionTrue
		reason = reasonProxyGroupReady
		message = reasonProxyGroupReady
	}
	tsoperator.SetProxyGroupCondition(pg, tsapi.ProxyGroupReady, status, reason, message, pg.Generation, r.clock, logger)

	return nil
}

// getServicePortsForProxyGroups returns a map of ProxyGroup Service names to their NodePorts,
// and a set of all allocated NodePorts for quick occupancy checking.
func getServicePortsForProxyGroups(ctx context.Context, c client.Client, namespace string, portRanges tsapi.PortRanges) (map[string]uint16, set.Set[uint16], error) {
	svcs := new(corev1.ServiceList)
	matchingLabels := client.MatchingLabels(map[string]string{
		LabelParentType: "proxygroup",
	})

	err := c.List(ctx, svcs, matchingLabels, client.InNamespace(namespace))
	if err != nil {
		return nil, nil, fmt.Errorf("failed to list ProxyGroup Services: %w", err)
	}

	svcToNodePorts := map[string]uint16{}
	usedPorts := set.Set[uint16]{}
	for _, svc := range svcs.Items {
		if len(svc.Spec.Ports) == 1 && svc.Spec.Ports[0].NodePort != 0 {
			p := uint16(svc.Spec.Ports[0].NodePort)
			if portRanges.Contains(p) {
				svcToNodePorts[svc.Name] = p
				usedPorts.Add(p)
			}
		}
	}

	return svcToNodePorts, usedPorts, nil
}

type allocatePortsErr struct {
	msg string
}

func (e *allocatePortsErr) Error() string {
	return e.msg
}

func (r *ProxyGroupReconciler) allocatePorts(ctx context.Context, pg *tsapi.ProxyGroup, proxyClassName string, portRanges tsapi.PortRanges) (map[string]uint16, error) {
	replicaCount := int(pgReplicas(pg))
	svcToNodePorts, usedPorts, err := getServicePortsForProxyGroups(ctx, r.Client, r.tsNamespace, portRanges)
	if err != nil {
		return nil, &allocatePortsErr{msg: fmt.Sprintf("failed to find ports for existing ProxyGroup NodePort Services: %s", err.Error())}
	}

	replicasAllocated := 0
	for i := range pgReplicas(pg) {
		if _, ok := svcToNodePorts[pgNodePortServiceName(pg.Name, i)]; !ok {
			svcToNodePorts[pgNodePortServiceName(pg.Name, i)] = 0
		} else {
			replicasAllocated++
		}
	}

	for replica, port := range svcToNodePorts {
		if port == 0 {
			for p := range portRanges.All() {
				if !usedPorts.Contains(p) {
					svcToNodePorts[replica] = p
					usedPorts.Add(p)
					replicasAllocated++
					break
				}
			}
		}
	}

	if replicasAllocated < replicaCount {
		return nil, &allocatePortsErr{msg: fmt.Sprintf("not enough available ports to allocate all replicas (needed %d, got %d). Field 'spec.staticEndpoints.nodePort.ports' on ProxyClass %q must have bigger range allocated", replicaCount, usedPorts.Len(), proxyClassName)}
	}

	return svcToNodePorts, nil
}

func (r *ProxyGroupReconciler) ensureNodePortServiceCreated(ctx context.Context, pg *tsapi.ProxyGroup, pc *tsapi.ProxyClass) (map[string]uint16, *uint16, error) {
	// NOTE: (ChaosInTheCRD) we want the same TargetPort for every static endpoint NodePort Service for the ProxyGroup
	tailscaledPort := getRandomPort()
	svcs := []*corev1.Service{}
	for i := range pgReplicas(pg) {
		nodePortSvcName := pgNodePortServiceName(pg.Name, i)

		svc := &corev1.Service{}
		err := r.Get(ctx, types.NamespacedName{Name: nodePortSvcName, Namespace: r.tsNamespace}, svc)
		if err != nil && !apierrors.IsNotFound(err) {
			return nil, nil, fmt.Errorf("error getting Kubernetes Service %q: %w", nodePortSvcName, err)
		}
		if apierrors.IsNotFound(err) {
			svcs = append(svcs, pgNodePortService(pg, nodePortSvcName, r.tsNamespace))
		} else {
			// NOTE: if we can we want to recover the random port used for tailscaled,
			// as well as the NodePort previously used for that Service
			if len(svc.Spec.Ports) == 1 {
				if svc.Spec.Ports[0].Port != 0 {
					tailscaledPort = uint16(svc.Spec.Ports[0].Port)
				}
			}
			svcs = append(svcs, svc)
		}
	}

	svcToNodePorts, err := r.allocatePorts(ctx, pg, pc.Name, pc.Spec.StaticEndpoints.NodePort.Ports)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to allocate NodePorts to ProxyGroup Services: %w", err)
	}

	for _, svc := range svcs {
		// NOTE: we know that every service is going to have 1 port here
		svc.Spec.Ports[0].Port = int32(tailscaledPort)
		svc.Spec.Ports[0].TargetPort = intstr.FromInt(int(tailscaledPort))
		svc.Spec.Ports[0].NodePort = int32(svcToNodePorts[svc.Name])

		_, err = createOrUpdate(ctx, r.Client, r.tsNamespace, svc, func(s *corev1.Service) {
			s.ObjectMeta.Labels = svc.ObjectMeta.Labels
			s.ObjectMeta.Annotations = svc.ObjectMeta.Annotations
			s.ObjectMeta.OwnerReferences = svc.ObjectMeta.OwnerReferences
			s.Spec.Selector = svc.Spec.Selector
			s.Spec.Ports = svc.Spec.Ports
		})
		if err != nil {
			return nil, nil, fmt.Errorf("error creating/updating Kubernetes NodePort Service %q: %w", svc.Name, err)
		}
	}

	return svcToNodePorts, new(tailscaledPort), nil
}

// cleanupDanglingResources ensures we don't leak config secrets, state secrets, and
// tailnet devices when the number of replicas specified is reduced.
func (r *ProxyGroupReconciler) cleanupDanglingResources(ctx context.Context, tsClient tsclient.Client, pg *tsapi.ProxyGroup, pc *tsapi.ProxyClass) error {
	logger := r.logger(pg.Name)
	metadata, err := getNodeMetadata(ctx, pg, r.Client, r.tsNamespace)
	if err != nil {
		return err
	}

	for _, m := range metadata {
		if m.ordinal+1 <= pgReplicas(pg) {
			continue
		}

		// 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 {
			return err
		}
		if err := r.Delete(ctx, m.stateSecret); err != nil && !apierrors.IsNotFound(err) {
			return fmt.Errorf("error deleting state Secret %q: %w", m.stateSecret.Name, err)
		}
		configSecret := m.stateSecret.DeepCopy()
		configSecret.Name += "-config"
		if err := r.Delete(ctx, configSecret); err != nil && !apierrors.IsNotFound(err) {
			return fmt.Errorf("error deleting config Secret %q: %w", configSecret.Name, err)
		}
		// NOTE(ChaosInTheCRD): we shouldn't need to get the service first, checking for a not found error should be enough
		svc := &corev1.Service{
			ObjectMeta: metav1.ObjectMeta{
				Name:      fmt.Sprintf("%s-nodeport", m.stateSecret.Name),
				Namespace: m.stateSecret.Namespace,
			},
		}
		if err := r.Delete(ctx, svc); err != nil {
			if !apierrors.IsNotFound(err) {
				return fmt.Errorf("error deleting static endpoints Kubernetes Service %q: %w", svc.Name, err)
			}
		}
	}

	// If the ProxyClass has its StaticEndpoints config removed, we want to remove all of the NodePort Services
	if pc != nil && pc.Spec.StaticEndpoints == nil {
		labels := map[string]string{
			kubetypes.LabelManaged: "true",
			LabelParentType:        proxyTypeProxyGroup,
			LabelParentName:        pg.Name,
		}
		if err := r.DeleteAllOf(ctx, &corev1.Service{}, client.InNamespace(r.tsNamespace), client.MatchingLabels(labels)); err != nil {
			return fmt.Errorf("error deleting Kubernetes Services for static endpoints: %w", err)
		}
	}

	return nil
}

// maybeCleanup just deletes the device from the tailnet. All the kubernetes
// resources linked to a ProxyGroup will get cleaned up via owner references
// (which we can use because they are all in the same namespace).
func (r *ProxyGroupReconciler) maybeCleanup(ctx context.Context, tsClient tsclient.Client, pg *tsapi.ProxyGroup) (bool, error) {
	logger := r.logger(pg.Name)

	metadata, err := getNodeMetadata(ctx, pg, r.Client, r.tsNamespace)
	if err != nil {
		return false, err
	}

	for _, m := range metadata {
		if err := r.ensureDeviceDeleted(ctx, tsClient, m.tsID, logger); err != nil {
			return false, err
		}
	}

	mo := &metricsOpts{
		proxyLabels: pgLabels(pg.Name, nil),
		tsNamespace: r.tsNamespace,
		proxyType:   "proxygroup",
	}
	if err := maybeCleanupMetricsResources(ctx, mo, r.Client); err != nil {
		return false, fmt.Errorf("error cleaning up metrics resources: %w", err)
	}

	logger.Infof("cleaned up ProxyGroup resources")
	r.mu.Lock()
	r.ensureStateRemovedForProxyGroup(pg)
	r.mu.Unlock()
	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,
	pg *tsapi.ProxyGroup,
	proxyClass *tsapi.ProxyClass,
	svcToNodePorts map[string]uint16,
) (endpoints map[string][]netip.AddrPort, err error) {
	logger := r.logger(pg.Name)
	endpoints = make(map[string][]netip.AddrPort, pgReplicas(pg)) // keyed by Service name.
	for i := range pgReplicas(pg) {
		logger = logger.With("Pod", fmt.Sprintf("%s-%d", pg.Name, i))
		cfgSecret := &corev1.Secret{
			ObjectMeta: metav1.ObjectMeta{
				Name:            pgConfigSecretName(pg.Name, i),
				Namespace:       r.tsNamespace,
				Labels:          pgSecretLabels(pg.Name, kubetypes.LabelSecretTypeConfig),
				OwnerReferences: pgOwnerReference(pg),
			},
		}

		var existingCfgSecret *corev1.Secret // unmodified copy of secret
		if err = r.Get(ctx, client.ObjectKeyFromObject(cfgSecret), cfgSecret); err == nil {
			logger.Debugf("Secret %s/%s already exists", cfgSecret.GetNamespace(), cfgSecret.GetName())
			existingCfgSecret = cfgSecret.DeepCopy()
		} else if !apierrors.IsNotFound(err) {
			return nil, err
		}

		authKey, err := r.getAuthKey(ctx, tsClient, pg, existingCfgSecret, i, logger)
		if err != nil {
			return nil, err
		}

		nodePortSvcName := pgNodePortServiceName(pg.Name, i)
		if len(svcToNodePorts) > 0 {
			replicaName := fmt.Sprintf("%s-%d", pg.Name, i)
			port, ok := svcToNodePorts[nodePortSvcName]
			if !ok {
				return nil, fmt.Errorf("could not find configured NodePort for ProxyGroup replica %q", replicaName)
			}

			endpoints[nodePortSvcName], err = r.findStaticEndpoints(ctx, existingCfgSecret, proxyClass, port, logger)
			if err != nil {
				return nil, fmt.Errorf("could not find static endpoints for replica %q: %w", replicaName, err)
			}
		}

		if pg.Spec.Type == tsapi.ProxyGroupTypeKubernetesAPIServer {
			hostname := pgHostname(pg, i)

			if authKey == nil && existingCfgSecret != nil {
				deviceAuthed := false
				for _, d := range pg.Status.Devices {
					if d.Hostname == hostname {
						deviceAuthed = true
						break
					}
				}
				if !deviceAuthed {
					existingCfg := conf.ConfigV1Alpha1{}
					if err := json.Unmarshal(existingCfgSecret.Data[kubetypes.KubeAPIServerConfigFile], &existingCfg); err != nil {
						return nil, fmt.Errorf("error unmarshalling existing config: %w", err)
					}
					if existingCfg.AuthKey != nil {
						authKey = existingCfg.AuthKey
					}
				}
			}

			mode := kubetypes.APIServerProxyModeAuth
			if !isAuthAPIServerProxy(pg) {
				mode = kubetypes.APIServerProxyModeNoAuth
			}
			cfg := conf.VersionedConfig{
				Version: "v1alpha1",
				ConfigV1Alpha1: &conf.ConfigV1Alpha1{
					AuthKey:  authKey,
					State:    new(fmt.Sprintf("kube:%s", pgPodName(pg.Name, i))),
					App:      new(kubetypes.AppProxyGroupKubeAPIServer),
					LogLevel: new(logger.Level().String()),

					// Reloadable fields.
					Hostname: &hostname,
					APIServerProxy: &conf.APIServerProxyConfig{
						Enabled: opt.NewBool(true),
						Mode:    &mode,
						// The first replica is elected as the cert issuer, same
						// as containerboot does for ingress-pg-reconciler.
						IssueCerts: opt.NewBool(i == 0),
					},
					LocalPort:          new(uint16(9002)),
					HealthCheckEnabled: opt.NewBool(true),
				},
			}

			// Copy over config that the apiserver-proxy-service-reconciler sets.
			if existingCfgSecret != nil {
				if k8sProxyCfg, ok := cfgSecret.Data[kubetypes.KubeAPIServerConfigFile]; ok {
					k8sCfg := &conf.ConfigV1Alpha1{}
					if err := json.Unmarshal(k8sProxyCfg, k8sCfg); err != nil {
						return nil, fmt.Errorf("failed to unmarshal kube-apiserver config: %w", err)
					}

					cfg.AdvertiseServices = k8sCfg.AdvertiseServices
					if k8sCfg.APIServerProxy != nil {
						cfg.APIServerProxy.ServiceName = k8sCfg.APIServerProxy.ServiceName
					}
				}
			}

			if tsClient.LoginURL() != "" {
				cfg.ServerURL = new(tsClient.LoginURL())
			}

			if proxyClass != nil && proxyClass.Spec.TailscaleConfig != nil {
				cfg.AcceptRoutes = opt.NewBool(proxyClass.Spec.TailscaleConfig.AcceptRoutes)
			}

			if proxyClass != nil && proxyClass.Spec.Metrics != nil {
				cfg.MetricsEnabled = opt.NewBool(proxyClass.Spec.Metrics.Enable)
			}

			if len(endpoints[nodePortSvcName]) > 0 {
				cfg.StaticEndpoints = endpoints[nodePortSvcName]
			}

			cfgB, err := json.Marshal(cfg)
			if err != nil {
				return nil, fmt.Errorf("error marshalling k8s-proxy config: %w", err)
			}
			mak.Set(&cfgSecret.Data, kubetypes.KubeAPIServerConfigFile, cfgB)
		} else {
			// AdvertiseServices config is set by ingress-pg-reconciler, so make sure we
			// don't overwrite it if already set.
			existingAdvertiseServices, err := extractAdvertiseServicesConfig(existingCfgSecret)
			if err != nil {
				return nil, err
			}

			configs, err := pgTailscaledConfig(pg, tsClient.LoginURL(), proxyClass, i, authKey, endpoints[nodePortSvcName], existingAdvertiseServices)
			if err != nil {
				return nil, fmt.Errorf("error creating tailscaled config: %w", err)
			}

			for cap, cfg := range configs {
				cfgJSON, err := json.Marshal(cfg)
				if err != nil {
					return nil, fmt.Errorf("error marshalling tailscaled config: %w", err)
				}
				mak.Set(&cfgSecret.Data, tsoperator.TailscaledConfigFileName(cap), cfgJSON)
			}
		}

		if existingCfgSecret != nil {
			if !apiequality.Semantic.DeepEqual(existingCfgSecret, cfgSecret) {
				logger.Debugf("Updating the existing ProxyGroup config Secret %s", cfgSecret.Name)
				if err := r.Update(ctx, cfgSecret); err != nil {
					return nil, err
				}
			}
		} else {
			logger.Debugf("Creating a new config Secret %s for the ProxyGroup", cfgSecret.Name)
			if err := r.Create(ctx, cfgSecret); err != nil {
				return nil, err
			}
		}

	}

	return endpoints, nil
}

// getAuthKey returns an auth key for the proxy, or nil if none is needed.
// A new key is created if the config Secret doesn't exist yet, or if the
// proxy has requested a reissue via its state Secret. An existing key is
// retained while the device hasn't authed or a reissue is in progress.
func (r *ProxyGroupReconciler) getAuthKey(ctx context.Context, tsClient tsclient.Client, pg *tsapi.ProxyGroup, existingCfgSecret *corev1.Secret, ordinal int32, logger *zap.SugaredLogger) (*string, error) {
	// Get state Secret to check if it's already authed or has requested
	// a fresh auth key.
	stateSecret := &corev1.Secret{
		ObjectMeta: metav1.ObjectMeta{
			Name:      pgStateSecretName(pg.Name, ordinal),
			Namespace: r.tsNamespace,
		},
	}
	if err := r.Get(ctx, client.ObjectKeyFromObject(stateSecret), stateSecret); err != nil && !apierrors.IsNotFound(err) {
		return nil, err
	}

	var createAuthKey bool
	var cfgAuthKey *string
	if existingCfgSecret == nil {
		createAuthKey = true
	} else {
		var err error
		cfgAuthKey, err = authKeyFromSecret(existingCfgSecret)
		if err != nil {
			return nil, fmt.Errorf("error retrieving auth key from existing config Secret: %w", err)
		}
	}

	if !createAuthKey {
		var err error
		createAuthKey, err = r.shouldReissueAuthKey(ctx, tsClient, pg, stateSecret, cfgAuthKey)
		if err != nil {
			return nil, err
		}
	}

	var authKey *string
	if createAuthKey {
		logger.Debugf("creating auth key for ProxyGroup proxy %q", stateSecret.Name)

		tags := pg.Spec.Tags.Stringify()
		if len(tags) == 0 {
			tags = r.defaultTags
		}
		key, err := newAuthKey(ctx, tsClient, tags)
		if err != nil {
			return nil, err
		}
		authKey = &key
	} else {
		// Retain auth key if the device hasn't authed yet, or if a
		// reissue is in progress (device_id is stale during reissue).
		_, reissueRequested := stateSecret.Data[kubetypes.KeyReissueAuthkey]
		if !deviceAuthed(stateSecret) || reissueRequested {
			authKey = cfgAuthKey
		}
	}

	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
}

func (e *FindStaticEndpointErr) Error() string {
	return e.msg
}

// findStaticEndpoints returns up to two `netip.AddrPort` entries, derived from the ExternalIPs of Nodes that
// match the `proxyClass`'s selector within the StaticEndpoints configuration. The port is set to the replica's NodePort Service Port.
func (r *ProxyGroupReconciler) findStaticEndpoints(ctx context.Context, existingCfgSecret *corev1.Secret, proxyClass *tsapi.ProxyClass, port uint16, logger *zap.SugaredLogger) ([]netip.AddrPort, error) {
	var currAddrs []netip.AddrPort
	if existingCfgSecret != nil {
		oldConfB := existingCfgSecret.Data[tsoperator.TailscaledConfigFileName(106)]
		if len(oldConfB) > 0 {
			var oldConf ipn.ConfigVAlpha
			if err := json.Unmarshal(oldConfB, &oldConf); err == nil {
				currAddrs = oldConf.StaticEndpoints
			} else {
				logger.Debugf("failed to unmarshal tailscaled config from secret %q: %v", existingCfgSecret.Name, err)
			}
		} else {
			logger.Debugf("failed to get tailscaled config from secret %q: empty data", existingCfgSecret.Name)
		}
	}

	nodes := new(corev1.NodeList)
	selectors := client.MatchingLabels(proxyClass.Spec.StaticEndpoints.NodePort.Selector)

	err := r.List(ctx, nodes, selectors)
	if err != nil {
		return nil, fmt.Errorf("failed to list nodes: %w", err)
	}

	if len(nodes.Items) == 0 {
		return nil, &FindStaticEndpointErr{msg: fmt.Sprintf("failed to match nodes to configured Selectors on `spec.staticEndpoints.nodePort.selectors` field for ProxyClass %q", proxyClass.Name)}
	}

	endpoints := []netip.AddrPort{}

	// NOTE(ChaosInTheCRD): Setting a hard limit of two static endpoints.
	newAddrs := []netip.AddrPort{}
	for _, n := range nodes.Items {
		for _, a := range n.Status.Addresses {
			if a.Type == corev1.NodeExternalIP {
				addr := getStaticEndpointAddress(&a, port)
				if addr == nil {
					logger.Debugf("failed to parse %q address on node %q: %q", corev1.NodeExternalIP, n.Name, a.Address)
					continue
				}

				// we want to add the currently used IPs first before
				// adding new ones.
				if currAddrs != nil && slices.Contains(currAddrs, *addr) {
					endpoints = append(endpoints, *addr)
				} else {
					newAddrs = append(newAddrs, *addr)
				}
			}

			if len(endpoints) == 2 {
				break
			}
		}
	}

	// if the 2 endpoints limit hasn't been reached, we
	// can start adding newIPs.
	if len(endpoints) < 2 {
		for _, a := range newAddrs {
			endpoints = append(endpoints, a)
			if len(endpoints) == 2 {
				break
			}
		}
	}

	if len(endpoints) == 0 {
		return nil, &FindStaticEndpointErr{msg: fmt.Sprintf("failed to find any `status.addresses` of type %q on nodes using configured Selectors on `spec.staticEndpoints.nodePort.selectors` for ProxyClass %q", corev1.NodeExternalIP, proxyClass.Name)}
	}

	return endpoints, nil
}

func getStaticEndpointAddress(a *corev1.NodeAddress, port uint16) *netip.AddrPort {
	addr, err := netip.ParseAddr(a.Address)
	if err != nil {
		return nil
	}

	return new(netip.AddrPortFrom(addr, port))
}

// 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.
func (r *ProxyGroupReconciler) ensureStateAddedForProxyGroup(pg *tsapi.ProxyGroup) {
	switch pg.Spec.Type {
	case tsapi.ProxyGroupTypeEgress:
		r.egressProxyGroups.Add(pg.UID)
	case tsapi.ProxyGroupTypeIngress:
		r.ingressProxyGroups.Add(pg.UID)
	case tsapi.ProxyGroupTypeKubernetesAPIServer:
		r.apiServerProxyGroups.Add(pg.UID)
	}
	gaugeEgressProxyGroupResources.Set(int64(r.egressProxyGroups.Len()))
	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
		}
	}
}

// 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.
func (r *ProxyGroupReconciler) ensureStateRemovedForProxyGroup(pg *tsapi.ProxyGroup) {
	switch pg.Spec.Type {
	case tsapi.ProxyGroupTypeEgress:
		r.egressProxyGroups.Remove(pg.UID)
	case tsapi.ProxyGroupTypeIngress:
		r.ingressProxyGroups.Remove(pg.UID)
	case tsapi.ProxyGroupTypeKubernetesAPIServer:
		r.apiServerProxyGroups.Remove(pg.UID)
	}
	gaugeEgressProxyGroupResources.Set(int64(r.egressProxyGroups.Len()))
	gaugeIngressProxyGroupResources.Set(int64(r.ingressProxyGroups.Len()))
	gaugeAPIServerProxyGroupResources.Set(int64(r.apiServerProxyGroups.Len()))
	delete(r.authKeyRateLimits, pg.Name)
}

func pgTailscaledConfig(pg *tsapi.ProxyGroup, loginServer string, pc *tsapi.ProxyClass, idx int32, authKey *string, staticEndpoints []netip.AddrPort, oldAdvertiseServices []string) (tailscaledConfigs, error) {
	conf := &ipn.ConfigVAlpha{
		Version:           "alpha0",
		AcceptDNS:         "false",
		AcceptRoutes:      "false", // AcceptRoutes defaults to true
		Locked:            "false",
		Hostname:          new(pgHostname(pg, idx)),
		AdvertiseServices: oldAdvertiseServices,
		AuthKey:           authKey,
	}

	if loginServer != "" {
		conf.ServerURL = &loginServer
	}

	if shouldAcceptRoutes(pc) {
		conf.AcceptRoutes = "true"
	}

	if len(staticEndpoints) > 0 {
		conf.StaticEndpoints = staticEndpoints
	}

	return map[tailcfg.CapabilityVersion]ipn.ConfigVAlpha{
		pgMinCapabilityVersion: *conf,
	}, nil
}

func extractAdvertiseServicesConfig(cfgSecret *corev1.Secret) ([]string, error) {
	if cfgSecret == nil {
		return nil, nil
	}

	cfg, err := latestConfigFromSecret(cfgSecret)
	if err != nil {
		return nil, err
	}

	if cfg == nil {
		return nil, nil
	}

	return cfg.AdvertiseServices, nil
}

// getNodeMetadata gets metadata for all the pods owned by this ProxyGroup by
// querying their state Secrets. It may not return the same number of items as
// specified in the ProxyGroup spec if e.g. it is getting scaled up or down, or
// some pods have failed to write state.
//
// The returned metadata will contain an entry for each state Secret that exists.
func getNodeMetadata(ctx context.Context, pg *tsapi.ProxyGroup, cl client.Client, tsNamespace string) (metadata []nodeMetadata, _ error) {
	// List all state Secrets owned by this ProxyGroup.
	secrets := &corev1.SecretList{}
	if err := cl.List(ctx, secrets, client.InNamespace(tsNamespace), client.MatchingLabels(pgSecretLabels(pg.Name, kubetypes.LabelSecretTypeState))); err != nil {
		return nil, fmt.Errorf("failed to list state Secrets: %w", err)
	}
	for _, secret := range secrets.Items {
		var ordinal int32
		if _, err := fmt.Sscanf(secret.Name, pg.Name+"-%d", &ordinal); err != nil {
			return nil, fmt.Errorf("unexpected secret %s was labelled as owned by the ProxyGroup %s: %w", secret.Name, pg.Name, err)
		}

		nm := nodeMetadata{
			ordinal:     ordinal,
			stateSecret: &secret,
		}

		prefs, ok, err := getDevicePrefs(&secret)
		if err != nil {
			return nil, err
		}
		if ok {
			nm.tsID = prefs.Config.NodeID
			nm.dnsName = prefs.Config.UserProfile.LoginName
		}

		pod := &corev1.Pod{}
		if err := cl.Get(ctx, client.ObjectKey{Namespace: tsNamespace, Name: fmt.Sprintf("%s-%d", pg.Name, ordinal)}, pod); err != nil && !apierrors.IsNotFound(err) {
			return nil, err
		} else if err == nil {
			nm.podUID = string(pod.UID)
		}
		metadata = append(metadata, nm)
	}

	// Sort for predictable ordering and status.
	sort.Slice(metadata, func(i, j int) bool {
		return metadata[i].ordinal < metadata[j].ordinal
	})

	return metadata, nil
}

// getRunningProxies will return status for all proxy Pods whose state Secret
// has an up to date Pod UID and at least a hostname.
func (r *ProxyGroupReconciler) getRunningProxies(ctx context.Context, pg *tsapi.ProxyGroup, staticEndpoints map[string][]netip.AddrPort) (devices []tsapi.TailnetDevice, _ error) {
	metadata, err := getNodeMetadata(ctx, pg, r.Client, r.tsNamespace)
	if err != nil {
		return nil, err
	}

	for i, m := range metadata {
		if m.podUID == "" || !strings.EqualFold(string(m.stateSecret.Data[kubetypes.KeyPodUID]), m.podUID) {
			// Current Pod has not yet written its UID to the state Secret, data may
			// be stale.
			continue
		}

		device := tsapi.TailnetDevice{}
		if hostname, _, ok := strings.Cut(string(m.stateSecret.Data[kubetypes.KeyDeviceFQDN]), "."); ok {
			device.Hostname = hostname
		} else {
			continue
		}

		if ipsB := m.stateSecret.Data[kubetypes.KeyDeviceIPs]; len(ipsB) > 0 {
			ips := []string{}
			if err := json.Unmarshal(ipsB, &ips); err != nil {
				return nil, fmt.Errorf("failed to extract device IPs from state Secret %q: %w", m.stateSecret.Name, err)
			}
			device.TailnetIPs = ips
		}

		// TODO(tomhjp): This is our input to the proxy, but we should instead
		// read this back from the proxy's state in some way to more accurately
		// reflect its status.
		if ep, ok := staticEndpoints[pgNodePortServiceName(pg.Name, int32(i))]; ok && len(ep) > 0 {
			eps := make([]string, 0, len(ep))
			for _, e := range ep {
				eps = append(eps, e.String())
			}
			device.StaticEndpoints = eps
		}

		devices = append(devices, device)
	}

	return devices, nil
}

type nodeMetadata struct {
	ordinal     int32
	stateSecret *corev1.Secret
	podUID      string // or empty if the Pod no longer exists.
	tsID        tailcfg.StableNodeID
	dnsName     string
}

func notReady(reason, msg string) (map[string][]netip.AddrPort, *notReadyReason, error) {
	return nil, &notReadyReason{
		reason:  reason,
		message: msg,
	}, nil
}

func (r *ProxyGroupReconciler) notReadyErrf(pg *tsapi.ProxyGroup, logger *zap.SugaredLogger, format string, a ...any) (map[string][]netip.AddrPort, *notReadyReason, error) {
	err := fmt.Errorf(format, a...)
	if strings.Contains(err.Error(), optimisticLockErrorMsg) {
		msg := fmt.Sprintf("optimistic lock error, retrying: %s", err.Error())
		logger.Info(msg)
		return notReady(reasonProxyGroupCreating, msg)
	}

	r.recorder.Event(pg, corev1.EventTypeWarning, reasonProxyGroupCreationFailed, err.Error())
	return nil, &notReadyReason{
		reason:  reasonProxyGroupCreationFailed,
		message: err.Error(),
	}, err
}

type notReadyReason struct {
	reason  string
	message string
}