-
Notifications
You must be signed in to change notification settings - Fork 218
Expand file tree
/
Copy pathmcpremoteproxy_controller.go
More file actions
1610 lines (1434 loc) · 63.8 KB
/
mcpremoteproxy_controller.go
File metadata and controls
1610 lines (1434 loc) · 63.8 KB
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
// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc.
// SPDX-License-Identifier: Apache-2.0
// Package controllers contains the reconciliation logic for the MCPRemoteProxy custom resource.
// It handles the creation, update, and deletion of remote MCP proxies in Kubernetes.
package controllers
import (
"context"
stderrors "errors"
"fmt"
"maps"
"reflect"
"time"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/events"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
mcpv1beta1 "github.com/stacklok/toolhive/cmd/thv-operator/api/v1beta1"
ctrlutil "github.com/stacklok/toolhive/cmd/thv-operator/pkg/controllerutil"
"github.com/stacklok/toolhive/cmd/thv-operator/pkg/imagepullsecrets"
"github.com/stacklok/toolhive/cmd/thv-operator/pkg/kubernetes/rbac"
"github.com/stacklok/toolhive/cmd/thv-operator/pkg/runconfig/configmap/checksum"
"github.com/stacklok/toolhive/cmd/thv-operator/pkg/validation"
)
// MCPRemoteProxyReconciler reconciles a MCPRemoteProxy object
type MCPRemoteProxyReconciler struct {
client.Client
Scheme *runtime.Scheme
Recorder events.EventRecorder
PlatformDetector *ctrlutil.SharedPlatformDetector
// ImagePullSecretsDefaults are cluster-wide defaults sourced from the
// operator chart that are merged with the per-CR imagePullSecrets when
// constructing workloads. The zero value is a usable empty Defaults.
ImagePullSecretsDefaults imagepullsecrets.Defaults
}
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=mcpremoteproxies,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=mcpremoteproxies/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=mcptoolconfigs,verbs=get;list;watch
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=mcpexternalauthconfigs,verbs=get;list;watch
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=mcpoidcconfigs,verbs=get;list;watch
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=mcptelemetryconfigs,verbs=get;list;watch
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=mcpoidcconfigs/status,verbs=get;update;patch
// +kubebuilder:rbac:groups="",resources=configmaps,verbs=create;delete;get;list;patch;update;watch
// +kubebuilder:rbac:groups="",resources=services,verbs=create;delete;get;list;patch;update;watch
// +kubebuilder:rbac:groups="rbac.authorization.k8s.io",resources=roles,verbs=create;delete;get;list;patch;update;watch
// +kubebuilder:rbac:groups="rbac.authorization.k8s.io",resources=rolebindings,verbs=create;delete;get;list;patch;update;watch
// +kubebuilder:rbac:groups="",resources=events,verbs=create;patch
// +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch
// +kubebuilder:rbac:groups=apps,resources=deployments,verbs=create;delete;get;list;patch;update;watch
// +kubebuilder:rbac:groups="",resources=serviceaccounts,verbs=create;delete;get;list;patch;update;watch
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
func (r *MCPRemoteProxyReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
ctxLogger := log.FromContext(ctx)
// Fetch the MCPRemoteProxy instance
proxy := &mcpv1beta1.MCPRemoteProxy{}
err := r.Get(ctx, req.NamespacedName, proxy)
if err != nil {
if errors.IsNotFound(err) {
ctxLogger.Info("MCPRemoteProxy resource not found. Ignoring since object must be deleted")
return ctrl.Result{}, nil
}
ctxLogger.Error(err, "Failed to get MCPRemoteProxy")
return ctrl.Result{}, err
}
// Validate and handle configurations
if err := r.validateAndHandleConfigs(ctx, proxy); err != nil {
return ctrl.Result{}, err
}
// Ensure all resources
if err := r.ensureAllResources(ctx, proxy); err != nil {
return ctrl.Result{}, err
}
// Update status
if err := r.updateMCPRemoteProxyStatus(ctx, proxy); err != nil {
ctxLogger.Error(err, "Failed to update MCPRemoteProxy status")
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
// validateAndHandleConfigs validates spec and handles referenced configurations
func (r *MCPRemoteProxyReconciler) validateAndHandleConfigs(ctx context.Context, proxy *mcpv1beta1.MCPRemoteProxy) error {
ctxLogger := log.FromContext(ctx)
// Validate the spec
if err := r.validateSpec(ctx, proxy); err != nil {
ctxLogger.Error(err, "MCPRemoteProxy spec validation failed")
proxy.Status.Phase = mcpv1beta1.MCPRemoteProxyPhaseFailed
proxy.Status.Message = fmt.Sprintf("Validation failed: %v", err)
meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{
Type: mcpv1beta1.ConditionTypeAuthConfigured,
Status: metav1.ConditionFalse,
Reason: mcpv1beta1.ConditionReasonAuthInvalid,
Message: err.Error(),
})
if statusErr := r.Status().Update(ctx, proxy); statusErr != nil {
ctxLogger.Error(statusErr, "Failed to update MCPRemoteProxy status after validation error")
}
return err
}
// Validate the GroupRef if specified
r.validateGroupRef(ctx, proxy)
// Handle MCPToolConfig
if err := r.handleToolConfig(ctx, proxy); err != nil {
ctxLogger.Error(err, "Failed to handle MCPToolConfig")
proxy.Status.Phase = mcpv1beta1.MCPRemoteProxyPhaseFailed
if statusErr := r.Status().Update(ctx, proxy); statusErr != nil {
ctxLogger.Error(statusErr, "Failed to update MCPRemoteProxy status after MCPToolConfig error")
}
return err
}
// Handle MCPTelemetryConfig
if err := r.handleTelemetryConfig(ctx, proxy); err != nil {
ctxLogger.Error(err, "Failed to handle MCPTelemetryConfig")
proxy.Status.Phase = mcpv1beta1.MCPRemoteProxyPhaseFailed
if statusErr := r.Status().Update(ctx, proxy); statusErr != nil {
ctxLogger.Error(statusErr, "Failed to update MCPRemoteProxy status after MCPTelemetryConfig error")
}
return err
}
// Handle MCPExternalAuthConfig
if err := r.handleExternalAuthConfig(ctx, proxy); err != nil {
ctxLogger.Error(err, "Failed to handle MCPExternalAuthConfig")
proxy.Status.Phase = mcpv1beta1.MCPRemoteProxyPhaseFailed
if statusErr := r.Status().Update(ctx, proxy); statusErr != nil {
ctxLogger.Error(statusErr, "Failed to update MCPRemoteProxy status after MCPExternalAuthConfig error")
}
return err
}
// Handle authServerRef config hash tracking
if err := r.handleAuthServerRef(ctx, proxy); err != nil {
ctxLogger.Error(err, "Failed to handle authServerRef")
proxy.Status.Phase = mcpv1beta1.MCPRemoteProxyPhaseFailed
if statusErr := r.Status().Update(ctx, proxy); statusErr != nil {
ctxLogger.Error(statusErr, "Failed to update MCPRemoteProxy status after authServerRef error")
}
return err
}
// Handle MCPOIDCConfig
if err := r.handleOIDCConfig(ctx, proxy); err != nil {
ctxLogger.Error(err, "Failed to handle MCPOIDCConfig")
proxy.Status.Phase = mcpv1beta1.MCPRemoteProxyPhaseFailed
if statusErr := r.Status().Update(ctx, proxy); statusErr != nil {
ctxLogger.Error(statusErr, "Failed to update MCPRemoteProxy status after MCPOIDCConfig error")
}
return err
}
return nil
}
// ensureAllResources ensures all Kubernetes resources for the proxy
func (r *MCPRemoteProxyReconciler) ensureAllResources(ctx context.Context, proxy *mcpv1beta1.MCPRemoteProxy) error {
ctxLogger := log.FromContext(ctx)
// Ensure RBAC resources
if err := r.ensureRBACResources(ctx, proxy); err != nil {
ctxLogger.Error(err, "Failed to ensure RBAC resources")
return err
}
// Ensure authorization ConfigMap
if err := r.ensureAuthzConfigMapForProxy(ctx, proxy); err != nil {
ctxLogger.Error(err, "Failed to ensure authorization ConfigMap")
return err
}
// Ensure RunConfig ConfigMap
if err := r.ensureRunConfigConfigMap(ctx, proxy); err != nil {
ctxLogger.Error(err, "Failed to ensure RunConfig ConfigMap")
return err
}
// Ensure Deployment
if result, err := r.ensureDeployment(ctx, proxy); err != nil {
return err
} else if result.RequeueAfter > 0 {
return nil
}
// Ensure Service
if result, err := r.ensureService(ctx, proxy); err != nil {
return err
} else if result.RequeueAfter > 0 {
return nil
}
// Update service URL in status
return r.ensureServiceURL(ctx, proxy)
}
// ensureAuthzConfigMapForProxy ensures the authorization ConfigMap for inline configuration
func (r *MCPRemoteProxyReconciler) ensureAuthzConfigMapForProxy(ctx context.Context, proxy *mcpv1beta1.MCPRemoteProxy) error {
authzLabels := labelsForMCPRemoteProxy(proxy.Name)
authzLabels[authzLabelKey] = authzLabelValueInline
return ctrlutil.EnsureAuthzConfigMap(
ctx, r.Client, r.Scheme, proxy, proxy.Namespace, proxy.Name, proxy.Spec.AuthzConfig, authzLabels,
)
}
// getRunConfigChecksum fetches the RunConfig ConfigMap checksum annotation for this proxy.
// Uses the shared RunConfigChecksumFetcher to maintain consistency with MCPServer.
func (r *MCPRemoteProxyReconciler) getRunConfigChecksum(
ctx context.Context, proxy *mcpv1beta1.MCPRemoteProxy,
) (string, error) {
if proxy == nil {
return "", fmt.Errorf("proxy cannot be nil")
}
fetcher := checksum.NewRunConfigChecksumFetcher(r.Client)
return fetcher.GetRunConfigChecksum(ctx, proxy.Namespace, proxy.Name)
}
// ensureDeployment ensures the Deployment exists and is up to date.
//
// This function coordinates deployment creation and updates, including:
// - Fetching the RunConfig ConfigMap checksum for pod restart triggering
// - Creating deployments when they don't exist
// - Updating deployments when configuration changes
// - Preserving replica counts for HPA compatibility
//
// If the RunConfig ConfigMap doesn't exist yet (e.g., during initial resource creation),
// the function returns an error that will trigger reconciliation requeue, allowing the
// ConfigMap to be created first in ensureAllResources().
func (r *MCPRemoteProxyReconciler) ensureDeployment(
ctx context.Context, proxy *mcpv1beta1.MCPRemoteProxy,
) (ctrl.Result, error) {
ctxLogger := log.FromContext(ctx)
// Fetch RunConfig ConfigMap checksum to include in pod template annotations
// This ensures pods restart when configuration changes
runConfigChecksum, err := r.getRunConfigChecksum(ctx, proxy)
if err != nil {
if errors.IsNotFound(err) {
// ConfigMap doesn't exist yet - it will be created by ensureRunConfigConfigMap
// before this function is called. If we still hit this, it's likely a timing
// issue with API server consistency. Requeue with a short delay to allow
// API server propagation.
ctxLogger.Info("RunConfig ConfigMap not found yet, will retry",
"proxy", proxy.Name, "namespace", proxy.Namespace)
return ctrl.Result{RequeueAfter: 5 * time.Second}, nil
}
// Other errors (missing annotation, empty checksum, etc.) are real problems
ctxLogger.Error(err, "Failed to get RunConfig checksum")
return ctrl.Result{}, err
}
deployment := &appsv1.Deployment{}
err = r.Get(ctx, types.NamespacedName{Name: proxy.Name, Namespace: proxy.Namespace}, deployment)
if errors.IsNotFound(err) {
dep := r.deploymentForMCPRemoteProxy(ctx, proxy, runConfigChecksum)
if dep == nil {
return ctrl.Result{}, fmt.Errorf("failed to create Deployment object")
}
ctxLogger.Info("Creating a new Deployment", "Deployment.Namespace", dep.Namespace, "Deployment.Name", dep.Name)
if err := r.Create(ctx, dep); err != nil {
ctxLogger.Error(err, "Failed to create new Deployment")
return ctrl.Result{}, err
}
return ctrl.Result{RequeueAfter: 0}, nil
} else if err != nil {
ctxLogger.Error(err, "Failed to get Deployment")
return ctrl.Result{}, err
}
// Deployment exists - check if it needs to be updated
if r.deploymentNeedsUpdate(ctx, deployment, proxy, runConfigChecksum) {
newDeployment := r.deploymentForMCPRemoteProxy(ctx, proxy, runConfigChecksum)
if newDeployment == nil {
return ctrl.Result{}, fmt.Errorf("failed to create updated Deployment object")
}
// Update the deployment spec but preserve replica count for HPA compatibility
deployment.Spec.Template = newDeployment.Spec.Template
deployment.Labels = newDeployment.Labels
deployment.Annotations = ctrlutil.MergeAnnotations(newDeployment.Annotations, deployment.Annotations)
ctxLogger.Info("Updating Deployment", "Deployment.Namespace", deployment.Namespace, "Deployment.Name", deployment.Name)
if err := r.Update(ctx, deployment); err != nil {
ctxLogger.Error(err, "Failed to update Deployment")
return ctrl.Result{}, err
}
return ctrl.Result{Requeue: true}, nil
}
return ctrl.Result{}, nil
}
// ensureService ensures the Service exists and is up to date
func (r *MCPRemoteProxyReconciler) ensureService(
ctx context.Context, proxy *mcpv1beta1.MCPRemoteProxy,
) (ctrl.Result, error) {
ctxLogger := log.FromContext(ctx)
serviceName := createProxyServiceName(proxy.Name)
service := &corev1.Service{}
err := r.Get(ctx, types.NamespacedName{Name: serviceName, Namespace: proxy.Namespace}, service)
if errors.IsNotFound(err) {
svc := r.serviceForMCPRemoteProxy(ctx, proxy)
if svc == nil {
return ctrl.Result{}, fmt.Errorf("failed to create Service object")
}
ctxLogger.Info("Creating a new Service", "Service.Namespace", svc.Namespace, "Service.Name", svc.Name)
if err := r.Create(ctx, svc); err != nil {
ctxLogger.Error(err, "Failed to create new Service")
return ctrl.Result{}, err
}
return ctrl.Result{RequeueAfter: 0}, nil
} else if err != nil {
ctxLogger.Error(err, "Failed to get Service")
return ctrl.Result{}, err
}
// Service exists - check if it needs to be updated
if r.serviceNeedsUpdate(service, proxy) {
newService := r.serviceForMCPRemoteProxy(ctx, proxy)
if newService == nil {
return ctrl.Result{}, fmt.Errorf("failed to create updated Service object")
}
service.Spec.Ports = newService.Spec.Ports
service.Spec.SessionAffinity = newService.Spec.SessionAffinity
service.Labels = newService.Labels
service.Annotations = newService.Annotations
ctxLogger.Info("Updating Service", "Service.Namespace", service.Namespace, "Service.Name", service.Name)
if err := r.Update(ctx, service); err != nil {
ctxLogger.Error(err, "Failed to update Service")
return ctrl.Result{}, err
}
return ctrl.Result{Requeue: true}, nil
}
return ctrl.Result{}, nil
}
// ensureServiceURL ensures the service URL is set in the status
func (r *MCPRemoteProxyReconciler) ensureServiceURL(ctx context.Context, proxy *mcpv1beta1.MCPRemoteProxy) error {
if proxy.Status.URL == "" {
// Note: createProxyServiceURL uses the remote-prefixed service name
proxy.Status.URL = createProxyServiceURL(proxy.Name, proxy.Namespace, int32(proxy.GetProxyPort()))
return r.Status().Update(ctx, proxy)
}
return nil
}
// validateSpec validates the MCPRemoteProxy spec
func (r *MCPRemoteProxyReconciler) validateSpec(ctx context.Context, proxy *mcpv1beta1.MCPRemoteProxy) error {
// Validate external auth config if referenced
if proxy.Spec.ExternalAuthConfigRef != nil {
externalAuthConfig, err := ctrlutil.GetExternalAuthConfigForMCPRemoteProxy(ctx, r.Client, proxy)
if err != nil {
return r.failValidation(proxy,
mcpv1beta1.ConditionReasonMCPRemoteProxyExternalAuthConfigFetchError,
fmt.Errorf("failed to validate external auth config: %w", err),
)
}
if externalAuthConfig == nil {
return r.failValidation(proxy,
mcpv1beta1.ConditionReasonMCPRemoteProxyExternalAuthConfigNotFound,
fmt.Errorf("referenced MCPExternalAuthConfig %s not found", proxy.Spec.ExternalAuthConfigRef.Name),
)
}
}
// Validate remote URL format (also rejects empty URLs)
if err := validation.ValidateRemoteURL(proxy.Spec.RemoteURL); err != nil {
return r.failValidation(proxy, mcpv1beta1.ConditionReasonRemoteURLInvalid, err)
}
// Validate inline Cedar policy syntax
if err := r.validateAuthzPolicySyntax(proxy); err != nil {
return r.failValidation(proxy, mcpv1beta1.ConditionReasonAuthzPolicySyntaxInvalid, err)
}
// Validate Kubernetes resource references (ConfigMaps, Secrets)
if err := r.validateK8sRefs(ctx, proxy); err != nil {
return err
}
// All validations passed
meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{
Type: mcpv1beta1.ConditionTypeConfigurationValid,
Status: metav1.ConditionTrue,
Reason: mcpv1beta1.ConditionReasonConfigurationValid,
Message: "All configuration validations passed",
ObservedGeneration: proxy.Generation,
})
return nil
}
// failValidation records a validation event, sets the ConfigurationValid condition to False,
// and returns the error. This consolidates the repeated validate → event → condition → return pattern.
func (r *MCPRemoteProxyReconciler) failValidation(proxy *mcpv1beta1.MCPRemoteProxy, reason string, err error) error {
r.recordValidationEvent(proxy, reason, err.Error())
setConfigurationInvalidCondition(proxy, reason, err.Error())
return err
}
// recordValidationEvent emits a Warning event for a validation failure.
func (r *MCPRemoteProxyReconciler) recordValidationEvent(proxy *mcpv1beta1.MCPRemoteProxy, reason, message string) {
if r.Recorder != nil {
r.Recorder.Eventf(proxy, nil, corev1.EventTypeWarning, reason, "ValidateSpec", message)
}
}
// setConfigurationInvalidCondition sets the ConfigurationValid condition to False.
func setConfigurationInvalidCondition(proxy *mcpv1beta1.MCPRemoteProxy, reason, message string) {
meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{
Type: mcpv1beta1.ConditionTypeConfigurationValid,
Status: metav1.ConditionFalse,
Reason: reason,
Message: message,
ObservedGeneration: proxy.Generation,
})
}
// validateAuthzPolicySyntax validates inline Cedar authorization policy syntax.
func (*MCPRemoteProxyReconciler) validateAuthzPolicySyntax(
proxy *mcpv1beta1.MCPRemoteProxy,
) error {
if proxy.Spec.AuthzConfig == nil ||
proxy.Spec.AuthzConfig.Type != mcpv1beta1.AuthzConfigTypeInline ||
proxy.Spec.AuthzConfig.Inline == nil {
return nil
}
return validation.ValidateCedarPolicies(proxy.Spec.AuthzConfig.Inline.Policies)
}
// validateK8sRefs validates that referenced ConfigMaps and Secrets exist.
func (r *MCPRemoteProxyReconciler) validateK8sRefs(
ctx context.Context, proxy *mcpv1beta1.MCPRemoteProxy,
) error {
// Check authz ConfigMap reference
if proxy.Spec.AuthzConfig != nil &&
proxy.Spec.AuthzConfig.Type == mcpv1beta1.AuthzConfigTypeConfigMap &&
proxy.Spec.AuthzConfig.ConfigMap != nil {
cm := &corev1.ConfigMap{}
cmName := proxy.Spec.AuthzConfig.ConfigMap.Name
err := r.Get(ctx, types.NamespacedName{
Name: cmName, Namespace: proxy.Namespace,
}, cm)
if err != nil {
if errors.IsNotFound(err) {
msg := fmt.Sprintf(
"authorization ConfigMap %q not found in namespace %q",
cmName, proxy.Namespace,
)
r.recordValidationEvent(
proxy,
mcpv1beta1.ConditionReasonAuthzConfigMapNotFound,
msg,
)
setConfigurationInvalidCondition(
proxy,
mcpv1beta1.ConditionReasonAuthzConfigMapNotFound,
msg,
)
return stderrors.New(msg)
}
ctxLogger := log.FromContext(ctx)
ctxLogger.Error(err, "Failed to fetch authorization ConfigMap", "name", cmName, "namespace", proxy.Namespace)
genericMsg := fmt.Sprintf("failed to fetch authorization ConfigMap %q", cmName)
r.recordValidationEvent(proxy, mcpv1beta1.ConditionReasonAuthzConfigMapNotFound, genericMsg)
setConfigurationInvalidCondition(proxy, mcpv1beta1.ConditionReasonAuthzConfigMapNotFound, genericMsg)
return stderrors.New(genericMsg)
}
}
// Check header Secret references
if proxy.Spec.HeaderForward != nil {
for _, headerRef := range proxy.Spec.HeaderForward.AddHeadersFromSecret {
if headerRef.ValueSecretRef == nil {
continue
}
secret := &corev1.Secret{}
secretName := headerRef.ValueSecretRef.Name
err := r.Get(ctx, types.NamespacedName{
Name: secretName, Namespace: proxy.Namespace,
}, secret)
if err != nil {
if errors.IsNotFound(err) {
msg := fmt.Sprintf(
"secret %q referenced for header %q not found in namespace %q",
secretName, headerRef.HeaderName, proxy.Namespace,
)
r.recordValidationEvent(
proxy,
mcpv1beta1.ConditionReasonHeaderSecretNotFound,
msg,
)
setConfigurationInvalidCondition(
proxy,
mcpv1beta1.ConditionReasonHeaderSecretNotFound,
msg,
)
return stderrors.New(msg)
}
ctxLogger := log.FromContext(ctx)
ctxLogger.Error(err, "Failed to fetch secret", "name", secretName, "namespace", proxy.Namespace)
genericMsg := fmt.Sprintf("failed to fetch secret %q for header %q", secretName, headerRef.HeaderName)
r.recordValidationEvent(proxy, mcpv1beta1.ConditionReasonHeaderSecretNotFound, genericMsg)
setConfigurationInvalidCondition(proxy, mcpv1beta1.ConditionReasonHeaderSecretNotFound, genericMsg)
return stderrors.New(genericMsg)
}
}
}
return nil
}
// handleToolConfig handles MCPToolConfig reference for an MCPRemoteProxy
func (r *MCPRemoteProxyReconciler) handleToolConfig(ctx context.Context, proxy *mcpv1beta1.MCPRemoteProxy) error {
ctxLogger := log.FromContext(ctx)
if proxy.Spec.ToolConfigRef == nil {
// Remove condition if ToolConfigRef is not set
meta.RemoveStatusCondition(&proxy.Status.Conditions, mcpv1beta1.ConditionTypeMCPRemoteProxyToolConfigValidated)
if proxy.Status.ToolConfigHash != "" {
proxy.Status.ToolConfigHash = ""
if err := r.Status().Update(ctx, proxy); err != nil {
return fmt.Errorf("failed to clear MCPToolConfig hash from status: %w", err)
}
}
return nil
}
toolConfig, err := ctrlutil.GetToolConfigForMCPRemoteProxy(ctx, r.Client, proxy)
if err != nil {
if errors.IsNotFound(err) {
meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{
Type: mcpv1beta1.ConditionTypeMCPRemoteProxyToolConfigValidated,
Status: metav1.ConditionFalse,
Reason: mcpv1beta1.ConditionReasonMCPRemoteProxyToolConfigNotFound,
Message: fmt.Sprintf("MCPToolConfig '%s' not found in namespace '%s'",
proxy.Spec.ToolConfigRef.Name, proxy.Namespace),
ObservedGeneration: proxy.Generation,
})
return fmt.Errorf("MCPToolConfig '%s' not found in namespace '%s'",
proxy.Spec.ToolConfigRef.Name, proxy.Namespace)
}
meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{
Type: mcpv1beta1.ConditionTypeMCPRemoteProxyToolConfigValidated,
Status: metav1.ConditionFalse,
Reason: mcpv1beta1.ConditionReasonMCPRemoteProxyToolConfigFetchError,
Message: "Failed to fetch MCPToolConfig",
ObservedGeneration: proxy.Generation,
})
return fmt.Errorf("failed to fetch MCPToolConfig: %w", err)
}
// ToolConfig found and valid
meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{
Type: mcpv1beta1.ConditionTypeMCPRemoteProxyToolConfigValidated,
Status: metav1.ConditionTrue,
Reason: mcpv1beta1.ConditionReasonMCPRemoteProxyToolConfigValid,
Message: fmt.Sprintf("MCPToolConfig '%s' is valid", toolConfig.Name),
ObservedGeneration: proxy.Generation,
})
if proxy.Status.ToolConfigHash != toolConfig.Status.ConfigHash {
ctxLogger.Info("MCPToolConfig has changed, updating MCPRemoteProxy",
"proxy", proxy.Name,
"toolconfig", toolConfig.Name,
"oldHash", proxy.Status.ToolConfigHash,
"newHash", toolConfig.Status.ConfigHash)
proxy.Status.ToolConfigHash = toolConfig.Status.ConfigHash
if err := r.Status().Update(ctx, proxy); err != nil {
return fmt.Errorf("failed to update MCPToolConfig hash in status: %w", err)
}
}
return nil
}
// handleTelemetryConfig validates and tracks the hash of the referenced MCPTelemetryConfig.
// It updates the MCPRemoteProxy status when the telemetry configuration changes.
func (r *MCPRemoteProxyReconciler) handleTelemetryConfig(ctx context.Context, proxy *mcpv1beta1.MCPRemoteProxy) error {
ctxLogger := log.FromContext(ctx)
if proxy.Spec.TelemetryConfigRef == nil {
// No MCPTelemetryConfig referenced, clear any stored hash and condition.
condType := mcpv1beta1.ConditionTypeMCPRemoteProxyTelemetryConfigRefValidated
condRemoved := meta.FindStatusCondition(proxy.Status.Conditions, condType) != nil
meta.RemoveStatusCondition(&proxy.Status.Conditions, condType)
if condRemoved || proxy.Status.TelemetryConfigHash != "" {
proxy.Status.TelemetryConfigHash = ""
if err := r.Status().Update(ctx, proxy); err != nil {
return fmt.Errorf("failed to clear MCPTelemetryConfig hash from status: %w", err)
}
}
return nil
}
// Get the referenced MCPTelemetryConfig
telemetryConfig, err := ctrlutil.GetTelemetryConfigForMCPRemoteProxy(ctx, r.Client, proxy)
if err != nil {
// Transient API error (not a NotFound)
meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{
Type: mcpv1beta1.ConditionTypeMCPRemoteProxyTelemetryConfigRefValidated,
Status: metav1.ConditionFalse,
Reason: mcpv1beta1.ConditionReasonMCPRemoteProxyTelemetryConfigRefFetchError,
Message: err.Error(),
ObservedGeneration: proxy.Generation,
})
return err
}
if telemetryConfig == nil {
// Resource genuinely does not exist
meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{
Type: mcpv1beta1.ConditionTypeMCPRemoteProxyTelemetryConfigRefValidated,
Status: metav1.ConditionFalse,
Reason: mcpv1beta1.ConditionReasonMCPRemoteProxyTelemetryConfigRefNotFound,
Message: fmt.Sprintf("MCPTelemetryConfig %s not found", proxy.Spec.TelemetryConfigRef.Name),
ObservedGeneration: proxy.Generation,
})
return fmt.Errorf("MCPTelemetryConfig %s not found", proxy.Spec.TelemetryConfigRef.Name)
}
// Validate that the MCPTelemetryConfig is valid (has Valid=True condition)
if err := telemetryConfig.Validate(); err != nil {
meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{
Type: mcpv1beta1.ConditionTypeMCPRemoteProxyTelemetryConfigRefValidated,
Status: metav1.ConditionFalse,
Reason: mcpv1beta1.ConditionReasonMCPRemoteProxyTelemetryConfigRefInvalid,
Message: fmt.Sprintf("MCPTelemetryConfig %s is invalid: %v", proxy.Spec.TelemetryConfigRef.Name, err),
ObservedGeneration: proxy.Generation,
})
return fmt.Errorf("MCPTelemetryConfig %s is invalid: %w", proxy.Spec.TelemetryConfigRef.Name, err)
}
// Detect whether the condition is transitioning to True (e.g. recovering from
// a transient error). Without this check the status update is skipped when the
// hash is unchanged, leaving a stale False condition.
condType := mcpv1beta1.ConditionTypeMCPRemoteProxyTelemetryConfigRefValidated
prevCondition := meta.FindStatusCondition(proxy.Status.Conditions, condType)
needsUpdate := prevCondition == nil || prevCondition.Status != metav1.ConditionTrue
meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{
Type: mcpv1beta1.ConditionTypeMCPRemoteProxyTelemetryConfigRefValidated,
Status: metav1.ConditionTrue,
Reason: mcpv1beta1.ConditionReasonMCPRemoteProxyTelemetryConfigRefValid,
Message: fmt.Sprintf("MCPTelemetryConfig %s is valid", proxy.Spec.TelemetryConfigRef.Name),
ObservedGeneration: proxy.Generation,
})
if proxy.Status.TelemetryConfigHash != telemetryConfig.Status.ConfigHash {
ctxLogger.Info("MCPTelemetryConfig has changed, updating MCPRemoteProxy",
"proxy", proxy.Name,
"telemetryConfig", telemetryConfig.Name,
"oldHash", proxy.Status.TelemetryConfigHash,
"newHash", telemetryConfig.Status.ConfigHash)
proxy.Status.TelemetryConfigHash = telemetryConfig.Status.ConfigHash
needsUpdate = true
}
if needsUpdate {
if err := r.Status().Update(ctx, proxy); err != nil {
return fmt.Errorf("failed to update MCPTelemetryConfig status: %w", err)
}
}
return nil
}
// handleExternalAuthConfig validates and tracks the hash of the referenced MCPExternalAuthConfig
func (r *MCPRemoteProxyReconciler) handleExternalAuthConfig(ctx context.Context, proxy *mcpv1beta1.MCPRemoteProxy) error {
ctxLogger := log.FromContext(ctx)
if proxy.Spec.ExternalAuthConfigRef == nil {
// Remove condition if ExternalAuthConfigRef is not set
meta.RemoveStatusCondition(&proxy.Status.Conditions, mcpv1beta1.ConditionTypeMCPRemoteProxyExternalAuthConfigValidated)
if proxy.Status.ExternalAuthConfigHash != "" {
proxy.Status.ExternalAuthConfigHash = ""
if err := r.Status().Update(ctx, proxy); err != nil {
return fmt.Errorf("failed to clear MCPExternalAuthConfig hash from status: %w", err)
}
}
return nil
}
externalAuthConfig, err := ctrlutil.GetExternalAuthConfigForMCPRemoteProxy(ctx, r.Client, proxy)
if err != nil {
if errors.IsNotFound(err) {
meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{
Type: mcpv1beta1.ConditionTypeMCPRemoteProxyExternalAuthConfigValidated,
Status: metav1.ConditionFalse,
Reason: mcpv1beta1.ConditionReasonMCPRemoteProxyExternalAuthConfigNotFound,
Message: fmt.Sprintf("MCPExternalAuthConfig '%s' not found in namespace '%s'",
proxy.Spec.ExternalAuthConfigRef.Name, proxy.Namespace),
ObservedGeneration: proxy.Generation,
})
return fmt.Errorf("MCPExternalAuthConfig '%s' not found in namespace '%s'",
proxy.Spec.ExternalAuthConfigRef.Name, proxy.Namespace)
}
meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{
Type: mcpv1beta1.ConditionTypeMCPRemoteProxyExternalAuthConfigValidated,
Status: metav1.ConditionFalse,
Reason: mcpv1beta1.ConditionReasonMCPRemoteProxyExternalAuthConfigFetchError,
Message: "Failed to fetch MCPExternalAuthConfig",
ObservedGeneration: proxy.Generation,
})
return fmt.Errorf("failed to fetch MCPExternalAuthConfig: %w", err)
}
// MCPRemoteProxy supports only single-upstream embedded auth server configs.
// Multi-upstream requires VirtualMCPServer.
if embeddedCfg := externalAuthConfig.Spec.EmbeddedAuthServer; embeddedCfg != nil && len(embeddedCfg.UpstreamProviders) > 1 {
meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{
Type: mcpv1beta1.ConditionTypeMCPRemoteProxyExternalAuthConfigValidated,
Status: metav1.ConditionFalse,
Reason: mcpv1beta1.ConditionReasonMCPRemoteProxyExternalAuthConfigMultiUpstream,
Message: fmt.Sprintf(
"MCPRemoteProxy supports only one upstream provider (found %d); "+
"use VirtualMCPServer for multi-upstream",
len(embeddedCfg.UpstreamProviders)),
ObservedGeneration: proxy.Generation,
})
return fmt.Errorf("MCPRemoteProxy %s/%s: embedded auth server has %d upstream providers, but only 1 is supported",
proxy.Namespace, proxy.Name, len(embeddedCfg.UpstreamProviders))
}
// ExternalAuthConfig found and valid
meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{
Type: mcpv1beta1.ConditionTypeMCPRemoteProxyExternalAuthConfigValidated,
Status: metav1.ConditionTrue,
Reason: mcpv1beta1.ConditionReasonMCPRemoteProxyExternalAuthConfigValid,
Message: fmt.Sprintf("MCPExternalAuthConfig '%s' is valid", externalAuthConfig.Name),
ObservedGeneration: proxy.Generation,
})
if proxy.Status.ExternalAuthConfigHash != externalAuthConfig.Status.ConfigHash {
ctxLogger.Info("MCPExternalAuthConfig has changed, updating MCPRemoteProxy",
"proxy", proxy.Name,
"externalAuthConfig", externalAuthConfig.Name,
"oldHash", proxy.Status.ExternalAuthConfigHash,
"newHash", externalAuthConfig.Status.ConfigHash)
proxy.Status.ExternalAuthConfigHash = externalAuthConfig.Status.ConfigHash
if err := r.Status().Update(ctx, proxy); err != nil {
return fmt.Errorf("failed to update MCPExternalAuthConfig hash in status: %w", err)
}
}
return nil
}
// handleAuthServerRef validates and tracks the hash of the referenced authServerRef config.
// It updates the MCPRemoteProxy status when the auth server configuration changes and sets
// the AuthServerRefValidated condition.
func (r *MCPRemoteProxyReconciler) handleAuthServerRef(ctx context.Context, proxy *mcpv1beta1.MCPRemoteProxy) error {
ctxLogger := log.FromContext(ctx)
if proxy.Spec.AuthServerRef == nil {
meta.RemoveStatusCondition(&proxy.Status.Conditions, mcpv1beta1.ConditionTypeMCPRemoteProxyAuthServerRefValidated)
if proxy.Status.AuthServerConfigHash != "" {
proxy.Status.AuthServerConfigHash = ""
if err := r.Status().Update(ctx, proxy); err != nil {
return fmt.Errorf("failed to clear authServerRef hash from status: %w", err)
}
}
return nil
}
// Only MCPExternalAuthConfig kind is supported
if proxy.Spec.AuthServerRef.Kind != "MCPExternalAuthConfig" {
meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{
Type: mcpv1beta1.ConditionTypeMCPRemoteProxyAuthServerRefValidated,
Status: metav1.ConditionFalse,
Reason: mcpv1beta1.ConditionReasonMCPRemoteProxyAuthServerRefInvalidKind,
Message: fmt.Sprintf("unsupported authServerRef kind %q: only MCPExternalAuthConfig is supported",
proxy.Spec.AuthServerRef.Kind),
ObservedGeneration: proxy.Generation,
})
return fmt.Errorf("unsupported authServerRef kind %q: only MCPExternalAuthConfig is supported",
proxy.Spec.AuthServerRef.Kind)
}
// Fetch the referenced MCPExternalAuthConfig
authConfig, err := ctrlutil.GetExternalAuthConfigByName(ctx, r.Client, proxy.Namespace, proxy.Spec.AuthServerRef.Name)
if err != nil {
if errors.IsNotFound(err) {
meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{
Type: mcpv1beta1.ConditionTypeMCPRemoteProxyAuthServerRefValidated,
Status: metav1.ConditionFalse,
Reason: mcpv1beta1.ConditionReasonMCPRemoteProxyAuthServerRefNotFound,
Message: fmt.Sprintf("MCPExternalAuthConfig '%s' not found in namespace '%s'",
proxy.Spec.AuthServerRef.Name, proxy.Namespace),
ObservedGeneration: proxy.Generation,
})
return fmt.Errorf("MCPExternalAuthConfig '%s' not found in namespace '%s'",
proxy.Spec.AuthServerRef.Name, proxy.Namespace)
}
meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{
Type: mcpv1beta1.ConditionTypeMCPRemoteProxyAuthServerRefValidated,
Status: metav1.ConditionFalse,
Reason: mcpv1beta1.ConditionReasonMCPRemoteProxyAuthServerRefFetchError,
Message: fmt.Sprintf("Failed to fetch MCPExternalAuthConfig '%s'", proxy.Spec.AuthServerRef.Name),
ObservedGeneration: proxy.Generation,
})
return fmt.Errorf("failed to get authServerRef MCPExternalAuthConfig %s: %w", proxy.Spec.AuthServerRef.Name, err)
}
// Validate the config type is embeddedAuthServer
if authConfig.Spec.Type != mcpv1beta1.ExternalAuthTypeEmbeddedAuthServer {
meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{
Type: mcpv1beta1.ConditionTypeMCPRemoteProxyAuthServerRefValidated,
Status: metav1.ConditionFalse,
Reason: mcpv1beta1.ConditionReasonMCPRemoteProxyAuthServerRefInvalidType,
Message: fmt.Sprintf("authServerRef '%s' has type %q, but only embeddedAuthServer is supported",
proxy.Spec.AuthServerRef.Name, authConfig.Spec.Type),
ObservedGeneration: proxy.Generation,
})
return fmt.Errorf("authServerRef '%s' has type %q, but only embeddedAuthServer is supported",
proxy.Spec.AuthServerRef.Name, authConfig.Spec.Type)
}
// MCPRemoteProxy supports only single-upstream embedded auth server configs
if embeddedCfg := authConfig.Spec.EmbeddedAuthServer; embeddedCfg != nil && len(embeddedCfg.UpstreamProviders) > 1 {
meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{
Type: mcpv1beta1.ConditionTypeMCPRemoteProxyAuthServerRefValidated,
Status: metav1.ConditionFalse,
Reason: mcpv1beta1.ConditionReasonMCPRemoteProxyAuthServerRefMultiUpstream,
Message: fmt.Sprintf("MCPRemoteProxy supports only one upstream provider (found %d); "+
"use VirtualMCPServer for multi-upstream",
len(embeddedCfg.UpstreamProviders)),
ObservedGeneration: proxy.Generation,
})
return fmt.Errorf("MCPRemoteProxy %s/%s: embedded auth server has %d upstream providers, "+
"but only 1 is supported; use VirtualMCPServer",
proxy.Namespace, proxy.Name, len(embeddedCfg.UpstreamProviders))
}
// AuthServerRef valid
meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{
Type: mcpv1beta1.ConditionTypeMCPRemoteProxyAuthServerRefValidated,
Status: metav1.ConditionTrue,
Reason: mcpv1beta1.ConditionReasonMCPRemoteProxyAuthServerRefValid,
Message: fmt.Sprintf("AuthServerRef '%s' is valid", authConfig.Name),
ObservedGeneration: proxy.Generation,
})
// Check if the config hash has changed
if proxy.Status.AuthServerConfigHash != authConfig.Status.ConfigHash {
ctxLogger.Info("authServerRef config has changed, updating MCPRemoteProxy",
"proxy", proxy.Name,
"authServerRef", authConfig.Name,
"oldHash", proxy.Status.AuthServerConfigHash,
"newHash", authConfig.Status.ConfigHash)
proxy.Status.AuthServerConfigHash = authConfig.Status.ConfigHash
if err := r.Status().Update(ctx, proxy); err != nil {
return fmt.Errorf("failed to update authServerRef hash in status: %w", err)
}
}
return nil
}
// handleOIDCConfig validates and tracks the hash of the referenced MCPOIDCConfig.
// It updates the MCPRemoteProxy status when the OIDC configuration changes and sets
// the OIDCConfigRefValidated condition.
func (r *MCPRemoteProxyReconciler) handleOIDCConfig(ctx context.Context, proxy *mcpv1beta1.MCPRemoteProxy) error {
ctxLogger := log.FromContext(ctx)
if proxy.Spec.OIDCConfigRef == nil {
// Remove condition if OIDCConfigRef is not set
meta.RemoveStatusCondition(&proxy.Status.Conditions, mcpv1beta1.ConditionOIDCConfigRefValidated)
if proxy.Status.OIDCConfigHash != "" {
proxy.Status.OIDCConfigHash = ""
if err := r.Status().Update(ctx, proxy); err != nil {
return fmt.Errorf("failed to clear MCPOIDCConfig hash from status: %w", err)
}
}
return nil
}
// Fetch and validate the referenced MCPOIDCConfig
oidcConfig, err := r.fetchAndValidateOIDCConfig(ctx, proxy)
if err != nil {
return err
}
// Update ReferencingWorkloads on the MCPOIDCConfig status
if err := r.updateOIDCConfigReferencingWorkloads(ctx, oidcConfig, proxy.Name); err != nil {
ctxLogger.Error(err, "Failed to update MCPOIDCConfig ReferencingWorkloads")
// Non-fatal: continue with reconciliation
}
// Detect whether the condition is transitioning to True (e.g. recovering from
// a transient error). Without this check the status update is skipped when the
// hash is unchanged, leaving a stale False condition (#4511).
prevCondition := meta.FindStatusCondition(proxy.Status.Conditions, mcpv1beta1.ConditionOIDCConfigRefValidated)
needsUpdate := prevCondition == nil || prevCondition.Status != metav1.ConditionTrue
meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{
Type: mcpv1beta1.ConditionOIDCConfigRefValidated,
Status: metav1.ConditionTrue,
Reason: mcpv1beta1.ConditionReasonOIDCConfigRefValid,
Message: fmt.Sprintf("MCPOIDCConfig %s is valid and ready", proxy.Spec.OIDCConfigRef.Name),
ObservedGeneration: proxy.Generation,
})
if proxy.Status.OIDCConfigHash != oidcConfig.Status.ConfigHash {
ctxLogger.Info("MCPOIDCConfig has changed, updating MCPRemoteProxy",
"proxy", proxy.Name,
"oidcConfig", oidcConfig.Name,
"oldHash", proxy.Status.OIDCConfigHash,
"newHash", oidcConfig.Status.ConfigHash)
proxy.Status.OIDCConfigHash = oidcConfig.Status.ConfigHash
needsUpdate = true
}
if needsUpdate {
if err := r.Status().Update(ctx, proxy); err != nil {
return fmt.Errorf("failed to update MCPOIDCConfig status: %w", err)
}
}
return nil
}
// fetchAndValidateOIDCConfig fetches the referenced MCPOIDCConfig, validates it is
// ready, and sets appropriate failure conditions on the MCPRemoteProxy if not.
func (r *MCPRemoteProxyReconciler) fetchAndValidateOIDCConfig(
ctx context.Context, proxy *mcpv1beta1.MCPRemoteProxy,
) (*mcpv1beta1.MCPOIDCConfig, error) {
ctxLogger := log.FromContext(ctx)
oidcConfig, err := ctrlutil.GetOIDCConfigForServer(ctx, r.Client, proxy.Namespace, proxy.Spec.OIDCConfigRef)
if err != nil {
meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{
Type: mcpv1beta1.ConditionOIDCConfigRefValidated,
Status: metav1.ConditionFalse,
Reason: mcpv1beta1.ConditionReasonOIDCConfigRefNotFound,
Message: fmt.Sprintf("MCPOIDCConfig %s not found: %v", proxy.Spec.OIDCConfigRef.Name, err),
ObservedGeneration: proxy.Generation,
})
if statusErr := r.Status().Update(ctx, proxy); statusErr != nil {
ctxLogger.Error(statusErr, "Failed to update status after MCPOIDCConfig lookup error")
}
return nil, err
}
if oidcConfig == nil {
meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{
Type: mcpv1beta1.ConditionOIDCConfigRefValidated,
Status: metav1.ConditionFalse,
Reason: mcpv1beta1.ConditionReasonOIDCConfigRefNotFound,
Message: fmt.Sprintf("MCPOIDCConfig %s not found", proxy.Spec.OIDCConfigRef.Name),
ObservedGeneration: proxy.Generation,
})
if statusErr := r.Status().Update(ctx, proxy); statusErr != nil {
ctxLogger.Error(statusErr, "Failed to update status after MCPOIDCConfig not found")
}
return nil, fmt.Errorf("MCPOIDCConfig %s not found", proxy.Spec.OIDCConfigRef.Name)
}
validCondition := meta.FindStatusCondition(oidcConfig.Status.Conditions, mcpv1beta1.ConditionTypeOIDCConfigValid)
if validCondition == nil || validCondition.Status != metav1.ConditionTrue {
msg := fmt.Sprintf("MCPOIDCConfig %s is not valid", proxy.Spec.OIDCConfigRef.Name)
if validCondition != nil {
msg = fmt.Sprintf("MCPOIDCConfig %s is not valid: %s", proxy.Spec.OIDCConfigRef.Name, validCondition.Message)
}
meta.SetStatusCondition(&proxy.Status.Conditions, metav1.Condition{
Type: mcpv1beta1.ConditionOIDCConfigRefValidated,
Status: metav1.ConditionFalse,
Reason: mcpv1beta1.ConditionReasonOIDCConfigRefNotValid,
Message: msg,
ObservedGeneration: proxy.Generation,
})
if statusErr := r.Status().Update(ctx, proxy); statusErr != nil {