From d6fa54915fe03181a4586af03ded19a116ff98bc Mon Sep 17 00:00:00 2001 From: yandongxiao Date: Wed, 29 Jul 2026 14:24:45 +0800 Subject: [PATCH] [BugFix] Support TLS on the operator's MySQL connection to FE MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The operator opens its MySQL connection to FE in plaintext only. When a user sets ssl_force_secure_transport=true on FE, FE rejects every operator connection with "Error 5205 (HY000): Connections using insecure transport are prohibited" and logs a WARN each time, flooding the FE log. Add a global --fe-ssl-mode flag (Helm value starrocksOperator.feSslMode) with values DISABLED / PREFERRED / REQUIRED, default PREFERRED, mapped onto go-sql-driver's tls= DSN parameter: - DISABLED: plaintext, byte-for-byte the previous behavior. - PREFERRED (default): encrypt when FE advertises CLIENT_SSL, stay plaintext otherwise — a cluster without SSL behaves exactly as before. - REQUIRED: always encrypt (tls=skip-verify), fail when FE does not support SSL. - VERIFY_CA / VERIFY_IDENTITY: recognized but rejected at startup — FE's documented keystore is self-signed, so certificate verification cannot succeed; the names are reserved for the future. An unrecognized or empty value stops the operator at startup instead of silently falling back to plaintext. The two duplicated DSN literals in cn_mysql.go are collapsed into one dsn() method so both query paths always honor the same mode. No new dependency, no CRD change, no RBAC change; deploy/operator.yaml and the parent chart values are regenerated. Signed-off-by: yandongxiao --- cmd/config/config.go | 6 + cmd/main.go | 12 ++ deploy/operator.yaml | 1 + doc/README.md | 1 + doc/connect_to_ssl_enabled_fe_howto.md | 132 ++++++++++++++++++ .../charts/operator/templates/deployment.yaml | 3 + .../charts/operator/values.yaml | 13 ++ helm-charts/charts/kube-starrocks/values.yaml | 13 ++ pkg/subcontrollers/cn/cn_mysql.go | 21 ++- pkg/subcontrollers/cn/cn_mysql_ssl.go | 69 +++++++++ pkg/subcontrollers/cn/cn_mysql_ssl_test.go | 59 ++++++++ pkg/subcontrollers/cn/cn_mysql_test.go | 44 ++++++ 12 files changed, 370 insertions(+), 4 deletions(-) create mode 100644 doc/connect_to_ssl_enabled_fe_howto.md create mode 100644 pkg/subcontrollers/cn/cn_mysql_ssl.go create mode 100644 pkg/subcontrollers/cn/cn_mysql_ssl_test.go diff --git a/cmd/config/config.go b/cmd/config/config.go index 932d78b9a..4433c69cb 100644 --- a/cmd/config/config.go +++ b/cmd/config/config.go @@ -8,6 +8,12 @@ var ( // VolumeNameWithHash decides whether adding a hash to the volume name VolumeNameWithHash bool + + // FeSslMode decides whether the operator's MySQL connection to FE negotiates TLS. Valid values + // are DISABLED, PREFERRED and REQUIRED — the MySQL client's --ssl-mode vocabulary, matched + // case-insensitively. It is validated once at startup (see cn.ValidateSSLMode), applies to the + // whole operator process, and requires an operator restart to change. + FeSslMode string ) func GetServiceDomainSuffix() string { diff --git a/cmd/main.go b/cmd/main.go index e0e2200da..2a39ad8fa 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -29,6 +29,7 @@ import ( srapi "github.com/StarRocks/starrocks-kubernetes-operator/pkg/apis/starrocks/v1" "github.com/StarRocks/starrocks-kubernetes-operator/pkg/controllers" "github.com/StarRocks/starrocks-kubernetes-operator/pkg/k8sutils" + "github.com/StarRocks/starrocks-kubernetes-operator/pkg/subcontrollers/cn" ) var ( @@ -50,6 +51,11 @@ func main() { flag.StringVar(&config.DNSDomainSuffix, "dns-domain-suffix", "cluster.local", "The suffix of the dns domain in k8s") flag.BoolVar(&config.VolumeNameWithHash, "volume-name-with-hash", true, "Add a hash to the volume name") flag.StringVar(&_denyList, "deny-list", "", "Comma-separated list of namespaces to exclude from reconciliation") + flag.StringVar(&config.FeSslMode, "fe-ssl-mode", cn.SSLModePreferred, + "How the operator's MySQL connection to FE negotiates TLS. DISABLED keeps it plaintext; "+ + "PREFERRED encrypts when FE advertises SSL support and stays plaintext otherwise; "+ + "REQUIRED always encrypts and fails when FE does not support SSL. Case-insensitive. "+ + "The server certificate is never verified. Requires an operator restart to change.") // Set up logger. opts := zap.Options{} @@ -58,6 +64,12 @@ func main() { ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts))) logger := ctrl.Log.WithName("main") + // Fail fast: an unusable ssl mode would otherwise stay silent until the first FE connection. + if err := cn.ValidateSSLMode(config.FeSslMode); err != nil { + logger.Error(err, "invalid --fe-ssl-mode") + os.Exit(1) + } + // Register CRD to SchemeBuilder srapi.Register() diff --git a/deploy/operator.yaml b/deploy/operator.yaml index 21ca84587..8e8375982 100644 --- a/deploy/operator.yaml +++ b/deploy/operator.yaml @@ -179,6 +179,7 @@ spec: - --zap-time-encoding=iso8601 - --zap-encoder=console - --volume-name-with-hash=true + - --fe-ssl-mode=PREFERRED env: - name: TZ value: Asia/Shanghai diff --git a/doc/README.md b/doc/README.md index 410774b27..16e396ac8 100644 --- a/doc/README.md +++ b/doc/README.md @@ -17,6 +17,7 @@ Table Of Content - [HPA Automatic Scaling For CN Nodes](./hpa_dynamic_scaling_with_helm_howto.md) - [Load Data Using Stream Load](./load_data_using_stream_load_howto.md) - [Build Your Own Container Image](./build_your_own_container_image_howto.md) + - [Connect the Operator to an SSL-Enabled FE](./connect_to_ssl_enabled_fe_howto.md) - Integration - [Prometheus And Grafana](./integration/integration-prometheus-grafana.md) - [Datadog](./integration/integration-with-datadog.md) diff --git a/doc/connect_to_ssl_enabled_fe_howto.md b/doc/connect_to_ssl_enabled_fe_howto.md new file mode 100644 index 000000000..db9cefb2a --- /dev/null +++ b/doc/connect_to_ssl_enabled_fe_howto.md @@ -0,0 +1,132 @@ +# Connect the Operator to an SSL-Enabled FE HOWTO + +The operator talks to FE over the MySQL protocol to run maintenance statements such as +`SHOW COMPUTE NODES`, `ALTER SYSTEM DROP COMPUTE NODE`, and `DROP WAREHOUSE`. Before this feature the +operator could only open a **plaintext** connection. If FE was configured with +`ssl_force_secure_transport = true` in `fe.conf`, it rejected every one of these connections with +error 5205 (`Connections using insecure transport are prohibited`) and logged a warning each time. + +This document describes the `--fe-ssl-mode` flag (Helm value `starrocksOperator.feSslMode`) that lets +the operator negotiate TLS for this connection, and how to choose the right value for your cluster. + +## 1. How It Works + +`--fe-ssl-mode` accepts three values, matched case-insensitively: + +| Value | Behavior | +|---|---| +| `DISABLED` | Always plaintext. An FE with `ssl_force_secure_transport = true` rejects the connection with error 5205. | +| `PREFERRED` (default) | Encrypt when FE advertises SSL support; stay plaintext when it does not. A cluster without SSL configured on FE behaves exactly as before this feature. | +| `REQUIRED` | Always encrypt; fail the connection when FE does not support SSL. | + +`VERIFY_CA` and `VERIFY_IDENTITY` are recognized names — they exist in the MySQL client's +`--ssl-mode` vocabulary that this flag mirrors — but the operator refuses to start if either is +configured; see [Certificate Verification](#2-certificate-verification) for why. An unrecognized or +empty value also stops the operator at startup: a typo in this flag should be loud, not silently +fall back to plaintext. + +## 2. Certificate Verification + +**The server certificate is never verified, in any mode**, including `REQUIRED`. FE's own +documentation for enabling SSL has you generate a self-signed keystore, for example: + +```bash +keytool -genkeypair -alias starrocks -keyalg RSA -keysize 1024 -validity 365 +``` + +A self-signed certificate has no CA to chain to, and its certificate name never matches the +in-cluster service DNS name the operator dials to reach FE. Verifying either one would fail +against the exact keystore FE's documentation tells you to create. + +Because of this, `PREFERRED` and `REQUIRED` protect the connection from **passive eavesdropping +only**. They do not protect against an **active man-in-the-middle**, since the operator never +confirms it is actually talking to your FE. Do not treat `REQUIRED` as a strong security guarantee; +treat it as "always encrypted, certificate unchecked." + +## 3. Choosing a Mode + +- **Most users should change nothing.** The default, `PREFERRED`, already handles both cases: it + encrypts against an FE with SSL enabled and stays plaintext against an FE without it. +- **Use `REQUIRED`** if you need a guarantee that the operator never talks to FE in plaintext — for + example, a compliance posture that does not accept `PREFERRED`'s silent fallback to plaintext when + FE does not advertise SSL. +- **Fall back to `DISABLED`** if FE advertises SSL but the TLS handshake cannot be negotiated (for + example, a TLS version or cipher mismatch between the operator's MySQL driver and FE's keystore). + `PREFERRED` does **not** fall back to plaintext in that situation — it only falls back when FE does + not advertise SSL at all, so a handshake failure with `PREFERRED` still fails the connection. + `DISABLED` is the escape hatch while you fix the handshake, or if you decide not to run FE with SSL. + +## 4. FE-Side Settings + +These `fe.conf` settings on the FE side determine whether FE advertises and accepts SSL, and are +what `--fe-ssl-mode` reacts to: + +- `ssl_keystore_location` — path to the keystore file. +- `ssl_keystore_password` — password for the keystore. +- `ssl_key_password` — password for the private key inside the keystore. +- `ssl_force_secure_transport` — when `true`, FE rejects plaintext connections outright (error 5205). + +Refer to FE's own documentation for how to generate the keystore and set these values. Two traps to +watch for while doing so: + +- **`ssl_key_password` must equal `ssl_keystore_password`.** JDK 9+ defaults `keytool` to the PKCS12 + keystore format, which does not support a separate per-key password: `-storepass A -keypass B` + silently keeps the private key's password as `A` and only prints a warning. FE still starts and + logs the three `ssl_*` settings as if healthy, but cannot read its private key, and the operator in + `REQUIRED` mode fails with no obvious cause. +- **Verify enforcement through the FE Service DNS name, not loopback.** FE exempts `127.0.0.1` + connections from `ssl_force_secure_transport`, so `kubectl exec ... -- mysql -h127.0.0.1` still + succeeds in plaintext even with enforcement on. Test from the FE's Service DNS name or another pod. + +## 5. Configure via Helm + +Set `starrocksOperator.feSslMode` when installing or upgrading the operator (or the `kube-starrocks` +umbrella chart, where the same key lives under `operator.starrocksOperator.feSslMode`): + +```bash +helm upgrade starrocks-operator starrocks/operator \ + --reuse-values \ + --set starrocksOperator.feSslMode=REQUIRED +``` + +Or set it in `values.yaml`: + +```yaml +starrocksOperator: + feSslMode: REQUIRED +``` + +If you installed the `kube-starrocks` umbrella chart instead of the standalone `operator` chart, the +same value lives one level deeper, under the `operator` subchart: + +```bash +helm upgrade starrocks starrocks/kube-starrocks \ + --reuse-values \ + --set operator.starrocksOperator.feSslMode=REQUIRED +``` + +## 6. Configure via Raw Manifest + +If you deploy the operator from `deploy/operator.yaml` instead of Helm, edit the `--fe-ssl-mode` +argument that already ships in the manager container's `args`: + +```yaml + args: + - --leader-elect + - --zap-time-encoding=iso8601 + - --zap-encoder=console + - --volume-name-with-hash=true + - --fe-ssl-mode=REQUIRED +``` + +Then re-apply the manifest: + +```bash +kubectl apply -f deploy/operator.yaml +``` + +## 7. Restart Behavior + +`--fe-ssl-mode` is read once at process start, so changing it (through either path above) **restarts +the operator pod**. It does **not** restart FE, BE, or CN pods — those keep running unaffected, and +the new mode only takes effect for the operator's own FE connections after its pod comes back up. diff --git a/helm-charts/charts/kube-starrocks/charts/operator/templates/deployment.yaml b/helm-charts/charts/kube-starrocks/charts/operator/templates/deployment.yaml index e9620301a..27e9a2bcf 100644 --- a/helm-charts/charts/kube-starrocks/charts/operator/templates/deployment.yaml +++ b/helm-charts/charts/kube-starrocks/charts/operator/templates/deployment.yaml @@ -47,6 +47,9 @@ spec: {{- if .Values.starrocksOperator.denyList }} - --deny-list={{ .Values.starrocksOperator.denyList }} {{- end }} + {{- if .Values.starrocksOperator.feSslMode }} + - --fe-ssl-mode={{ .Values.starrocksOperator.feSslMode }} + {{- end }} env: - name: TZ value: {{ .Values.timeZone }} diff --git a/helm-charts/charts/kube-starrocks/charts/operator/values.yaml b/helm-charts/charts/kube-starrocks/charts/operator/values.yaml index f91ceecb0..54fc36b70 100644 --- a/helm-charts/charts/kube-starrocks/charts/operator/values.yaml +++ b/helm-charts/charts/kube-starrocks/charts/operator/values.yaml @@ -95,6 +95,19 @@ starrocksOperator: # any resources in it. Avoid configuring conflicting values between these two settings. # Example: "kube-system,kube-public,monitoring" denyList: "" + # How the operator's MySQL connection to FE negotiates TLS. Mirrors the MySQL client's + # --ssl-mode option: + # DISABLED - always plaintext. An FE with ssl_force_secure_transport=true rejects the + # connection with error 5205 and logs a warning for every attempt. + # PREFERRED - (default) encrypt when FE advertises SSL support, stay plaintext when it does + # not, so a cluster without SSL configured behaves exactly as before. + # REQUIRED - always encrypt, and fail the connection when FE does not support SSL. Use this + # to guarantee the operator never talks to FE in plaintext. + # The server certificate is never verified: the keystore FE's documentation generates is + # self-signed, so there is no CA to chain to and its name does not match FE's in-cluster + # service DNS name. Leave empty to use the operator's built-in default. Changing this value + # restarts the operator pod. + feSslMode: PREFERRED # Additional operator container environment variables # You specify this manually like you would a raw deployment manifest. # Ref: https://kubernetes.io/docs/tasks/inject-data-application/define-environment-variable-container/ diff --git a/helm-charts/charts/kube-starrocks/values.yaml b/helm-charts/charts/kube-starrocks/values.yaml index 096fb2872..fe334154f 100644 --- a/helm-charts/charts/kube-starrocks/values.yaml +++ b/helm-charts/charts/kube-starrocks/values.yaml @@ -102,6 +102,19 @@ operator: # any resources in it. Avoid configuring conflicting values between these two settings. # Example: "kube-system,kube-public,monitoring" denyList: "" + # How the operator's MySQL connection to FE negotiates TLS. Mirrors the MySQL client's + # --ssl-mode option: + # DISABLED - always plaintext. An FE with ssl_force_secure_transport=true rejects the + # connection with error 5205 and logs a warning for every attempt. + # PREFERRED - (default) encrypt when FE advertises SSL support, stay plaintext when it does + # not, so a cluster without SSL configured behaves exactly as before. + # REQUIRED - always encrypt, and fail the connection when FE does not support SSL. Use this + # to guarantee the operator never talks to FE in plaintext. + # The server certificate is never verified: the keystore FE's documentation generates is + # self-signed, so there is no CA to chain to and its name does not match FE's in-cluster + # service DNS name. Leave empty to use the operator's built-in default. Changing this value + # restarts the operator pod. + feSslMode: PREFERRED # Additional operator container environment variables # You specify this manually like you would a raw deployment manifest. # Ref: https://kubernetes.io/docs/tasks/inject-data-application/define-environment-variable-container/ diff --git a/pkg/subcontrollers/cn/cn_mysql.go b/pkg/subcontrollers/cn/cn_mysql.go index d78719367..dd37f37dc 100644 --- a/pkg/subcontrollers/cn/cn_mysql.go +++ b/pkg/subcontrollers/cn/cn_mysql.go @@ -13,6 +13,7 @@ import ( "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" + "github.com/StarRocks/starrocks-kubernetes-operator/cmd/config" "github.com/StarRocks/starrocks-kubernetes-operator/pkg/k8sutils" "github.com/StarRocks/starrocks-kubernetes-operator/pkg/k8sutils/templates/object" ) @@ -29,6 +30,11 @@ type SQLExecutor struct { FeServiceName string FeServiceNamespace string FeServicePort string + + // SSLMode decides whether the connection to FE negotiates TLS; see the SSLMode* constants. + // It is captured per executor rather than read from the flag at connect time so that tests can + // exercise each mode without mutating process-wide state. + SSLMode string } // NewSQLExecutor creates a SQLExecutor instance. It will get the root password, fe service name, and fe service port @@ -77,16 +83,24 @@ func NewSQLExecutor(ctx context.Context, k8sClient client.Client, namespace, cnS FeServiceName: feServiceName, FeServiceNamespace: namespace, FeServicePort: feServicePort, + SSLMode: config.FeSslMode, }, nil } +// dsn builds the go-sql-driver DSN for the FE connection. Both ExecuteContext and QueryContext go +// through it so the SSL mode can never be honored by one path and skipped by the other. +func (executor *SQLExecutor) dsn() string { + return fmt.Sprintf("root:%s@tcp(%s.%s:%s)/%s", + executor.RootPassword, executor.FeServiceName, executor.FeServiceNamespace, + executor.FeServicePort, sslModeDSNSuffix(executor.SSLMode)) +} + // ExecuteContext sql statements. Every time a SQL statement needs to be executed, a new sql.DB instance will be created. // This is because SQL statements are executed infrequently. func (executor *SQLExecutor) ExecuteContext(ctx context.Context, db *sql.DB, statement string) error { var err error if db == nil { - db, err = sql.Open("mysql", fmt.Sprintf("root:%s@tcp(%s.%s:%s)/", - executor.RootPassword, executor.FeServiceName, executor.FeServiceNamespace, executor.FeServicePort)) + db, err = sql.Open("mysql", executor.dsn()) if err != nil { return err } @@ -104,8 +118,7 @@ func (executor *SQLExecutor) ExecuteContext(ctx context.Context, db *sql.DB, sta func (executor *SQLExecutor) QueryContext(ctx context.Context, db *sql.DB, statements string) (*sql.Rows, error) { var err error if db == nil { - db, err = sql.Open("mysql", fmt.Sprintf("root:%s@tcp(%s.%s:%s)/", - executor.RootPassword, executor.FeServiceName, executor.FeServiceNamespace, executor.FeServicePort)) + db, err = sql.Open("mysql", executor.dsn()) if err != nil { return nil, err } diff --git a/pkg/subcontrollers/cn/cn_mysql_ssl.go b/pkg/subcontrollers/cn/cn_mysql_ssl.go new file mode 100644 index 000000000..ec982208c --- /dev/null +++ b/pkg/subcontrollers/cn/cn_mysql_ssl.go @@ -0,0 +1,69 @@ +package cn + +import ( + "fmt" + "strings" +) + +// SSL modes for the operator's MySQL connection to FE. The names mirror the MySQL client's +// --ssl-mode option so that the vocabulary in the FE SSL documentation carries over unchanged. +const ( + // SSLModeDisabled never negotiates TLS. An FE configured with ssl_force_secure_transport=true + // rejects such a connection with error 5205. + SSLModeDisabled = "DISABLED" + + // SSLModePreferred negotiates TLS when FE advertises the CLIENT_SSL capability and falls back + // to plaintext when it does not. The server certificate is not verified. + SSLModePreferred = "PREFERRED" + + // SSLModeRequired always negotiates TLS and fails the connection when FE does not advertise + // CLIENT_SSL. The server certificate is not verified. + SSLModeRequired = "REQUIRED" + + // SSLModeVerifyCA and SSLModeVerifyIdentity are recognized but rejected. The keystore FE's + // documentation tells users to generate is self-signed, so there is no CA to chain to, and its + // certificate name never matches the in-cluster service DNS name the operator dials. + SSLModeVerifyCA = "VERIFY_CA" + SSLModeVerifyIdentity = "VERIFY_IDENTITY" +) + +// normalizeSSLMode makes a user-supplied mode comparable to the SSLMode* constants: matching is +// case-insensitive, and surrounding whitespace (easy to introduce through Helm values) is ignored. +func normalizeSSLMode(mode string) string { + return strings.ToUpper(strings.TrimSpace(mode)) +} + +// ValidateSSLMode reports whether mode is a value the operator can act on. main calls it right +// after flag.Parse so that a typo stops the operator at startup, instead of surfacing much later +// as a failed FE connection during reconcile. +func ValidateSSLMode(mode string) error { + switch normalizeSSLMode(mode) { + case SSLModeDisabled, SSLModePreferred, SSLModeRequired: + return nil + case SSLModeVerifyCA, SSLModeVerifyIdentity: + return fmt.Errorf("ssl mode %q is not supported: the keystore FE's documentation generates is "+ + "self-signed, so neither its certificate chain nor its certificate name can be verified; "+ + "use %s to require encryption without certificate verification", mode, SSLModeRequired) + default: + return fmt.Errorf("invalid ssl mode %q, must be one of %s, %s, %s", + mode, SSLModeDisabled, SSLModePreferred, SSLModeRequired) + } +} + +// sslModeDSNSuffix returns the query string to append to the FE DSN for mode, including the leading +// "?" when non-empty. The values map onto go-sql-driver's tls= parameter: "preferred" negotiates TLS +// but falls back to plaintext when the server does not advertise CLIENT_SSL, while "skip-verify" +// insists on TLS. Neither verifies the server certificate. +// +// Unrecognized values yield "" — the plaintext behavior that predates this feature — rather than a +// panic. Production never reaches that branch because main rejects such values via ValidateSSLMode. +func sslModeDSNSuffix(mode string) string { + switch normalizeSSLMode(mode) { + case SSLModePreferred: + return "?tls=preferred" + case SSLModeRequired: + return "?tls=skip-verify" + default: + return "" + } +} diff --git a/pkg/subcontrollers/cn/cn_mysql_ssl_test.go b/pkg/subcontrollers/cn/cn_mysql_ssl_test.go new file mode 100644 index 000000000..69b2af78a --- /dev/null +++ b/pkg/subcontrollers/cn/cn_mysql_ssl_test.go @@ -0,0 +1,59 @@ +package cn + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestSSLModeDSNSuffix(t *testing.T) { + tests := []struct { + name string + mode string + want string + }{ + {name: "disabled adds nothing", mode: SSLModeDisabled, want: ""}, + {name: "preferred negotiates with plaintext fallback", mode: SSLModePreferred, want: "?tls=preferred"}, + {name: "required always negotiates", mode: SSLModeRequired, want: "?tls=skip-verify"}, + {name: "lower case is accepted", mode: "preferred", want: "?tls=preferred"}, + {name: "mixed case is accepted", mode: "ReQuIrEd", want: "?tls=skip-verify"}, + {name: "surrounding spaces are trimmed", mode: " PREFERRED ", want: "?tls=preferred"}, + {name: "verify_ca falls back to plaintext", mode: SSLModeVerifyCA, want: ""}, + {name: "verify_identity falls back to plaintext", mode: SSLModeVerifyIdentity, want: ""}, + {name: "unrecognized value falls back to plaintext", mode: "banana", want: ""}, + {name: "empty value falls back to plaintext", mode: "", want: ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, sslModeDSNSuffix(tt.mode)) + }) + } +} + +func TestValidateSSLMode(t *testing.T) { + for _, mode := range []string{SSLModeDisabled, SSLModePreferred, SSLModeRequired, "preferred", " REQUIRED "} { + t.Run("accepts "+mode, func(t *testing.T) { + assert.NoError(t, ValidateSSLMode(mode)) + }) + } + + // VERIFY_CA / VERIFY_IDENTITY are recognized names, so the error must explain why they are + // unusable and point at REQUIRED instead of just listing valid values. + for _, mode := range []string{SSLModeVerifyCA, SSLModeVerifyIdentity} { + t.Run("rejects "+mode, func(t *testing.T) { + err := ValidateSSLMode(mode) + require.Error(t, err) + assert.Contains(t, err.Error(), "self-signed") + assert.Contains(t, err.Error(), SSLModeRequired) + }) + } + + for _, mode := range []string{"", "banana", "true"} { + t.Run("rejects unrecognized "+mode, func(t *testing.T) { + err := ValidateSSLMode(mode) + require.Error(t, err) + assert.Contains(t, err.Error(), SSLModePreferred) + }) + } +} diff --git a/pkg/subcontrollers/cn/cn_mysql_test.go b/pkg/subcontrollers/cn/cn_mysql_test.go index 07c72b922..f21a71d1e 100644 --- a/pkg/subcontrollers/cn/cn_mysql_test.go +++ b/pkg/subcontrollers/cn/cn_mysql_test.go @@ -17,6 +17,7 @@ import ( clientgoscheme "k8s.io/client-go/kubernetes/scheme" "sigs.k8s.io/controller-runtime/pkg/client" + "github.com/StarRocks/starrocks-kubernetes-operator/cmd/config" "github.com/StarRocks/starrocks-kubernetes-operator/pkg/k8sutils/fake" ) @@ -27,6 +28,12 @@ func TestNewSQLExecutor(t *testing.T) { namespace string name string } + + // NewSQLExecutor copies the process-wide flag value onto the executor, so pin it for this test. + originalSslMode := config.FeSslMode + config.FeSslMode = SSLModeRequired + t.Cleanup(func() { config.FeSslMode = originalSslMode }) + tests := []struct { name string args args @@ -89,6 +96,7 @@ func TestNewSQLExecutor(t *testing.T) { FeServiceName: "fe", FeServiceNamespace: "default", FeServicePort: "9030", + SSLMode: SSLModeRequired, }, wantErr: assert.NoError, }, @@ -356,3 +364,39 @@ func TestSQLExecutor_ExecuteDropWarehouse(t *testing.T) { }) } } + +func TestSQLExecutorDSN(t *testing.T) { + tests := []struct { + name string + mode string + want string + }{ + { + name: "disabled keeps the plaintext DSN unchanged", + mode: SSLModeDisabled, + want: "root:123456@tcp(fe.default:9030)/", + }, + { + name: "preferred appends the opportunistic tls parameter", + mode: SSLModePreferred, + want: "root:123456@tcp(fe.default:9030)/?tls=preferred", + }, + { + name: "required appends the mandatory tls parameter", + mode: SSLModeRequired, + want: "root:123456@tcp(fe.default:9030)/?tls=skip-verify", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + executor := &SQLExecutor{ + RootPassword: "123456", + FeServiceName: "fe", + FeServiceNamespace: "default", + FeServicePort: "9030", + SSLMode: tt.mode, + } + assert.Equal(t, tt.want, executor.dsn()) + }) + } +}