← Back to Pull requests

Restrict tenant-controlled fields on infra LoadBalancer Services #422

Open
qinqon opened this pull request with 985 lines diff across 9 files
View on GitHub
qinqon qinqon commented on Sep 24, 2026 13:51 UTC
Author

What this PR does


Before this PR:

The provider copied tenant Service annotations, externalIPs, loadBalancerIP and healthCheckNodePort into an infra LoadBalancer Service. Source ranges were not forwarded, and only ports were reconciled.

Unrestricted copying allows tenant input to influence infra controllers and shared address allocation. The impact depends on the infra load-balancer implementation, network and admission policy.

After this PR:

  • No tenant annotations are copied by default. loadBalancer.allowedAnnotations permits exact keys chosen by the infra operator.

  • Provider ownership metadata, kubectl last-applied configuration and the legacy source-range annotation are excluded even if allowlisted. Other provider-specific annotation keys can be explicitly permitted.

  • externalIPs and tenant healthCheckNodePort are not copied. loadBalancerIP requires loadBalancer.allowTenantLoadBalancerIP: true.

  • Source ranges are validated and forwarded, with field precedence over the legacy annotation. Malformed input fails reconciliation instead of silently becoming unrestricted. Enforcement remains the responsibility of the infra implementation.

  • Previously mirrored annotation keys are tracked on the infra Service. Reconciliation updates/removes those keys while preserving other infra annotations, including MetalLB allocation metadata.

  • Infra-allocated NodePorts, health-check ports and any infra load-balancer class are preserved. Ports, source ranges, annotations and the requested-IP policy are reconciled; existing infra externalIPs are cleared.

  • Ignored IP requests produce Warning events on the tenant Service through a tenant-client recorder initialized in Cloud.Initialize.
  • Tenant loadBalancerClass is not propagated: the standard Kubernetes service controller skips Services with a class. It is not a way to select the backend for an infra mirror.

    Default configuration:

    loadBalancer:
      allowedAnnotations: []
      allowTenantLoadBalancerIP: false
    

    Why we need it and why it was done in this way

    Tenant administrators may be less trusted than infrastructure operators. The provider must explicitly control what crosses that boundary.

    The following tradeoffs were made:

  • An exact-key allowlist handles unknown infra controllers better than a list of known dangerous annotations.

  • Opt-in IP requests and annotation permissions preserve an explicitly delegated capability; they do not make arbitrary values safe. In particular, allowing MetalLB IPAM keys or requested IPs can restore tenant control over shared address allocation.

  • Tracking annotation keys supports removals and permission revocation without repeatedly deleting infra-controller metadata.
  • The following alternatives were considered:

  • Replacing all infra annotations would delete operator/controller-owned metadata.

  • Copying tenant loadBalancerClass cannot work through the standard service controller. Any future infra-class selection should be an operator-controlled feature.
  • Special notes for your reviewer


    N/S

    Checklist

  • Design: A VEP was considered and is present or not required

  • PR: The PR description explains behavior and migration limitations

  • Code: Changes and tests address the review findings

  • Refactor: Shared field handling and annotation ownership are explicit

  • Upgrade: Legacy migration limits and operator cleanup are documented

  • Testing: Unit/race tests pass and e2e coverage is added; live e2e execution is pending

  • Documentation: README configuration, behavior and migration guidance updated

  • Community: Announcement to kubevirt-dev was considered

  • AI Contributions: AI assistance is disclosed in the commit; contributor review under the KubeVirt AI Contribution Policy remains required
  • Release note


    ``release-note
    ACTION REQUIRED: Tenant LoadBalancer Service annotations and requested loadBalancerIP are no longer forwarded by default. Infrastructure operators must review existing mirrored Services for historical tenant annotations and address allocations, and explicitly configure any trusted annotation/IP permissions. Tenant externalIPs and healthCheckNodePort are no longer copied. Source ranges are validated and forwarded, subject to enforcement by the infrastructure implementation. Ignored IP requests emit Warning events on tenant Services. Tenant loadBalancerClass continues to opt out of the standard cloud-provider service controller; it is not propagated to infrastructure Services.
    ``

    Diff: 985 lines (+960 / -25) across 9 files Reviewer: aimnbrs Review duration: 18470m
    All Vouch review confidence checks passed
    Residual risk 0.07 = Change Risk (0.78) × (1 − Review Confidence (0.90)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.78 · 985 lines diff across 9 files
    0.78
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.89 · 5 substantive comment(s)
    0.89
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    90%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Sensitive Paths sensitive_paths
    0.078
    Real PR Conversation Timeline
    20 items
    kubevirt-prow[bot] kubevirt-prow[bot] commented on Sep 24, 2026 13:51 UTC
    Bot

    [APPROVALNOTIFIER] This PR is NOT APPROVED

    This pull-request has been approved by:
    Once this PR has been reviewed and has the lgtm label, please assign rmohr for approval. For more information see the Code Review Process.

    The full list of commands accepted by this bot can be found here.

    <details open>
    Needs approval from an approver in each of these files:

  • OWNERS
  • Approvers can indicate their approval by writing /approve in a comment
    Approvers can cancel approval by writing /approve cancel in a comment
    </details>
    <!-- META={"approvers":["rmohr"]} -->

    aimnbrs aimnbrs commented on Sep 25, 2026 00:09 UTC
    Reviewer

    Thanks for picking this up — the allowlist and the clean-up on update match what we had in mind. A few points inline: three about behaviour and a nit.

    aimnbrs aimnbrs commented on code on Sep 25, 2026 00:09 UTC
    Code Review
    pkg/provider/loadbalancer.go:1
    @@ -232,6 +276,92 @@ func (lb *loadbalancer) createLoadBalancerService(ctx context.Context, lbName st
     	return lbService, nil
     }
     
    +// allowedAnnotations returns the subset of the tenant Service's annotations that
    +// the infra operator has explicitly allowlisted via LoadBalancerConfig.
    +// System annotations (kubernetes.io / k8s.io) are never copied, even when they
    +// appear in the allowlist, so that tenant metadata such as
    +// kubectl.kubernetes.io/last-applied-configuration never leaks into the infra
    +// cluster. Returns nil when nothing is copied.
    +func (lb *loadbalancer) allowedAnnotations(service *corev1.Service) map[string]string {
    +	if len(lb.config.AllowedAnnotations) == 0 || len(service.Annotations) == 0 {
    +		return nil
    +	}
    +	var annotations map[string]string
    +	for _, key := range lb.config.AllowedAnnotations {
    +		if isSystemAnnotation(key) {
    +			klog.Warningf("Ignoring system annotation %q in load balancer allowlist", key)
    +			continue
    +		}
    +		val, ok := service.Annotations[key]
    +		if !ok {
    +			continue
    +		}
    +		if annotations == nil {
    +			annotations = map[string]string{}
    +		}
    +		annotations[key] = val
    +	}
    +	return annotations
    +}
    +
    +// isSystemAnnotation reports whether an annotation key belongs to a Kubernetes
    +// system namespace and must never be copied across the tenant/infra boundary.
    +func isSystemAnnotation(key string) bool {
    +	return strings.Contains(key, "kubernetes.io/") || strings.Contains(key, "k8s.io/")
    +}
    +
    +// applyTenantLoadBalancerFields copies only the tenant Service fields that are
    +// safe to honour on the infra Service:
    +//   - spec.loadBalancerClass: a typed, immutable backend selector,
    +//   - spec.loadBalancerSourceRanges (or the legacy annotation): a firewall
    +//     restriction, so it must not be silently dropped.
    +//
    +// Fields that let a tenant control shared infra resources are deliberately not
    +// copied: spec.externalIPs (CVE-2020-8554 traffic interception) and
    +// spec.healthCheckNodePort (belongs to the infra Service's own allocation) are
    +// always ignored; spec.loadBalancerIP is ignored unless the operator opts in
    +// via AllowTenantLoadBalancerIP.
    +func (lb *loadbalancer) applyTenantLoadBalancerFields(service, lbService *corev1.Service) {
    +	if service.Spec.LoadBalancerClass != nil {
    +		lbService.Spec.LoadBalancerClass = service.Spec.LoadBalancerClass

    The service controller in k8s.io/cloud-provider skips Services that set a class: wantsLoadBalancer (controllers/service/controller.go, v0.37.0 as vendored here) returns false when spec.loadBalancerClass is set, so EnsureLoadBalancer/UpdateLoadBalancer are never called for them. The class can't reach the infra Service, and a tenant following the README to pick a backend with loadBalancerClass gets no infra Service at all.

    Unless I'm missing another path, I'd drop the class propagation and that advice; if a backend choice is needed, an operator option that sets the class on every infra Service keeps it with the infra side.

    aimnbrs aimnbrs commented on code on Sep 25, 2026 00:09 UTC
    Code Review
    pkg/provider/loadbalancer.go:1
    @@ -141,17 +147,62 @@ func (lb *loadbalancer) UpdateLoadBalancer(ctx context.Context, clusterName stri
     	}
     
     	ports := lb.createLoadBalancerServicePorts(service)
    -	// LoadBalancer already exist, update the ports if changed
    -	return lb.updateLoadBalancerServicePorts(ctx, &lbService, ports)
    +	// LoadBalancer already exists, reconcile the mirrored fields if changed
    +	return lb.reconcileLoadBalancerService(ctx, service, &lbService, ports)
     }
     
    -func (lb *loadbalancer) updateLoadBalancerServicePorts(ctx context.Context, lbService *corev1.Service, ports []corev1.ServicePort) error {
    +// reconcileLoadBalancerService updates an existing infra Service so that its
    +// ports and the security-relevant mirrored fields (allowlisted annotations,
    +// loadBalancerClass, loadBalancerSourceRanges, loadBalancerIP) match what the
    +// tenant Service is currently allowed to request. It also strips fields that
    +// must never be present (externalIPs), which cleans up infra Services created by
    +// older builds that copied tenant fields verbatim.
    +func (lb *loadbalancer) reconcileLoadBalancerService(ctx context.Context, service, lbService *corev1.Service, ports []corev1.ServicePort) error {
    +	changed := false
    +
     	if !equality.Semantic.DeepEqual(ports, lbService.Spec.Ports) {
     		lbService.Spec.Ports = ports
    -		if err := lb.client.Update(ctx, lbService); err != nil {
    -			klog.Errorf("Failed to update LoadBalancer service: %v", err)
    -			return err
    -		}
    +		changed = true
    +	}
    +
    +	desiredAnnotations := lb.allowedAnnotations(service)
    +	if !equality.Semantic.DeepEqual(desiredAnnotations, lbService.Annotations) {
    +		lbService.Annotations = desiredAnnotations

    This replaces every annotation on the infra Service, including ones written in the infra cluster — MetalLB sets metallb.io/ip-allocated-from-pool on each Service it assigns, and operators may annotate these Services too. Each tenant-side reconcile would remove them and the infra controller write them back.

    Removing only the keys the tenant Service carries that are not allowlisted (or recording the mirrored keys on the infra Service) would still clean Services from older builds without touching the infra side's.

    aimnbrs aimnbrs commented on code on Sep 25, 2026 00:09 UTC
    Code Review
    pkg/provider/loadbalancer.go:1
    @@ -232,6 +276,92 @@ func (lb *loadbalancer) createLoadBalancerService(ctx context.Context, lbName st
     	return lbService, nil
     }
     
    +// allowedAnnotations returns the subset of the tenant Service's annotations that
    +// the infra operator has explicitly allowlisted via LoadBalancerConfig.
    +// System annotations (kubernetes.io / k8s.io) are never copied, even when they
    +// appear in the allowlist, so that tenant metadata such as
    +// kubectl.kubernetes.io/last-applied-configuration never leaks into the infra
    +// cluster. Returns nil when nothing is copied.
    +func (lb *loadbalancer) allowedAnnotations(service *corev1.Service) map[string]string {
    +	if len(lb.config.AllowedAnnotations) == 0 || len(service.Annotations) == 0 {
    +		return nil
    +	}
    +	var annotations map[string]string
    +	for _, key := range lb.config.AllowedAnnotations {
    +		if isSystemAnnotation(key) {
    +			klog.Warningf("Ignoring system annotation %q in load balancer allowlist", key)
    +			continue
    +		}
    +		val, ok := service.Annotations[key]
    +		if !ok {
    +			continue
    +		}
    +		if annotations == nil {
    +			annotations = map[string]string{}
    +		}
    +		annotations[key] = val
    +	}
    +	return annotations
    +}
    +
    +// isSystemAnnotation reports whether an annotation key belongs to a Kubernetes
    +// system namespace and must never be copied across the tenant/infra boundary.
    +func isSystemAnnotation(key string) bool {
    +	return strings.Contains(key, "kubernetes.io/") || strings.Contains(key, "k8s.io/")
    +}
    +
    +// applyTenantLoadBalancerFields copies only the tenant Service fields that are
    +// safe to honour on the infra Service:
    +//   - spec.loadBalancerClass: a typed, immutable backend selector,
    +//   - spec.loadBalancerSourceRanges (or the legacy annotation): a firewall
    +//     restriction, so it must not be silently dropped.
    +//
    +// Fields that let a tenant control shared infra resources are deliberately not
    +// copied: spec.externalIPs (CVE-2020-8554 traffic interception) and
    +// spec.healthCheckNodePort (belongs to the infra Service's own allocation) are
    +// always ignored; spec.loadBalancerIP is ignored unless the operator opts in
    +// via AllowTenantLoadBalancerIP.
    +func (lb *loadbalancer) applyTenantLoadBalancerFields(service, lbService *corev1.Service) {
    +	if service.Spec.LoadBalancerClass != nil {
    +		lbService.Spec.LoadBalancerClass = service.Spec.LoadBalancerClass
    +	}
    +
    +	lbService.Spec.LoadBalancerSourceRanges = tenantLoadBalancerSourceRanges(service)
    +
    +	if len(service.Spec.ExternalIPs) > 0 {
    +		klog.Warningf("Ignoring spec.externalIPs %v requested by tenant Service %s/%s: externalIPs are not propagated to the infra cluster", service.Spec.ExternalIPs, service.Namespace, service.Name)

    With a hosted control plane the provider's log is on the infra side, so the tenant cluster administrator never sees these warnings — their Service just gets a different address, or no external IPs. A Warning event on the tenant Service (a recorder on the tenant client in Initialize) would tell them why. Same for the loadBalancerIP case below.

    aimnbrs aimnbrs commented on code on Sep 25, 2026 00:09 UTC
    Code Review
    pkg/provider/loadbalancer.go:1
    @@ -232,6 +276,92 @@ func (lb *loadbalancer) createLoadBalancerService(ctx context.Context, lbName st
     	return lbService, nil
     }
     
    +// allowedAnnotations returns the subset of the tenant Service's annotations that
    +// the infra operator has explicitly allowlisted via LoadBalancerConfig.
    +// System annotations (kubernetes.io / k8s.io) are never copied, even when they
    +// appear in the allowlist, so that tenant metadata such as
    +// kubectl.kubernetes.io/last-applied-configuration never leaks into the infra
    +// cluster. Returns nil when nothing is copied.
    +func (lb *loadbalancer) allowedAnnotations(service *corev1.Service) map[string]string {
    +	if len(lb.config.AllowedAnnotations) == 0 || len(service.Annotations) == 0 {
    +		return nil
    +	}
    +	var annotations map[string]string
    +	for _, key := range lb.config.AllowedAnnotations {
    +		if isSystemAnnotation(key) {
    +			klog.Warningf("Ignoring system annotation %q in load balancer allowlist", key)
    +			continue
    +		}
    +		val, ok := service.Annotations[key]
    +		if !ok {
    +			continue
    +		}
    +		if annotations == nil {
    +			annotations = map[string]string{}
    +		}
    +		annotations[key] = val
    +	}
    +	return annotations
    +}
    +
    +// isSystemAnnotation reports whether an annotation key belongs to a Kubernetes
    +// system namespace and must never be copied across the tenant/infra boundary.
    +func isSystemAnnotation(key string) bool {
    +	return strings.Contains(key, "kubernetes.io/") || strings.Contains(key, "k8s.io/")

    Nit: strings.Contains also matches e.g. notkubernetes.io/x. Comparing the key's prefix (== "kubernetes.io" or HasSuffix(".kubernetes.io"), same for k8s.io) is exact.

    qinqon qinqon commented on code on Sep 25, 2026 08:10 UTC
    Code Review
    pkg/provider/loadbalancer.go:1
    @@ -141,17 +147,62 @@ func (lb *loadbalancer) UpdateLoadBalancer(ctx context.Context, clusterName stri
     	}
     
     	ports := lb.createLoadBalancerServicePorts(service)
    -	// LoadBalancer already exist, update the ports if changed
    -	return lb.updateLoadBalancerServicePorts(ctx, &lbService, ports)
    +	// LoadBalancer already exists, reconcile the mirrored fields if changed
    +	return lb.reconcileLoadBalancerService(ctx, service, &lbService, ports)
     }
     
    -func (lb *loadbalancer) updateLoadBalancerServicePorts(ctx context.Context, lbService *corev1.Service, ports []corev1.ServicePort) error {
    +// reconcileLoadBalancerService updates an existing infra Service so that its
    +// ports and the security-relevant mirrored fields (allowlisted annotations,
    +// loadBalancerClass, loadBalancerSourceRanges, loadBalancerIP) match what the
    +// tenant Service is currently allowed to request. It also strips fields that
    +// must never be present (externalIPs), which cleans up infra Services created by
    +// older builds that copied tenant fields verbatim.
    +func (lb *loadbalancer) reconcileLoadBalancerService(ctx context.Context, service, lbService *corev1.Service, ports []corev1.ServicePort) error {
    +	changed := false
    +
     	if !equality.Semantic.DeepEqual(ports, lbService.Spec.Ports) {
     		lbService.Spec.Ports = ports
    -		if err := lb.client.Update(ctx, lbService); err != nil {
    -			klog.Errorf("Failed to update LoadBalancer service: %v", err)
    -			return err
    -		}
    +		changed = true
    +	}
    +
    +	desiredAnnotations := lb.allowedAnnotations(service)
    +	if !equality.Semantic.DeepEqual(desiredAnnotations, lbService.Annotations) {
    +		lbService.Annotations = desiredAnnotations

    Addressed in d2a7fd8ba by tracking mirrored keys in an infra-only annotation and reconciling only owned keys. Tests cover preserving MetalLB/operator annotations, tenant changes/removal, allowlist revocation and idempotency. Legacy Services have no provenance: the first reconcile conservatively cleans keys whose values still match the tenant, then records ownership. Historical keys no longer matching require operator audit/manual cleanup; identical independently authored annotations remain ambiguous. These migration limits are documented rather than promising complete automatic cleanup. Added an e2e preservation scenario (compiled locally; live execution pending CI).

    qinqon qinqon commented on code on Sep 25, 2026 08:10 UTC
    Code Review
    pkg/provider/loadbalancer.go:1
    @@ -232,6 +276,92 @@ func (lb *loadbalancer) createLoadBalancerService(ctx context.Context, lbName st
     	return lbService, nil
     }
     
    +// allowedAnnotations returns the subset of the tenant Service's annotations that
    +// the infra operator has explicitly allowlisted via LoadBalancerConfig.
    +// System annotations (kubernetes.io / k8s.io) are never copied, even when they
    +// appear in the allowlist, so that tenant metadata such as
    +// kubectl.kubernetes.io/last-applied-configuration never leaks into the infra
    +// cluster. Returns nil when nothing is copied.
    +func (lb *loadbalancer) allowedAnnotations(service *corev1.Service) map[string]string {
    +	if len(lb.config.AllowedAnnotations) == 0 || len(service.Annotations) == 0 {
    +		return nil
    +	}
    +	var annotations map[string]string
    +	for _, key := range lb.config.AllowedAnnotations {
    +		if isSystemAnnotation(key) {
    +			klog.Warningf("Ignoring system annotation %q in load balancer allowlist", key)
    +			continue
    +		}
    +		val, ok := service.Annotations[key]
    +		if !ok {
    +			continue
    +		}
    +		if annotations == nil {
    +			annotations = map[string]string{}
    +		}
    +		annotations[key] = val
    +	}
    +	return annotations
    +}
    +
    +// isSystemAnnotation reports whether an annotation key belongs to a Kubernetes
    +// system namespace and must never be copied across the tenant/infra boundary.
    +func isSystemAnnotation(key string) bool {
    +	return strings.Contains(key, "kubernetes.io/") || strings.Contains(key, "k8s.io/")
    +}
    +
    +// applyTenantLoadBalancerFields copies only the tenant Service fields that are
    +// safe to honour on the infra Service:
    +//   - spec.loadBalancerClass: a typed, immutable backend selector,
    +//   - spec.loadBalancerSourceRanges (or the legacy annotation): a firewall
    +//     restriction, so it must not be silently dropped.
    +//
    +// Fields that let a tenant control shared infra resources are deliberately not
    +// copied: spec.externalIPs (CVE-2020-8554 traffic interception) and
    +// spec.healthCheckNodePort (belongs to the infra Service's own allocation) are
    +// always ignored; spec.loadBalancerIP is ignored unless the operator opts in
    +// via AllowTenantLoadBalancerIP.
    +func (lb *loadbalancer) applyTenantLoadBalancerFields(service, lbService *corev1.Service) {
    +	if service.Spec.LoadBalancerClass != nil {
    +		lbService.Spec.LoadBalancerClass = service.Spec.LoadBalancerClass

    Addressed in d2a7fd8ba. Removed tenant class propagation and the direct-call test that bypassed the service controller. README and PR description now explain that tenant loadBalancerClass opts out of the standard controller, rather than selecting the infra backend. Existing infra classes are preserved on reconciliation; an operator-configured infra class is outside this fix.

    qinqon qinqon commented on code on Sep 25, 2026 08:10 UTC
    Code Review
    pkg/provider/loadbalancer.go:1
    @@ -232,6 +276,92 @@ func (lb *loadbalancer) createLoadBalancerService(ctx context.Context, lbName st
     	return lbService, nil
     }
     
    +// allowedAnnotations returns the subset of the tenant Service's annotations that
    +// the infra operator has explicitly allowlisted via LoadBalancerConfig.
    +// System annotations (kubernetes.io / k8s.io) are never copied, even when they
    +// appear in the allowlist, so that tenant metadata such as
    +// kubectl.kubernetes.io/last-applied-configuration never leaks into the infra
    +// cluster. Returns nil when nothing is copied.
    +func (lb *loadbalancer) allowedAnnotations(service *corev1.Service) map[string]string {
    +	if len(lb.config.AllowedAnnotations) == 0 || len(service.Annotations) == 0 {
    +		return nil
    +	}
    +	var annotations map[string]string
    +	for _, key := range lb.config.AllowedAnnotations {
    +		if isSystemAnnotation(key) {
    +			klog.Warningf("Ignoring system annotation %q in load balancer allowlist", key)
    +			continue
    +		}
    +		val, ok := service.Annotations[key]
    +		if !ok {
    +			continue
    +		}
    +		if annotations == nil {
    +			annotations = map[string]string{}
    +		}
    +		annotations[key] = val
    +	}
    +	return annotations
    +}
    +
    +// isSystemAnnotation reports whether an annotation key belongs to a Kubernetes
    +// system namespace and must never be copied across the tenant/infra boundary.
    +func isSystemAnnotation(key string) bool {
    +	return strings.Contains(key, "kubernetes.io/") || strings.Contains(key, "k8s.io/")
    +}
    +
    +// applyTenantLoadBalancerFields copies only the tenant Service fields that are
    +// safe to honour on the infra Service:
    +//   - spec.loadBalancerClass: a typed, immutable backend selector,
    +//   - spec.loadBalancerSourceRanges (or the legacy annotation): a firewall
    +//     restriction, so it must not be silently dropped.
    +//
    +// Fields that let a tenant control shared infra resources are deliberately not
    +// copied: spec.externalIPs (CVE-2020-8554 traffic interception) and
    +// spec.healthCheckNodePort (belongs to the infra Service's own allocation) are
    +// always ignored; spec.loadBalancerIP is ignored unless the operator opts in
    +// via AllowTenantLoadBalancerIP.
    +func (lb *loadbalancer) applyTenantLoadBalancerFields(service, lbService *corev1.Service) {
    +	if service.Spec.LoadBalancerClass != nil {
    +		lbService.Spec.LoadBalancerClass = service.Spec.LoadBalancerClass
    +	}
    +
    +	lbService.Spec.LoadBalancerSourceRanges = tenantLoadBalancerSourceRanges(service)
    +
    +	if len(service.Spec.ExternalIPs) > 0 {
    +		klog.Warningf("Ignoring spec.externalIPs %v requested by tenant Service %s/%s: externalIPs are not propagated to the infra cluster", service.Spec.ExternalIPs, service.Namespace, service.Name)

    Addressed in d2a7fd8ba. Cloud.Initialize now creates a recorder with the tenant client builder, using the existing service-controller identity and shutting down the broadcaster on stop. Both creation and reconciliation emit tenant Service Warning events for ignored externalIPs/loadBalancerIP. Tests verify tenant-client event delivery, both reconciliation entrypoints, and no warning for permitted IP requests; the new e2e scenario checks the tenant event too.

    qinqon qinqon commented on code on Sep 25, 2026 08:10 UTC
    Code Review
    pkg/provider/loadbalancer.go:1
    @@ -232,6 +276,92 @@ func (lb *loadbalancer) createLoadBalancerService(ctx context.Context, lbName st
     	return lbService, nil
     }
     
    +// allowedAnnotations returns the subset of the tenant Service's annotations that
    +// the infra operator has explicitly allowlisted via LoadBalancerConfig.
    +// System annotations (kubernetes.io / k8s.io) are never copied, even when they
    +// appear in the allowlist, so that tenant metadata such as
    +// kubectl.kubernetes.io/last-applied-configuration never leaks into the infra
    +// cluster. Returns nil when nothing is copied.
    +func (lb *loadbalancer) allowedAnnotations(service *corev1.Service) map[string]string {
    +	if len(lb.config.AllowedAnnotations) == 0 || len(service.Annotations) == 0 {
    +		return nil
    +	}
    +	var annotations map[string]string
    +	for _, key := range lb.config.AllowedAnnotations {
    +		if isSystemAnnotation(key) {
    +			klog.Warningf("Ignoring system annotation %q in load balancer allowlist", key)
    +			continue
    +		}
    +		val, ok := service.Annotations[key]
    +		if !ok {
    +			continue
    +		}
    +		if annotations == nil {
    +			annotations = map[string]string{}
    +		}
    +		annotations[key] = val
    +	}
    +	return annotations
    +}
    +
    +// isSystemAnnotation reports whether an annotation key belongs to a Kubernetes
    +// system namespace and must never be copied across the tenant/infra boundary.
    +func isSystemAnnotation(key string) bool {
    +	return strings.Contains(key, "kubernetes.io/") || strings.Contains(key, "k8s.io/")

    Addressed in d2a7fd8ba by removing the blanket namespace ban altogether. That ban also prevented operators from explicitly allowing legitimate service.beta.kubernetes.io provider keys. Only the ownership annotation, kubectl last-applied configuration and the separately validated legacy source-range annotation are excluded. Tests cover notkubernetes.io/x, a provider-specific Kubernetes-prefixed key, and exclusion of reserved metadata even when allowlisted.

    Copilot Copilot commented on code on Sep 25, 2026 08:27 UTC
    Code Review
    pkg/provider/cloud.go:1
    @@ -161,6 +179,20 @@ func kubevirtCloudProviderFactory(config io.Reader) (cloudprovider.Interface, er
     // Initialize provides the Cloud with a kubernetes client builder and may spawn goroutines
     // to perform housekeeping activities within the Cloud provider.
     func (c *Cloud) Initialize(clientBuilder cloudprovider.ControllerClientBuilder, stop <-chan struct{}) {
    +	if !c.config.LoadBalancer.Enabled {
    +		return
    +	}
    +	// The builder provides a tenant client, unlike c.client which targets infra.
    +	// Reuse the service controller identity, which already has event permissions
    +	// when the CCM uses per-controller service-account credentials.
    +	tenantClient := clientBuilder.ClientOrDie("service-controller")
    +	broadcaster := record.NewBroadcaster()
    +	broadcaster.StartRecordingToSink(&typedcorev1.EventSinkImpl{Interface: tenantClient.CoreV1().Events("")})

    The new recorder uses the tenant client under the service-controller identity, but the repository's packaged tenant RBAC (config/rbac/kccm_role.yaml:24-44) grants this controller access to services/nodes and no access to events. With the default manager.yaml deployment (and also when the builder reuses the CCM credentials), every Event write will be forbidden, so the promised LoadBalancerIPIgnored/ExternalIPsIgnored warnings will never reach the tenant Service. Add the required event permissions for the identity actually used here, or wire this to an already-authorized tenant event recorder.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Sep 25, 2026 08:27 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    Copilot review overview

    🟡 Changes recommended

    Tenant event recording lacks the required RBAC permissions, so warning events will be forbidden.

    Get a fresh assessment by requesting another Copilot review.

    Review effort: Lite
    Findings: 1 <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture>

    <details open>
    <summary><strong>Open (1)</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Tenant RBAC lacks event permissions for recorder warnings](#discussion_r4102677342) · New

  • </details>

    <details>
    <summary><strong>What changed in this PR</strong></summary>

    Restricts tenant-controlled fields mirrored to infrastructure LoadBalancer Services while preserving operator-owned state and adding validation, events, documentation, and tests.

    Changes:

  • Adds annotation allowlisting and opt-in tenant loadBalancerIP.

  • Validates source ranges and removes unsafe field propagation.

  • Tracks mirrored annotations and preserves infrastructure metadata.

  • Adds warning events, unit tests, and e2e coverage.
  • | File | Summary |
    |---|---|
    | test/​e2e/​cloud_provider_kubevirt/​load_balancer_test.go | Adds end-to-end reconciliation coverage. |
    | README.md | Documents configuration, behavior, and migration guidance. |
    | pkg/​provider/​loadbalancer.go | Implements restricted field reconciliation. |
    | pkg/​provider/​loadbalancer_test.go | Extends LoadBalancer tests. |
    | pkg/​provider/​loadbalancer_fields_test.go | Tests field validation and annotation ownership. |
    | pkg/​provider/​cloud.go | Initializes tenant event recording. |
    | pkg/​provider/​cloud_test.go | Tests configuration defaults. |
    | pkg/​provider/​cloud_events_test.go | Tests tenant warning events. |
    </details>

    ---

    💡 <a href="/kubevirt/cloud-provider-kubevirt/new/main?filename=.github/skills/code-review/SKILL.md" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Add a code-review agent skill</a> or configure MCP servers for context-aware, tailored reviews. <a href="https://docs.github.com/copilot/how-tos/use-copilot-agents/request-a-code-review/use-code-review?tool=webui#mcp-servers-and-agent-skills" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Learn more in the docs.</a>

    qinqon qinqon commented on code on Sep 25, 2026 11:23 UTC
    Code Review
    pkg/provider/cloud.go:1
    @@ -161,6 +179,20 @@ func kubevirtCloudProviderFactory(config io.Reader) (cloudprovider.Interface, er
     // Initialize provides the Cloud with a kubernetes client builder and may spawn goroutines
     // to perform housekeeping activities within the Cloud provider.
     func (c *Cloud) Initialize(clientBuilder cloudprovider.ControllerClientBuilder, stop <-chan struct{}) {
    +	if !c.config.LoadBalancer.Enabled {
    +		return
    +	}
    +	// The builder provides a tenant client, unlike c.client which targets infra.
    +	// Reuse the service controller identity, which already has event permissions
    +	// when the CCM uses per-controller service-account credentials.
    +	tenantClient := clientBuilder.ClientOrDie("service-controller")
    +	broadcaster := record.NewBroadcaster()
    +	broadcaster.StartRecordingToSink(&typedcorev1.EventSinkImpl{Interface: tenantClient.CoreV1().Events("")})

    Addressed in b0879bfe6 with a separate tenant-side event RBAC example (config/tenant-rbac/events.yaml), credential-specific documentation, and an e2e authorization check using the deployed CCM tenant kubeconfig. The current core Event recorder uses create and patch, so the supplemental ClusterRole grants those verbs across tenant namespaces. Operators must adjust its binding subject to their actual tenant identity. One distinction: config/rbac is applied alongside the provider in the infrastructure cluster, whereas manager.yaml uses an explicit tenant kubeconfig; adding permissions to the infra Role would not authorize tenant writes. Shared credentials use the tenant kubeconfig identity; per-controller credentials use service-controller. The initialization comment now makes that requirement explicit. Unit tests, lint and e2e compilation pass; live e2e remains for CI.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Sep 25, 2026 11:29 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    Copilot review overview

    🔵 Needs a closer look

    Allowlisted annotation changes may leave stale values on infrastructure Services until another reconciliation trigger occurs.

    Review effort: Lite
    Findings: 1 <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture>

    <details open>
    <summary><strong>Open (1)</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Tenant RBAC lacks event permissions for recorder warnings](#discussion_r4102677342)

  • </details>

    aimnbrs aimnbrs commented on code on Sep 25, 2026 14:47 UTC
    Code Review
    pkg/provider/loadbalancer.go:1
    @@ -232,6 +304,98 @@ func (lb *loadbalancer) createLoadBalancerService(ctx context.Context, lbName st
     	return lbService, nil
     }
     
    +// allowedAnnotations returns the subset of the tenant Service's annotations that
    +// the infra operator has explicitly allowlisted via LoadBalancerConfig.
    +// Ownership metadata, kubectl's saved configuration and the legacy source-range
    +// annotation are excluded even if allowlisted. Source ranges are handled as a
    +// validated field, not passed through as an annotation.
    +func (lb *loadbalancer) allowedAnnotations(service *corev1.Service) map[string]string {
    +	if len(lb.config.AllowedAnnotations) == 0 || len(service.Annotations) == 0 {
    +		return nil
    +	}
    +	var annotations map[string]string
    +	for _, key := range lb.config.AllowedAnnotations {
    +		if key == tenantAnnotationKeys || key == corev1.LastAppliedConfigAnnotation || key == corev1.AnnotationLoadBalancerSourceRangesKey {
    +			continue
    +		}
    +		val, ok := service.Annotations[key]
    +		if !ok {
    +			continue
    +		}
    +		if annotations == nil {
    +			annotations = map[string]string{}
    +		}
    +		annotations[key] = val
    +	}
    +	return annotations
    +}
    +
    +// reconcileAnnotations preserves infra-owned annotations and replaces only keys
    +// previously managed by this provider. Legacy Services have no ownership record:
    +// only keys still matching the current tenant value can be identified for cleanup.
    +func (lb *loadbalancer) reconcileAnnotations(service *corev1.Service, existing map[string]string) (map[string]string, error) {
    +	result := make(map[string]string, len(existing)+1)
    +	for key, value := range existing {
    +		result[key] = value
    +	}
    +	if raw, tracked := existing[tenantAnnotationKeys]; tracked {

    Older builds copied every tenant annotation onto the infra Service at creation, so on a Service created before the upgrade this record may come from the tenant rather than the provider. If a tenant on a cluster that hasn't been upgraded yet creates a Service with cloud-provider.kubevirt.io/tenant-annotation-keys set, then after the upgrade:

  • x (not JSON): reconcileAnnotations fails before anything is written, so the copied externalIPs and loadBalancerIP stay on the infra Service and every retry fails the same way.

  • []: the Service counts as tracked, the value-match cleanup is skipped, and annotations the old build copied (e.g. metallb.universe.tf/loadBalancerIPs) stay.

  • ["metallb.io/ip-allocated-from-pool"]: listed infra-side keys are deleted.
  • I checked the three cases with a unit test against e61b0df (an infra Service built the way the old createLoadBalancerService did, then UpdateLoadBalancer). Without the planted key, the same Service is cleaned as expected.

    Older builds only ever set provider-built label keys on the infra Service, so a label written together with the record (e.g. cloud-provider.kubevirt.io/annotation-ownership: v1) would separate a provider-written record from a copied one: without the label, ignore the record and take the legacy path. It may also be worth not letting an error in the annotation bookkeeping block the externalIPs/loadBalancerIP clean-up. For the README's upgrade audit: an infra Service from an older build that already carries cloud-provider.kubevirt.io/tenant-annotation-keys got it from the tenant.

    Happy to push the test to a branch if it helps.

    aimnbrs aimnbrs commented on Sep 25, 2026 14:47 UTC
    Reviewer

    Thanks — the four points from the first round are addressed in e61b0df. One more about the upgrade path, inline.

    qinqon qinqon commented on code on Sep 30, 2026 11:39 UTC
    Code Review
    pkg/provider/loadbalancer.go:1
    @@ -232,6 +304,98 @@ func (lb *loadbalancer) createLoadBalancerService(ctx context.Context, lbName st
     	return lbService, nil
     }
     
    +// allowedAnnotations returns the subset of the tenant Service's annotations that
    +// the infra operator has explicitly allowlisted via LoadBalancerConfig.
    +// Ownership metadata, kubectl's saved configuration and the legacy source-range
    +// annotation are excluded even if allowlisted. Source ranges are handled as a
    +// validated field, not passed through as an annotation.
    +func (lb *loadbalancer) allowedAnnotations(service *corev1.Service) map[string]string {
    +	if len(lb.config.AllowedAnnotations) == 0 || len(service.Annotations) == 0 {
    +		return nil
    +	}
    +	var annotations map[string]string
    +	for _, key := range lb.config.AllowedAnnotations {
    +		if key == tenantAnnotationKeys || key == corev1.LastAppliedConfigAnnotation || key == corev1.AnnotationLoadBalancerSourceRangesKey {
    +			continue
    +		}
    +		val, ok := service.Annotations[key]
    +		if !ok {
    +			continue
    +		}
    +		if annotations == nil {
    +			annotations = map[string]string{}
    +		}
    +		annotations[key] = val
    +	}
    +	return annotations
    +}
    +
    +// reconcileAnnotations preserves infra-owned annotations and replaces only keys
    +// previously managed by this provider. Legacy Services have no ownership record:
    +// only keys still matching the current tenant value can be identified for cleanup.
    +func (lb *loadbalancer) reconcileAnnotations(service *corev1.Service, existing map[string]string) (map[string]string, error) {
    +	result := make(map[string]string, len(existing)+1)
    +	for key, value := range existing {
    +		result[key] = value
    +	}
    +	if raw, tracked := existing[tenantAnnotationKeys]; tracked {

    Good catch, thanks. Fixed in 923578af0:

  • The record is only trusted when the infra Service carries cloud-provider.kubevirt.io/annotation-ownership: v1, set on create and on every update that writes the record. Without the label, the record is ignored and the legacy value-match path runs.

  • reconcileAnnotations no longer returns an error. An unreadable record falls back to the legacy path, so it can no longer block the externalIPs/loadBalancerIP cleanup.

  • TestPlantedOwnershipRecordIgnored covers your three values (x, [], ["metallb.io/ip-allocated-from-pool"]) through UpdateLoadBalancer on an infra Service built like the old createLoadBalancerService.

  • README upgrade audit now notes that a pre-upgrade tenant-annotation-keys came from the tenant.
  • If your test covers anything beyond that, feel free to push it.

    Copilot Copilot commented on code on Oct 01, 2026 06:11 UTC
    Code Review
    test/e2e/cloud_provider_kubevirt/load_balancer_test.go:1
    @@ -38,6 +42,93 @@ var _ = Describe("Load Balancer", func() {
     		server = resources.HTTPServerDeployment(testAppName, namespace)
     		service = resources.HTTPServerService(testAppName, namespace)
     	})
    +	It("should restrict tenant fields and preserve infra annotations on reconciliation", func() {
    +		ctx := context.Background()
    +		service.Name = "tenant-field-policy"
    +		service.Annotations = map[string]string{"example.com/tenant": "not-propagated"}
    +		service.Spec.LoadBalancerIP = "203.0.113.10"
    +		service.Spec.LoadBalancerSourceRanges = []string{"203.0.113.0/24"}
    +		resource.Create(tenantClient, service)
    +		DeferCleanup(func() { resource.Delete(tenantClient, service) })
    +
    +		var infra *v1.Service
    +		Eventually(func() error {
    +			var err error
    +			infra, err = findInfraLoadBalancerService(service.Name, service.Namespace)
    +			return err
    +		}, time.Minute, time.Second).Should(Succeed())
    +		// The kubevirtci Deployment mounts this secret as its tenant kubeconfig
    +		// and uses shared credentials. Check that identity, not the test client's
    +		// credentials, before asserting event delivery.
    +		By("checking event authorization with the deployed CCM's tenant credentials")
    +		credentials := &v1.Secret{}
    +		Expect(infraClient.Get(ctx, client.ObjectKey{Namespace: infra.Namespace, Name: "kubeconfig"}, credentials)).To(Succeed())

    This lookup uses the mirrored Service's namespace (infra.Namespace), but the kubeconfig Secret mounted by the deployed CCM is created in the default namespace (config/secret/kustomization.yaml:4-8 and config/manager/manager.yaml:53-58), while the mirrored Service uses the configured namespace: kvcluster (config/isolated/cloud-config:1-4). The new e2e test therefore fails before it can check authorization; fetch the Secret from the CCM Deployment's namespace (currently default).

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Oct 01, 2026 06:11 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    Copilot review overview

    🟡 Changes recommended

    Fix the e2e Secret namespace lookup and handle null ownership metadata without orphaning annotations.

    Review effort: Lite
    Findings: 1 <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> · 1 <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture>

    <details open>
    <summary><strong>Open (2)</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> [Fetch kubeconfig Secret from the CCM namespace](#discussion_r4152368096) · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Tenant RBAC lacks event permissions for recorder warnings](#discussion_r4102677342)

  • </details>

    Reviewers
    Assignees
    qinqon qinqon
    Labels
    risk: low confidence: 90.4% reviewed sensitive_module
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 77.9% (HIGH) · Higher = larger blast radius
    77.9%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 90.4% · Lower = rushed or shallow review
    90.4%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 7.4% · Safe to merge
    7.4%