Documentation
¶
Overview ¶
Package controllerutil provides utility functions for the ToolHive Kubernetes operator controllers.
Package controllerutil provides shared utility functions for ToolHive Kubernetes controllers.
This package contains helper functions extracted from the controllers package to improve code organization and reusability. Functions are organized by domain:
- platform.go: Platform detection and shared detector management
- rbac.go: RBAC (Role-Based Access Control) configuration helpers
- resources.go: Resource limit and request calculation utilities
- authz.go: Authorization (Cedar policy) configuration helpers
- oidc.go: OIDC (OpenID Connect) configuration helpers
- oidc_volumes.go: OIDC CA bundle volume and mount helpers
- tokenexchange.go: Token exchange configuration for external auth
- config.go: General configuration merging and validation utilities
- podtemplatespec_builder.go: PodTemplateSpec builder for constructing pod template patches
These utilities are used by multiple controllers including MCPServer, MCPRemoteProxy, and ToolConfig controllers to maintain consistent behavior across the operator.
Package controllerutil provides utility functions for Kubernetes controllers.
Package controllerutil provides shared utilities for ToolHive Kubernetes controllers.
Index ¶
- Constants
- func AddAuthzConfigOptions(ctx context.Context, c client.Client, namespace string, ...) error
- func AddEmbeddedAuthServerConfigOptions(ctx context.Context, c client.Client, namespace string, ...) error
- func AddExternalAuthConfigOptions(ctx context.Context, c client.Client, namespace string, ...) error
- func AddOIDCCABundleVolumes(oidcConfig *mcpv1alpha1.OIDCConfigRef) ([]corev1.Volume, []corev1.VolumeMount)
- func AddOIDCConfigOptions(ctx context.Context, c client.Client, res oidc.OIDCConfigurable, ...) error
- func BuildHealthProbe(path, port string, initialDelay, period, timeout, failureThreshold int32) *corev1.Probe
- func BuildResourceRequirements(resourceSpec mcpv1alpha1.ResourceRequirements) corev1.ResourceRequirements
- func CalculateConfigHash[T any](spec T) string
- func CreateProxyServiceName(resourceName string) string
- func CreateProxyServiceURL(resourceName, namespace string, port int32) string
- func EnsureAuthzConfigMap(ctx context.Context, c client.Client, scheme *runtime.Scheme, ...) error
- func EnsureRequiredEnvVars(ctx context.Context, env []corev1.EnvVar) []corev1.EnvVar
- func FindReferencingMCPServers(ctx context.Context, c client.Client, namespace string, configName string, ...) ([]mcpv1alpha1.MCPServer, error)
- func GenerateAuthServerConfig(ctx context.Context, c client.Client, namespace string, ...) ([]corev1.Volume, []corev1.VolumeMount, []corev1.EnvVar, error)
- func GenerateAuthServerEnvVars(authConfig *mcpv1alpha1.EmbeddedAuthServerConfig) []corev1.EnvVar
- func GenerateAuthServerVolumes(authConfig *mcpv1alpha1.EmbeddedAuthServerConfig) ([]corev1.Volume, []corev1.VolumeMount)
- func GenerateAuthzVolumeConfig(authzConfig *mcpv1alpha1.AuthzConfigRef, resourceName string) (*corev1.VolumeMount, *corev1.Volume)
- func GenerateHeaderForwardSecretEnvVarName(proxyName, headerName string) (envVarName, secretIdentifier string)
- func GenerateOIDCClientSecretEnvVar(ctx context.Context, c client.Client, namespace string, ...) (*corev1.EnvVar, error)
- func GenerateOpenTelemetryEnvVars(telemetryConfig *mcpv1alpha1.TelemetryConfig, resourceName string, ...) []corev1.EnvVar
- func GenerateTokenExchangeEnvVars(ctx context.Context, c client.Client, namespace string, ...) ([]corev1.EnvVar, error)
- func GenerateUniqueHeaderInjectionEnvVarName(configName string) string
- func GenerateUniqueTokenExchangeEnvVarName(configName string) string
- func GetExternalAuthConfigByName(ctx context.Context, c client.Client, namespace string, name string) (*mcpv1alpha1.MCPExternalAuthConfig, error)
- func GetExternalAuthConfigForMCPRemoteProxy(ctx context.Context, c client.Client, proxy *mcpv1alpha1.MCPRemoteProxy) (*mcpv1alpha1.MCPExternalAuthConfig, error)
- func GetToolConfigForMCPRemoteProxy(ctx context.Context, c client.Client, proxy *mcpv1alpha1.MCPRemoteProxy) (*mcpv1alpha1.MCPToolConfig, error)
- func GetToolConfigForMCPServer(ctx context.Context, c client.Client, mcpServer *mcpv1alpha1.MCPServer) (*mcpv1alpha1.MCPToolConfig, error)
- func MergeAnnotations(defaultAnnotations, overrideAnnotations map[string]string) map[string]string
- func MergeLabels(defaultLabels, overrideLabels map[string]string) map[string]string
- func MergeStringMaps(defaultMap, overrideMap map[string]string) map[string]string
- func ProxyRunnerServiceAccountName(resourceName string) string
- type PlatformDetectorInterface
- type PodTemplateSpecBuilder
- type SharedPlatformDetector
Constants ¶
const ( // AuthServerKeysVolumePrefix is the prefix for signing key volume names AuthServerKeysVolumePrefix = "authserver-signing-key-" // AuthServerHMACVolumePrefix is the prefix for HMAC secret volume names AuthServerHMACVolumePrefix = "authserver-hmac-secret-" // AuthServerKeysMountPath is the base path where signing keys are mounted AuthServerKeysMountPath = "/etc/toolhive/authserver/keys" // AuthServerHMACMountPath is the base path where HMAC secrets are mounted AuthServerHMACMountPath = "/etc/toolhive/authserver/hmac" // AuthServerKeyFilePattern is the pattern for signing key filenames AuthServerKeyFilePattern = "key-%d.pem" // AuthServerHMACFilePattern is the pattern for HMAC secret filenames AuthServerHMACFilePattern = "hmac-%d" // UpstreamClientSecretEnvVar is the environment variable name for the upstream client secret // #nosec G101 -- This is an environment variable name, not a hardcoded credential UpstreamClientSecretEnvVar = "TOOLHIVE_UPSTREAM_CLIENT_SECRET" )
Constants for auth server volume mounting
const (
// DefaultAuthzKey is the default key for authorization policies in ConfigMaps
DefaultAuthzKey = "authz.json"
)
Variables ¶
This section is empty.
Functions ¶
func AddAuthzConfigOptions ¶
func AddAuthzConfigOptions( ctx context.Context, c client.Client, namespace string, authzRef *mcpv1alpha1.AuthzConfigRef, options *[]runner.RunConfigBuilderOption, ) error
AddAuthzConfigOptions adds authorization configuration options to builder options
func AddEmbeddedAuthServerConfigOptions ¶ added in v0.9.0
func AddEmbeddedAuthServerConfigOptions( ctx context.Context, c client.Client, namespace string, externalAuthConfigRef *mcpv1alpha1.ExternalAuthConfigRef, oidcConfig *oidc.OIDCConfig, options *[]runner.RunConfigBuilderOption, ) error
AddEmbeddedAuthServerConfigOptions adds embedded auth server configuration to runner options when the external auth type is embeddedAuthServer. This is called by the runconfig generation logic to configure the auth server.
The function: 1. Fetches the MCPExternalAuthConfig by name 2. Checks if the type is embeddedAuthServer 3. Validates that oidcConfig is provided with ResourceURL (required for RFC 8707 compliance) 4. Adds the appropriate runner options for embedded auth server configuration
The oidcConfig parameter provides:
- AllowedAudiences: from oidcConfig.ResourceURL (REQUIRED)
- ScopesSupported: from oidcConfig.Scopes (optional, defaults to ["openid", "offline_access"])
Returns nil if externalAuthConfigRef is nil or if the auth type is not embeddedAuthServer. Returns error if oidcConfig is nil or oidcConfig.ResourceURL is empty when using embedded auth server.
func AddExternalAuthConfigOptions ¶
func AddExternalAuthConfigOptions( ctx context.Context, c client.Client, namespace string, externalAuthConfigRef *mcpv1alpha1.ExternalAuthConfigRef, oidcConfig *oidc.OIDCConfig, options *[]runner.RunConfigBuilderOption, ) error
AddExternalAuthConfigOptions adds external authentication configuration options to builder options This creates token exchange configuration which will be automatically converted to middleware by PopulateMiddlewareConfigs() when the runner starts. This ensures correct middleware ordering.
The oidcConfig parameter is used for embedded auth server configuration to populate:
- AllowedAudiences from oidcConfig.ResourceURL
- ScopesSupported from oidcConfig.Scopes
For embedded auth server type, oidcConfig is REQUIRED and must have ResourceURL set.
func AddOIDCCABundleVolumes ¶ added in v0.8.1
func AddOIDCCABundleVolumes( oidcConfig *mcpv1alpha1.OIDCConfigRef, ) ([]corev1.Volume, []corev1.VolumeMount)
AddOIDCCABundleVolumes returns volumes and volume mounts for OIDC CA bundle. Returns nil slices if no CA bundle is configured.
func AddOIDCConfigOptions ¶
func AddOIDCConfigOptions( ctx context.Context, c client.Client, res oidc.OIDCConfigurable, options *[]runner.RunConfigBuilderOption, ) error
AddOIDCConfigOptions adds OIDC configuration options to builder options
func BuildHealthProbe ¶
func BuildHealthProbe( path, port string, initialDelay, period, timeout, failureThreshold int32, ) *corev1.Probe
BuildHealthProbe builds a Kubernetes health probe configuration Shared between MCPServer and MCPRemoteProxy
func BuildResourceRequirements ¶
func BuildResourceRequirements(resourceSpec mcpv1alpha1.ResourceRequirements) corev1.ResourceRequirements
BuildResourceRequirements builds Kubernetes resource requirements from CRD spec Shared between MCPServer and MCPRemoteProxy
func CalculateConfigHash ¶
CalculateConfigHash calculates a hash of any configuration spec using Kubernetes utilities. This function uses k8s.io/apimachinery/pkg/util/dump.ForHash which is designed for generating consistent string representations for hashing in Kubernetes. It then applies FNV-1a hash which is commonly used in Kubernetes for fast hashing. See: https://github.com/kubernetes/kubernetes/blob/master/pkg/controller/controller_utils.go
func CreateProxyServiceName ¶
CreateProxyServiceName generates the service name for a proxy (MCPServer or MCPRemoteProxy) Shared naming convention across both controllers
func CreateProxyServiceURL ¶
CreateProxyServiceURL generates the full cluster-local service URL Shared between MCPServer and MCPRemoteProxy
func EnsureAuthzConfigMap ¶
func EnsureAuthzConfigMap( ctx context.Context, c client.Client, scheme *runtime.Scheme, owner client.Object, namespace string, resourceName string, authzConfig *mcpv1alpha1.AuthzConfigRef, labels map[string]string, ) error
EnsureAuthzConfigMap ensures the authorization ConfigMap exists for inline configuration
func EnsureRequiredEnvVars ¶
EnsureRequiredEnvVars ensures required environment variables are set with defaults Shared between MCPServer and MCPRemoteProxy
func FindReferencingMCPServers ¶
func FindReferencingMCPServers( ctx context.Context, c client.Client, namespace string, configName string, refExtractor func(*mcpv1alpha1.MCPServer) *string, ) ([]mcpv1alpha1.MCPServer, error)
FindReferencingMCPServers finds MCPServers in the given namespace that reference a config resource. The refExtractor function should return the config name from an MCPServer if it references the config, or nil if it doesn't reference any config of this type.
Example usage for ToolConfig:
servers, err := FindReferencingMCPServers(ctx, client, namespace, configName,
func(server *mcpv1alpha1.MCPServer) *string {
if server.Spec.ToolConfigRef != nil {
return &server.Spec.ToolConfigRef.Name
}
return nil
})
func GenerateAuthServerConfig ¶ added in v0.9.0
func GenerateAuthServerConfig( ctx context.Context, c client.Client, namespace string, externalAuthConfigRef *mcpv1alpha1.ExternalAuthConfigRef, ) ([]corev1.Volume, []corev1.VolumeMount, []corev1.EnvVar, error)
GenerateAuthServerConfig generates volumes, volume mounts, and environment variables for the embedded auth server if the external auth config is of type embeddedAuthServer.
This is a convenience function that combines GenerateAuthServerVolumes and GenerateAuthServerEnvVars, with the added logic to fetch and check the MCPExternalAuthConfig type.
Returns empty slices if externalAuthConfigRef is nil or if the auth type is not embeddedAuthServer.
func GenerateAuthServerEnvVars ¶ added in v0.9.0
func GenerateAuthServerEnvVars( authConfig *mcpv1alpha1.EmbeddedAuthServerConfig, ) []corev1.EnvVar
GenerateAuthServerEnvVars creates environment variables for embedded auth server. Currently generates TOOLHIVE_UPSTREAM_CLIENT_SECRET from the upstream provider's client secret reference.
The function looks at the first upstream provider (currently only one is supported) and generates an environment variable for its client secret if one is configured.
Returns nil slice if authConfig is nil or if no client secret is configured.
func GenerateAuthServerVolumes ¶ added in v0.9.0
func GenerateAuthServerVolumes( authConfig *mcpv1alpha1.EmbeddedAuthServerConfig, ) ([]corev1.Volume, []corev1.VolumeMount)
GenerateAuthServerVolumes creates volumes and volume mounts for embedded auth server signing keys and HMAC secrets. Returns slices of volumes and volume mounts. The volumes are configured with 0400 permissions for security.
For signing keys, files are mounted at /etc/toolhive/authserver/keys/key-{N}.pem For HMAC secrets, files are mounted at /etc/toolhive/authserver/hmac/hmac-{N}
Returns nil slices if authConfig is nil.
func GenerateAuthzVolumeConfig ¶
func GenerateAuthzVolumeConfig( authzConfig *mcpv1alpha1.AuthzConfigRef, resourceName string, ) (*corev1.VolumeMount, *corev1.Volume)
GenerateAuthzVolumeConfig generates volume mount and volume for authorization policies
func GenerateHeaderForwardSecretEnvVarName ¶ added in v0.8.3
func GenerateHeaderForwardSecretEnvVarName(proxyName, headerName string) (envVarName, secretIdentifier string)
GenerateHeaderForwardSecretEnvVarName generates the environment variable name for a header forward secret. The generated name follows the TOOLHIVE_SECRET_<identifier> pattern expected by the EnvironmentProvider.
Parameters:
- proxyName: The name of the MCPRemoteProxy resource
- headerName: The HTTP header name (e.g., "X-API-Key")
Returns the full environment variable name (e.g., "TOOLHIVE_SECRET_HEADER_FORWARD_X_API_KEY_MY_PROXY") and the secret identifier portion (e.g., "HEADER_FORWARD_X_API_KEY_MY_PROXY") for use in RunConfig.
func GenerateOIDCClientSecretEnvVar ¶ added in v0.5.0
func GenerateOIDCClientSecretEnvVar( ctx context.Context, c client.Client, namespace string, clientSecretRef *mcpv1alpha1.SecretKeyRef, ) (*corev1.EnvVar, error)
GenerateOIDCClientSecretEnvVar generates environment variable for OIDC client secret when using a SecretKeyRef. Returns nil if clientSecretRef is nil.
func GenerateOpenTelemetryEnvVars ¶
func GenerateOpenTelemetryEnvVars( telemetryConfig *mcpv1alpha1.TelemetryConfig, resourceName string, namespace string, ) []corev1.EnvVar
GenerateOpenTelemetryEnvVars generates OpenTelemetry environment variables
func GenerateTokenExchangeEnvVars ¶
func GenerateTokenExchangeEnvVars( ctx context.Context, c client.Client, namespace string, externalAuthConfigRef *mcpv1alpha1.ExternalAuthConfigRef, getExternalAuthConfig func(context.Context, client.Client, string, string) (*mcpv1alpha1.MCPExternalAuthConfig, error), ) ([]corev1.EnvVar, error)
GenerateTokenExchangeEnvVars generates environment variables for token exchange
func GenerateUniqueHeaderInjectionEnvVarName ¶ added in v0.6.12
GenerateUniqueHeaderInjectionEnvVarName generates a unique environment variable name for header injection values, incorporating the ExternalAuthConfig name to ensure uniqueness. This function is used by both the converter and deployment controller to ensure consistent environment variable naming across the system.
Example: For an ExternalAuthConfig named "my-auth-config", this returns: "TOOLHIVE_HEADER_INJECTION_VALUE_MY_AUTH_CONFIG"
func GenerateUniqueTokenExchangeEnvVarName ¶ added in v0.6.12
GenerateUniqueTokenExchangeEnvVarName generates a unique environment variable name for token exchange client secrets, incorporating the ExternalAuthConfig name to ensure uniqueness. This function is used by both the converter and deployment controller to ensure consistent environment variable naming across the system.
Example: For an ExternalAuthConfig named "my-auth-config", this returns: "TOOLHIVE_TOKEN_EXCHANGE_CLIENT_SECRET_MY_AUTH_CONFIG"
func GetExternalAuthConfigByName ¶
func GetExternalAuthConfigByName( ctx context.Context, c client.Client, namespace string, name string, ) (*mcpv1alpha1.MCPExternalAuthConfig, error)
GetExternalAuthConfigByName is a generic helper for fetching MCPExternalAuthConfig by name
func GetExternalAuthConfigForMCPRemoteProxy ¶
func GetExternalAuthConfigForMCPRemoteProxy( ctx context.Context, c client.Client, proxy *mcpv1alpha1.MCPRemoteProxy, ) (*mcpv1alpha1.MCPExternalAuthConfig, error)
GetExternalAuthConfigForMCPRemoteProxy fetches MCPExternalAuthConfig referenced by MCPRemoteProxy
func GetToolConfigForMCPRemoteProxy ¶
func GetToolConfigForMCPRemoteProxy( ctx context.Context, c client.Client, proxy *mcpv1alpha1.MCPRemoteProxy, ) (*mcpv1alpha1.MCPToolConfig, error)
GetToolConfigForMCPRemoteProxy fetches MCPToolConfig referenced by MCPRemoteProxy
func GetToolConfigForMCPServer ¶ added in v0.5.1
func GetToolConfigForMCPServer( ctx context.Context, c client.Client, mcpServer *mcpv1alpha1.MCPServer, ) (*mcpv1alpha1.MCPToolConfig, error)
GetToolConfigForMCPServer retrieves the MCPToolConfig referenced by an MCPServer
func MergeAnnotations ¶
MergeAnnotations merges override annotations with default annotations Default annotations take precedence to ensure operator-required metadata is preserved Shared between MCPServer and MCPRemoteProxy
func MergeLabels ¶
MergeLabels merges override labels with default labels Default labels take precedence to ensure operator-required metadata is preserved Shared between MCPServer and MCPRemoteProxy
func MergeStringMaps ¶
MergeStringMaps merges override map with default map, with default map taking precedence
func ProxyRunnerServiceAccountName ¶
ProxyRunnerServiceAccountName generates the service account name for the proxy runner Shared between MCPServer and MCPRemoteProxy
Types ¶
type PlatformDetectorInterface ¶
type PlatformDetectorInterface interface {
DetectPlatform(ctx context.Context) (kubernetes.Platform, error)
}
PlatformDetectorInterface provides platform detection capabilities
type PodTemplateSpecBuilder ¶ added in v0.6.11
type PodTemplateSpecBuilder struct {
// contains filtered or unexported fields
}
PodTemplateSpecBuilder provides an interface for building PodTemplateSpec patches. It is used by both MCPServer and VirtualMCPServer controllers.
func NewPodTemplateSpecBuilder ¶ added in v0.6.11
func NewPodTemplateSpecBuilder(userTemplateRaw *runtime.RawExtension, containerName string) (*PodTemplateSpecBuilder, error)
NewPodTemplateSpecBuilder creates a new builder, optionally starting with a user-provided template. The containerName parameter specifies which container WithSecrets() will target. Returns an error if the provided raw extension cannot be unmarshaled into a valid PodTemplateSpec.
func (*PodTemplateSpecBuilder) Build ¶ added in v0.6.11
func (b *PodTemplateSpecBuilder) Build() *corev1.PodTemplateSpec
Build returns the final PodTemplateSpec, or nil if no customizations were made.
func (*PodTemplateSpecBuilder) WithSecrets ¶ added in v0.6.11
func (b *PodTemplateSpecBuilder) WithSecrets(secrets []mcpv1alpha1.SecretRef) *PodTemplateSpecBuilder
WithSecrets adds secret environment variables to the target container. The target container is specified by containerName in the constructor.
func (*PodTemplateSpecBuilder) WithServiceAccount ¶ added in v0.6.11
func (b *PodTemplateSpecBuilder) WithServiceAccount(serviceAccount *string) *PodTemplateSpecBuilder
WithServiceAccount sets the service account name if non-empty.
type SharedPlatformDetector ¶
type SharedPlatformDetector struct {
// contains filtered or unexported fields
}
SharedPlatformDetector provides shared platform detection across controllers
func NewSharedPlatformDetector ¶
func NewSharedPlatformDetector() *SharedPlatformDetector
NewSharedPlatformDetector creates a new shared platform detector
func NewSharedPlatformDetectorWithDetector ¶
func NewSharedPlatformDetectorWithDetector(detector kubernetes.PlatformDetector) *SharedPlatformDetector
NewSharedPlatformDetectorWithDetector creates a new shared platform detector with a custom detector (for testing)
func (*SharedPlatformDetector) DetectPlatform ¶
func (s *SharedPlatformDetector) DetectPlatform(ctx context.Context) (kubernetes.Platform, error)
DetectPlatform detects the platform once and caches the result