github.com/cilium/cilium@v1.16.2/operator/pkg/gateway-api/helpers/referencegrants.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright Authors of Cilium
     3  
     4  package helpers
     5  
     6  import (
     7  	corev1 "k8s.io/api/core/v1"
     8  	schema "k8s.io/apimachinery/pkg/runtime/schema"
     9  	gatewayv1 "sigs.k8s.io/gateway-api/apis/v1"
    10  	gatewayv1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1"
    11  	mcsapiv1alpha1 "sigs.k8s.io/mcs-api/pkg/apis/v1alpha1"
    12  )
    13  
    14  // IsBackendReferenceAllowed returns true if the backend reference is allowed by the reference grant.
    15  func IsBackendReferenceAllowed(originatingNamespace string, be gatewayv1.BackendRef, gvk schema.GroupVersionKind, grants []gatewayv1beta1.ReferenceGrant) bool {
    16  	if IsService(be.BackendObjectReference) {
    17  		return isReferenceAllowed(originatingNamespace, string(be.Name), be.Namespace, gvk, corev1.SchemeGroupVersion.WithKind("Service"), grants)
    18  	}
    19  	if IsServiceImport(be.BackendObjectReference) {
    20  		return isReferenceAllowed(originatingNamespace, string(be.Name), be.Namespace, gvk, mcsapiv1alpha1.SchemeGroupVersion.WithKind("ServiceImport"), grants)
    21  	}
    22  
    23  	return false
    24  }
    25  
    26  // IsSecretReferenceAllowed returns true if the secret reference is allowed by the reference grant.
    27  func IsSecretReferenceAllowed(originatingNamespace string, sr gatewayv1.SecretObjectReference, gvk schema.GroupVersionKind, grants []gatewayv1beta1.ReferenceGrant) bool {
    28  	return isReferenceAllowed(originatingNamespace, string(sr.Name), sr.Namespace, gvk, corev1.SchemeGroupVersion.WithKind("Secret"), grants)
    29  }
    30  
    31  func isReferenceAllowed(originatingNamespace, name string, namespace *gatewayv1.Namespace, fromGVK, toGVK schema.GroupVersionKind, grants []gatewayv1beta1.ReferenceGrant) bool {
    32  	ns := NamespaceDerefOr(namespace, originatingNamespace)
    33  	if originatingNamespace == ns {
    34  		return true // same namespace is always allowed
    35  	}
    36  
    37  	for _, g := range grants {
    38  		if g.Namespace != ns {
    39  			continue
    40  		}
    41  		for _, from := range g.Spec.From {
    42  			if (from.Group == gatewayv1.Group(fromGVK.Group) && from.Kind == gatewayv1.Kind(fromGVK.Kind)) &&
    43  				(string)(from.Namespace) == originatingNamespace {
    44  				for _, to := range g.Spec.To {
    45  					if to.Group == gatewayv1.Group(toGVK.Group) && to.Kind == gatewayv1.Kind(toGVK.Kind) &&
    46  						(to.Name == nil || string(*to.Name) == name) {
    47  						return true
    48  					}
    49  				}
    50  			}
    51  		}
    52  	}
    53  	return false
    54  }