From 2df3f93c4d4600d486b8b44278bf9504fab9f091 Mon Sep 17 00:00:00 2001 From: sabith Date: Mon, 16 Nov 2026 11:39:09 -0800 Subject: [PATCH] feat(library): split pkg/chop config machinery from the kube client wiring Library consumers import the operator for its config generation, and today that drags the entire k8s.io/client-go surface through pkg/chop: the ConfigManager held *kube.Clientset and *chopclientset.Clientset fields, so any import of chop.Config() - the one accessor every consumer reads - compiled the full Kubernetes client machinery in. This splits the config machinery into pkg/chop/config, kube-free: - ConfigManager moves to pkg/chop/config with two narrow seams (the secretDataGetter pattern already established for the RootCA tests): - CRConfigLister - reads operator-configuration Custom Resources, answering specs + ResourceVersions (nil = file/env-only config, the library-consumer shape) - secretDataGetter - Kubernetes Secret reads (nil = secret refs log a warning and stay unresolved) - pkg/chop keeps New(), GetClientset, and the kube machinery, and adapts its clientsets to the seams - the operator binary's path is unchanged (same signature, same behavior, same logs) - ProvisionIPCToken stays exported from pkg/chop (wrapper over the config package's implementation) Net effect: a consumer importing only pkg/chop/config has ZERO k8s.io/client-go modules in its dependency tree (verified with a scratch consumer: require -> import -> build; go list -deps shows only apimachinery types). Consumers of the operator outside Kubernetes (VM bootstrappers embedding the config/keeper model layer) no longer inherit the client surface they never call. No behavior change: the CR listing, secret fetches, insecure-kube gate, and TLS min-version floor all run through the same logic - only the client boundary moved behind function seams. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- pkg/chop/chop.go | 62 ++++++- .../access_rootca_test.go} | 0 pkg/chop/config/ipc_token.go | 80 +++++++++ pkg/chop/{ => config}/ipc_token_test.go | 12 +- .../{config_manager.go => config/manager.go} | 153 +++++++++--------- .../manager_test.go} | 4 +- pkg/chop/ipc_token.go | 61 +------ pkg/chop/kube_machinery.go | 9 +- pkg/chop/setup_log_test.go | 9 +- 9 files changed, 233 insertions(+), 157 deletions(-) rename pkg/chop/{config_access_rootca_test.go => config/access_rootca_test.go} (100%) create mode 100644 pkg/chop/config/ipc_token.go rename pkg/chop/{ => config}/ipc_token_test.go (90%) rename pkg/chop/{config_manager.go => config/manager.go} (83%) rename pkg/chop/{config_manager_test.go => config/manager_test.go} (99%) diff --git a/pkg/chop/chop.go b/pkg/chop/chop.go index fec71e5f97..f4482bcc67 100644 --- a/pkg/chop/chop.go +++ b/pkg/chop/chop.go @@ -19,12 +19,16 @@ import ( "fmt" "os" + "context" + kube "k8s.io/client-go/kubernetes" log "github.com/altinity/clickhouse-operator/pkg/announcer" api "github.com/altinity/clickhouse-operator/pkg/apis/clickhouse.altinity.com/v1" "github.com/altinity/clickhouse-operator/pkg/apis/deployment" - chopclientset "github.com/altinity/clickhouse-operator/pkg/client/clientset/versioned" + chopconfig "github.com/altinity/clickhouse-operator/pkg/chop/config" + "github.com/altinity/clickhouse-operator/pkg/client/clientset/versioned" + "github.com/altinity/clickhouse-operator/pkg/controller" ) // CHOp defines ClickHouse Operator @@ -36,7 +40,7 @@ type CHOp struct { // Date specified date when operator was built Date string // ConfigManager specifies configuration manager in charge of operator's configuration - ConfigManager *ConfigManager + ConfigManager *chopconfig.ConfigManager } // newCHOp creates new CHOp @@ -45,14 +49,58 @@ func newCHOp( commit string, date string, kubeClient *kube.Clientset, - chopClient *chopclientset.Clientset, + chopClient *versioned.Clientset, initConfigFilePath string, ) *CHOp { return &CHOp{ - Version: version, - Commit: commit, - Date: date, - ConfigManager: newConfigManager(kubeClient, chopClient, initConfigFilePath), + Version: version, + Commit: commit, + Date: date, + ConfigManager: chopconfig.NewManager( + crConfigListerFrom(chopClient), + secretGetterFrom(kubeClient), + lastKubeConfigInsecure, + initConfigFilePath, + ), + } +} + +// crConfigListerFrom adapts the operator's custom-resource clientset to +// the config package's CRConfigLister seam — the only place the CR +// listing touches the k8s wire. +func crConfigListerFrom(chopClient *versioned.Clientset) chopconfig.CRConfigLister { + if chopClient == nil { + return nil + } + return func(namespace string) ([]*api.OperatorConfig, map[string]string, error) { + list, err := chopClient.ClickhouseV1().ClickHouseOperatorConfigurations(namespace).List(context.TODO(), controller.NewListOptions()) + if err != nil { + return nil, nil, err + } + configs := make([]*api.OperatorConfig, 0, len(list.Items)) + versions := make(map[string]string, len(list.Items)) + for i := range list.Items { + cr := &list.Items[i] + cr.Spec.Runtime.ConfigCRName = cr.Name + configs = append(configs, &cr.Spec) + versions[cr.Namespace+"/"+cr.Name] = cr.ResourceVersion + } + return configs, versions, nil + } +} + +// secretGetterFrom adapts the operator's kube clientset to the config +// package's secretDataGetter seam. +func secretGetterFrom(kubeClient *kube.Clientset) func(namespace, name string) (map[string][]byte, error) { + if kubeClient == nil { + return nil + } + return func(namespace, name string) (map[string][]byte, error) { + secret, err := kubeClient.CoreV1().Secrets(namespace).Get(context.TODO(), name, controller.NewGetOptions()) + if err != nil { + return nil, err + } + return secret.Data, nil } } diff --git a/pkg/chop/config_access_rootca_test.go b/pkg/chop/config/access_rootca_test.go similarity index 100% rename from pkg/chop/config_access_rootca_test.go rename to pkg/chop/config/access_rootca_test.go diff --git a/pkg/chop/config/ipc_token.go b/pkg/chop/config/ipc_token.go new file mode 100644 index 0000000000..712068406a --- /dev/null +++ b/pkg/chop/config/ipc_token.go @@ -0,0 +1,80 @@ +// Copyright 2019 Altinity Ltd and/or its affiliates. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package chop + +import ( + "crypto/rand" + "encoding/hex" + "fmt" + "os" + "path/filepath" + + log "github.com/altinity/clickhouse-operator/pkg/announcer" + api "github.com/altinity/clickhouse-operator/pkg/apis/clickhouse.altinity.com/v1" +) + +// ipcTokenBytes is the random-byte length of the operator↔exporter shared +// bearer token. 32 bytes = 256 bits → 64 hex characters in the file. +// Comfortably above the brute-force-resistance threshold; not so large that +// it stresses /etc tmpfs. +const ipcTokenBytes = 32 + +// ProvisionIPCToken generates a fresh random token and writes it to the +// configured TokenPath when chopconf has IPC Mode=Secure. Plain mode is a +// no-op so existing deployments are unaffected. +// +// provisionIPCToken is the test-accessible inner implementation. Splitting +// the IPC-config read from the file-write logic lets unit tests drive the +// behavior with a synthetic *api.OperatorConfigSecurityIPC rather +// than spinning up a full chop subsystem. +// +// Idempotent across restarts: if the path already holds a non-empty token, +// the existing value is reused (avoids invalidating the token if the operator +// container restarts while the exporter container keeps holding the old +// value). +// ProvisionIPCToken is the exported inner implementation (pkg/chop's +// wrapper reads the global config and hands the IPC section here). +func ProvisionIPCToken(ipc *api.OperatorConfigSecurityIPC) error { + if (ipc == nil) || (ipc.GetMode() != api.IPCModeSecure) { + return nil + } + + path := ipc.GetTokenPath() + if path == "" { + path = api.IPCDefaultTokenPath + } + + // Reuse non-empty existing token across operator-container restarts. + if data, err := os.ReadFile(path); (err == nil) && (len(data) > 0) { + log.V(1).Info("IPC: reusing existing token at %s", path) + return nil + } + + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return fmt.Errorf("IPC: cannot create token dir %s: %w", filepath.Dir(path), err) + } + + raw := make([]byte, ipcTokenBytes) + if _, err := rand.Read(raw); err != nil { + return fmt.Errorf("IPC: crypto/rand failure generating token: %w", err) + } + encoded := hex.EncodeToString(raw) + + if err := os.WriteFile(path, []byte(encoded), 0o400); err != nil { + return fmt.Errorf("IPC: cannot write token to %s: %w", path, err) + } + log.Info("IPC: Secure mode — provisioned token at %s (%d bytes)", path, len(encoded)) + return nil +} diff --git a/pkg/chop/ipc_token_test.go b/pkg/chop/config/ipc_token_test.go similarity index 90% rename from pkg/chop/ipc_token_test.go rename to pkg/chop/config/ipc_token_test.go index 2692a614d9..3deeed44be 100644 --- a/pkg/chop/ipc_token_test.go +++ b/pkg/chop/config/ipc_token_test.go @@ -35,14 +35,14 @@ func TestProvisionIPCTokenPlainModeIsNoop(t *testing.T) { dir := t.TempDir() tokenPath := filepath.Join(dir, "token") - require.NoError(t, provisionIPCToken(ipcCfg(api.IPCModePlain, tokenPath))) + require.NoError(t, ProvisionIPCToken(ipcCfg(api.IPCModePlain, tokenPath))) _, err := os.Stat(tokenPath) require.True(t, os.IsNotExist(err), "Plain mode must not write any token file") } func TestProvisionIPCTokenNilIPCIsNoop(t *testing.T) { - require.NoError(t, provisionIPCToken(nil)) + require.NoError(t, ProvisionIPCToken(nil)) } func TestProvisionIPCTokenSecureModeWritesToken(t *testing.T) { @@ -50,7 +50,7 @@ func TestProvisionIPCTokenSecureModeWritesToken(t *testing.T) { // Path under a subdirectory that doesn't exist yet — exercises MkdirAll. tokenPath := filepath.Join(dir, "subdir", "token") - require.NoError(t, provisionIPCToken(ipcCfg(api.IPCModeSecure, tokenPath))) + require.NoError(t, ProvisionIPCToken(ipcCfg(api.IPCModeSecure, tokenPath))) data, err := os.ReadFile(tokenPath) require.NoError(t, err) @@ -71,7 +71,7 @@ func TestProvisionIPCTokenReuseExisting(t *testing.T) { tokenPath := filepath.Join(dir, "token") require.NoError(t, os.WriteFile(tokenPath, []byte("preexisting-token-value"), 0o400)) - require.NoError(t, provisionIPCToken(ipcCfg(api.IPCModeSecure, tokenPath))) + require.NoError(t, ProvisionIPCToken(ipcCfg(api.IPCModeSecure, tokenPath))) data, err := os.ReadFile(tokenPath) require.NoError(t, err) @@ -86,12 +86,12 @@ func TestProvisionIPCTokenTwoCallsSameToken(t *testing.T) { tokenPath := filepath.Join(dir, "token") cfg := ipcCfg(api.IPCModeSecure, tokenPath) - require.NoError(t, provisionIPCToken(cfg)) + require.NoError(t, ProvisionIPCToken(cfg)) first, err := os.ReadFile(tokenPath) require.NoError(t, err) require.NotEmpty(t, first) - require.NoError(t, provisionIPCToken(cfg)) + require.NoError(t, ProvisionIPCToken(cfg)) second, err := os.ReadFile(tokenPath) require.NoError(t, err) require.Equal(t, first, second, "second call must reuse the existing token") diff --git a/pkg/chop/config_manager.go b/pkg/chop/config/manager.go similarity index 83% rename from pkg/chop/config_manager.go rename to pkg/chop/config/manager.go index 57ed20150f..730700bcc4 100644 --- a/pkg/chop/config_manager.go +++ b/pkg/chop/config/manager.go @@ -15,7 +15,6 @@ package chop import ( - "context" "errors" "fmt" "os" @@ -24,15 +23,22 @@ import ( "sort" "github.com/kubernetes-sigs/yaml" - kube "k8s.io/client-go/kubernetes" log "github.com/altinity/clickhouse-operator/pkg/announcer" api "github.com/altinity/clickhouse-operator/pkg/apis/clickhouse.altinity.com/v1" "github.com/altinity/clickhouse-operator/pkg/apis/deployment" - chopClientSet "github.com/altinity/clickhouse-operator/pkg/client/clientset/versioned" - "github.com/altinity/clickhouse-operator/pkg/controller" ) +// CRConfigLister reads every ClickHouseOperatorConfiguration in a +// namespace, answering the config specs (location info filled) and +// each CR's ResourceVersion by "namespace/name" (IsConfigListed +// compares it to detect a changed config). The kube clientset wiring +// behind this seam lives in the operator binary's path (pkg/chop wires +// it from its chopclientset) — this package stays free of k8s client +// imports so library consumers of the config machinery do not inherit +// the client-go surface. +type CRConfigLister func(namespace string) ([]*api.OperatorConfig, map[string]string, error) + // ErrInsecureKubeconfigRejected is returned by ConfigManager.Init when the loaded // kubeconfig has TLSClientConfig.Insecure=true but the file-based chopconf has // security.kubernetes.tls.verify=Strict. Sentinel so callers/tests @@ -41,14 +47,27 @@ var ErrInsecureKubeconfigRejected = errors.New("kubeconfig declares TLSClientCon // ConfigManager specifies configuration manager in charge of operator's configuration type ConfigManager struct { - // kubeClient is a k8s client - kubeClient *kube.Clientset - - // chopClient is a k8s client able to communicate with operator's Custom Resources - chopClient *chopClientSet.Clientset - - // chopConfigList is a list of available operator configurations - chopConfigList *api.ClickHouseOperatorConfigurationList + // listCRConfigs reads operator-configuration Custom Resources + // through the caller's seam (nil = no CR-based configs, the + // library-consumer and pre-client shapes). + listCRConfigs CRConfigLister + + // getSecret reads Kubernetes Secret data through the caller's + // seam (nil = secret references log a warning and stay + // unresolved; the secretDataGetter seam shape). + getSecret secretDataGetter + + // kubeConfigInsecure records whether the caller's kubeconfig + // declared TLSClientConfig.Insecure=true — the caller (pkg/chop's + // client machinery) sets it at load time; the strict-TLS startup + // gate below reads it before any CR-based wire call. + kubeConfigInsecure bool + + // crVersions maps "namespace/name" of a listed operator-config + // CR to its ResourceVersion — the raw CR metadata the lister + // seam cannot carry through the spec-only OperatorConfig, but + // IsConfigListed compares it to detect a changed config. + crVersions map[string]string // initConfigFilePath is a path to the configuration file, which will be used as initial/seed // to build final config, which will be used/consumed by users @@ -69,14 +88,21 @@ type ConfigManager struct { } // newConfigManager creates new ConfigManager -func newConfigManager( - kubeClient *kube.Clientset, - chopClient *chopClientSet.Clientset, +// NewManager creates the kube-free ConfigManager. The seams are the +// caller's wire adapters (the operator binary passes its clientsets +// through pkg/chop's adapters); nil seams load file/env-only config — +// the library-consumer shape. kubeConfigInsecure records the caller's +// kubeconfig TLSClientConfig.Insecure for the strict-TLS startup gate. +func NewManager( + listCRConfigs CRConfigLister, + getSecret secretDataGetter, + kubeConfigInsecure bool, initConfigFilePath string, ) *ConfigManager { return &ConfigManager{ - kubeClient: kubeClient, - chopClient: chopClient, + listCRConfigs: listCRConfigs, + getSecret: getSecret, + kubeConfigInsecure: kubeConfigInsecure, initConfigFilePath: initConfigFilePath, } } @@ -90,7 +116,7 @@ func (cm *ConfigManager) Init() error { cm.logEnvVarParams() // Get initial config from the file - cm.fileConfig, err = cm.getFileBasedConfig(cm.initConfigFilePath) + cm.fileConfig, err = cm.GetFileBasedConfig(cm.initConfigFilePath) if err != nil { return err } @@ -112,7 +138,7 @@ func (cm *ConfigManager) Init() error { // (or security.policy=Enforced, which one-way coerces verify to Strict) in a // CR-based ChOpConfig accept that the file-based config still wins for the // startup gate. - if lastKubeConfigInsecure && cm.fileConfig.RequiresStrictK8sTLS() { + if cm.kubeConfigInsecure && cm.fileConfig.RequiresStrictK8sTLS() { return ErrInsecureKubeconfigRejected } @@ -150,48 +176,29 @@ func (cm *ConfigManager) Config() *api.OperatorConfig { // getAllCRBasedConfigs reads all ClickHouseOperatorConfiguration objects in specified namespace func (cm *ConfigManager) getAllCRBasedConfigs(namespace string) { - // We need to have chop kube client available in order to fetch ClickHouseOperatorConfiguration objects - if cm.chopClient == nil { + // The caller wires the CR listing seam (the operator binary's kube + // path); a nil seam means no CR-based configs are available — the + // library-consumer shape. + if cm.listCRConfigs == nil { return } log.V(1).F().Info("Looking for ClickHouseOperatorConfigurations in namespace '%s'.", namespace) - // Get list of ClickHouseOperatorConfiguration objects - var err error - if cm.chopConfigList, err = cm.chopClient.ClickhouseV1().ClickHouseOperatorConfigurations(namespace).List(context.TODO(), controller.NewListOptions()); err != nil { + crConfigs, versions, err := cm.listCRConfigs(namespace) + if err != nil { log.V(1).F().Error("Error read ClickHouseOperatorConfigurations in namespace '%s'. Err: %v", namespace, err) return } + cm.crVersions = versions - if cm.chopConfigList == nil { - return - } - - // Get sorted list of names of ClickHouseOperatorConfiguration objects located in specified namespace - var names []string - for i := range cm.chopConfigList.Items { - chOperatorConfiguration := &cm.chopConfigList.Items[i] - names = append(names, chOperatorConfiguration.Name) - } - sort.Strings(names) + // Save location info into OperatorConfig itself + for _, crConfig := range crConfigs { + crConfig.Runtime.ConfigCRNamespace = namespace - // Build sorted list of configs - for _, name := range names { - for i := range cm.chopConfigList.Items { - // Convenience wrapper - chOperatorConfiguration := &cm.chopConfigList.Items[i] - if chOperatorConfiguration.Name == name { - // Save location info into OperatorConfig itself - chOperatorConfiguration.Spec.Runtime.ConfigCRNamespace = namespace - chOperatorConfiguration.Spec.Runtime.ConfigCRName = name + cm.crConfigs = append(cm.crConfigs, crConfig) - cm.crConfigs = append(cm.crConfigs, &chOperatorConfiguration.Spec) - - log.V(1).F().Info("Append ClickHouseOperatorConfigurations '%s/%s'.", namespace, name) - continue - } - } + log.V(1).F().Info("Append ClickHouseOperatorConfigurations '%s/%s'.", namespace, crConfig.Runtime.ConfigCRName) } } @@ -221,18 +228,8 @@ func (cm *ConfigManager) buildUnifiedConfig() { // IsConfigListed checks whether specified ClickHouseOperatorConfiguration is listed in list of ClickHouseOperatorConfiguration(s) func (cm *ConfigManager) IsConfigListed(config *api.ClickHouseOperatorConfiguration) bool { - for i := range cm.chopConfigList.Items { - chOperatorConfiguration := &cm.chopConfigList.Items[i] - - if config.Namespace == chOperatorConfiguration.Namespace && - config.Name == chOperatorConfiguration.Name && - config.ResourceVersion == chOperatorConfiguration.ResourceVersion { - // Yes, this config already listed with the same resource version - return true - } - } - - return false + version, ok := cm.crVersions[config.Namespace+"/"+config.Name] + return ok && version == config.ResourceVersion } const ( @@ -241,7 +238,7 @@ const ( ) // getFileBasedConfig creates one OperatorConfig object based on the first available configuration file -func (cm *ConfigManager) getFileBasedConfig(configFilePath string) (*api.OperatorConfig, error) { +func (cm *ConfigManager) GetFileBasedConfig(configFilePath string) (*api.OperatorConfig, error) { // Check config files availability in the following order: // 1. Explicitly specified config file as CLI option // 2. Explicitly specified config file as ENV var @@ -448,7 +445,11 @@ func (cm *ConfigManager) fetchSecretCredentials() { return } - secret, err := cm.kubeClient.CoreV1().Secrets(namespace).Get(context.TODO(), name, controller.NewGetOptions()) + if cm.getSecret == nil { + cm.config.ClickHouse.Access.Secret.Runtime.Error = fmt.Sprintf("No secret-reading capability wired for secret '%s'", name) + return + } + secret, err := cm.getSecret(namespace, name) if err != nil { cm.config.ClickHouse.Access.Secret.Runtime.Error = err.Error() log.V(1).Warning("Unable to fetch secret: '%s/%s'", namespace, name) @@ -459,7 +460,7 @@ func (cm *ConfigManager) fetchSecretCredentials() { log.V(1).Info("Secret fetched: '%s/%s'", namespace, name) // Find username and password from credentials - for key, value := range secret.Data { + for key, value := range secret { switch key { case "username": cm.config.ClickHouse.Access.Secret.Runtime.Username = string(value) @@ -493,7 +494,7 @@ type secretDataGetter func(namespace, name string) (map[string][]byte, error) // Secret and restarts the operator. func (cm *ConfigManager) fetchSecurityRootCA() { ns, _ := cm.GetRuntimeParam(deployment.OPERATOR_POD_NAMESPACE) - fetchSecurityRootCAResolve(cm.config.Security.GetClickHouse().GetTLS(), ns, cm.getSecretData) + fetchSecurityRootCAResolve(cm.config.Security.GetClickHouse().GetTLS(), ns, cm.getSecret) } // fetchAccessRootCA resolves clickhouse.access.rootCASecretRef into the inline @@ -509,18 +510,13 @@ func (cm *ConfigManager) fetchAccessRootCA() { access.RootCASecretRef.Key, ns, "chopconf clickhouse.access", - cm.getSecretData, + cm.getSecret, ) } -// getSecretData adapts the operator's kubeClient to the secretDataGetter seam. -func (cm *ConfigManager) getSecretData(namespace, name string) (map[string][]byte, error) { - secret, err := cm.kubeClient.CoreV1().Secrets(namespace).Get(context.TODO(), name, controller.NewGetOptions()) - if err != nil { - return nil, err - } - return secret.Data, nil -} +// getSecretData is the ConfigManager's secret-reading seam — the +// caller wires it (the operator binary adapts its kubeClient here); +// nil means the config loads without resolving secret references. // resolveRootCAFromSecret is the shared decision logic for inlining a CA bundle // from a Kubernetes Secret into an inline RootCA PEM string at config-load time. @@ -588,3 +584,10 @@ func fetchSecurityRootCAResolve(tls *api.ClusterSecurityClickHouseTLS, operatorN func (cm *ConfigManager) Postprocess() { cm.config.Postprocess() } + +// NewWithConfig builds a ConfigManager over a pre-built OperatorConfig — +// the seam the chop package's own tests use to drive SetupLog without a +// config-load cycle. +func NewWithConfig(config *api.OperatorConfig) *ConfigManager { + return &ConfigManager{config: config} +} diff --git a/pkg/chop/config_manager_test.go b/pkg/chop/config/manager_test.go similarity index 99% rename from pkg/chop/config_manager_test.go rename to pkg/chop/config/manager_test.go index da14f3114f..0527aca662 100644 --- a/pkg/chop/config_manager_test.go +++ b/pkg/chop/config/manager_test.go @@ -266,8 +266,8 @@ func TestInit_RefusesFIPSSwitchNotBoolean(t *testing.T) { t.Run(tc.name, func(t *testing.T) { path := filepath.Join(t.TempDir(), "config.yaml") require.NoError(t, os.WriteFile(path, []byte("security:\n fips:\n enforced: "+tc.value+"\n"), 0o600)) - cm := newConfigManager(nil, nil, path) - fileConfig, err := cm.getFileBasedConfig(path) + cm := NewManager(nil, nil, false, path) + fileConfig, err := cm.GetFileBasedConfig(path) require.NoError(t, err, "the file decodes") require.Equal(t, tc.refused, fileConfig.Security.GetFIPS().Validate() != nil) if tc.refused { diff --git a/pkg/chop/ipc_token.go b/pkg/chop/ipc_token.go index 48dbdf07b4..7c2fea175e 100644 --- a/pkg/chop/ipc_token.go +++ b/pkg/chop/ipc_token.go @@ -14,22 +14,7 @@ package chop -import ( - "crypto/rand" - "encoding/hex" - "fmt" - "os" - "path/filepath" - - log "github.com/altinity/clickhouse-operator/pkg/announcer" - api "github.com/altinity/clickhouse-operator/pkg/apis/clickhouse.altinity.com/v1" -) - -// ipcTokenBytes is the random-byte length of the operator↔exporter shared -// bearer token. 32 bytes = 256 bits → 64 hex characters in the file. -// Comfortably above the brute-force-resistance threshold; not so large that -// it stresses /etc tmpfs. -const ipcTokenBytes = 32 +import chopconfig "github.com/altinity/clickhouse-operator/pkg/chop/config" // ProvisionIPCToken generates a fresh random token and writes it to the // configured TokenPath when chopconf has IPC Mode=Secure. Plain mode is a @@ -38,47 +23,5 @@ const ipcTokenBytes = 32 // Called once at operator startup AFTER chop.New has loaded chopconf and // BEFORE the metrics-exporter sidecar's StartMetricsREST returns. func ProvisionIPCToken() error { - return provisionIPCToken(Config().Security.GetIPC()) -} - -// provisionIPCToken is the test-accessible inner implementation. Splitting -// the IPC-config read from the file-write logic lets unit tests drive the -// behavior with a synthetic *api.OperatorConfigSecurityIPC rather -// than spinning up a full chop subsystem. -// -// Idempotent across restarts: if the path already holds a non-empty token, -// the existing value is reused (avoids invalidating the token if the operator -// container restarts while the exporter container keeps holding the old -// value). -func provisionIPCToken(ipc *api.OperatorConfigSecurityIPC) error { - if (ipc == nil) || (ipc.GetMode() != api.IPCModeSecure) { - return nil - } - - path := ipc.GetTokenPath() - if path == "" { - path = api.IPCDefaultTokenPath - } - - // Reuse non-empty existing token across operator-container restarts. - if data, err := os.ReadFile(path); (err == nil) && (len(data) > 0) { - log.V(1).Info("IPC: reusing existing token at %s", path) - return nil - } - - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { - return fmt.Errorf("IPC: cannot create token dir %s: %w", filepath.Dir(path), err) - } - - raw := make([]byte, ipcTokenBytes) - if _, err := rand.Read(raw); err != nil { - return fmt.Errorf("IPC: crypto/rand failure generating token: %w", err) - } - encoded := hex.EncodeToString(raw) - - if err := os.WriteFile(path, []byte(encoded), 0o400); err != nil { - return fmt.Errorf("IPC: cannot write token to %s: %w", path, err) - } - log.Info("IPC: Secure mode — provisioned token at %s (%d bytes)", path, len(encoded)) - return nil + return chopconfig.ProvisionIPCToken(Config().Security.GetIPC()) } diff --git a/pkg/chop/kube_machinery.go b/pkg/chop/kube_machinery.go index 4e84dc71e5..c9d4d5c85b 100644 --- a/pkg/chop/kube_machinery.go +++ b/pkg/chop/kube_machinery.go @@ -33,6 +33,7 @@ import ( log "github.com/altinity/clickhouse-operator/pkg/announcer" api "github.com/altinity/clickhouse-operator/pkg/apis/clickhouse.altinity.com/v1" "github.com/altinity/clickhouse-operator/pkg/apis/deployment" + chopconfig "github.com/altinity/clickhouse-operator/pkg/chop/config" chopclientset "github.com/altinity/clickhouse-operator/pkg/client/clientset/versioned" "github.com/altinity/clickhouse-operator/pkg/util/tlsutil" ) @@ -178,8 +179,8 @@ func GetClientset(kubeConfigFile, masterURL, chopConfigFile string) ( // visible here and will not floor the K8s transport. Declare fips.enforced / policy in // the file-based chopconf for the K8s-API floor to apply. func resolveK8sTLSMinVersion(chopConfigFile string) (minVersion string, hardened bool) { - cm := newConfigManager(nil, nil, chopConfigFile) - fileConfig, err := cm.getFileBasedConfig(chopConfigFile) + cm := chopconfig.NewManager(nil, nil, lastKubeConfigInsecure, chopConfigFile) + fileConfig, err := cm.GetFileBasedConfig(chopConfigFile) if err != nil || fileConfig == nil { return "", false } @@ -189,8 +190,8 @@ func resolveK8sTLSMinVersion(chopConfigFile string) (minVersion string, hardened // resolveK8sClientRateLimits reads reconcile.runtime.k8sClientQPS and k8sClientBurst from the // file-based chopconf. File-only for the same reason as resolveK8sTLSMinVersion. func resolveK8sClientRateLimits(chopConfigFile string) (qps float32, burst int) { - cm := newConfigManager(nil, nil, chopConfigFile) - fileConfig, err := cm.getFileBasedConfig(chopConfigFile) + cm := chopconfig.NewManager(nil, nil, lastKubeConfigInsecure, chopConfigFile) + fileConfig, err := cm.GetFileBasedConfig(chopConfigFile) if err != nil || fileConfig == nil { return 0, 0 } diff --git a/pkg/chop/setup_log_test.go b/pkg/chop/setup_log_test.go index 26c019571b..f745c6fbec 100644 --- a/pkg/chop/setup_log_test.go +++ b/pkg/chop/setup_log_test.go @@ -16,6 +16,7 @@ package chop import ( "flag" + chopconfig "github.com/altinity/clickhouse-operator/pkg/chop/config" "testing" "github.com/stretchr/testify/require" @@ -46,7 +47,7 @@ func restoreFlags(t *testing.T, names ...string) { func TestSetupLogAppliesVModuleAndLogBacktraceAt(t *testing.T) { restoreFlags(t, "vmodule", "log_backtrace_at") - c := &CHOp{ConfigManager: &ConfigManager{config: &api.OperatorConfig{}}} + c := &CHOp{ConfigManager: chopconfig.NewWithConfig(&api.OperatorConfig{})} c.Config().Logger.VModule = "worker=3" c.Config().Logger.LogBacktraceAt = "worker.go:42" @@ -65,7 +66,7 @@ func TestSetupLogLeavesUnsetOptionsAlone(t *testing.T) { require.NoError(t, flag.Set("vmodule", "preset=1")) - c := &CHOp{ConfigManager: &ConfigManager{config: &api.OperatorConfig{}}} + c := &CHOp{ConfigManager: chopconfig.NewWithConfig(&api.OperatorConfig{})} c.SetupLog() require.Equal(t, "preset=1", flag.Lookup("vmodule").Value.String(), @@ -78,7 +79,7 @@ func TestSetupLogEnvOverridesConfig(t *testing.T) { restoreFlags(t, "v", "vmodule") t.Setenv(deployment.CHOP_LOGGER_V, "0") - c := &CHOp{ConfigManager: &ConfigManager{config: &api.OperatorConfig{}}} + c := &CHOp{ConfigManager: chopconfig.NewWithConfig(&api.OperatorConfig{})} c.Config().Logger.V = "1" c.Config().Logger.VModule = "worker=3" @@ -97,7 +98,7 @@ func TestSetupLogEnvWithoutConfigAndEmptyEnv(t *testing.T) { t.Setenv(deployment.CHOP_LOGGER_VMODULE, "worker=2") t.Setenv(deployment.CHOP_LOGGER_V, "") - c := &CHOp{ConfigManager: &ConfigManager{config: &api.OperatorConfig{}}} + c := &CHOp{ConfigManager: chopconfig.NewWithConfig(&api.OperatorConfig{})} c.Config().Logger.V = "2" c.SetupLog()