diff --git a/CHANGELOG.md b/CHANGELOG.md index 270d46cb..d018bd0d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,7 @@ # Release History ## Unreleased +- Add kernel-backend mTLS client certificate support through `WithKernelClientCertificate(certPEM, keyPEM)` - Support `WithFederatedTokenProvider*` on the kernel backend by resolving its token once for kernel-side federation and forwarding the optional SP-wide client ID - Improve telemetry error reporting: driver failures are now categorized by cause instead of reported as a generic error (databricks/databricks-sql-go#414, #415, #417, #419, #424) - Fix OAuth U2M on the kernel backend (`WithUseKernel(true)`) against **Azure** workspaces: `resolveKernelAuth` now forwards the in-house OAuth app (`databricks-sql-connector`) + `sql offline_access` scopes **uniformly across all clouds**, instead of the Azure Entra-direct app id + `user_impersonation` scope that the Thrift path infers from the host. The kernel runs a single cloud-blind in-house workspace-federated U2M flow (it uses the workspace's OIDC-discovered authorize endpoint verbatim), so feeding it the Entra-direct app made the workspace federation route the browser to a broken AAD authorize URL. AWS/GCP behavior is unchanged (those already resolved to the in-house app + scopes). The Thrift path is unaffected. diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 1f2d3566..61b7730a 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -111,6 +111,7 @@ BINARY as `sql.RawBytes`). | `WithSkipTLSHostVerify()` | ✅ | ✅ | Disable TLS chain + hostname verification. **Use only for internal private-link hostnames** — susceptible to machine-in-the-middle attacks. | | `WithTransport(http.RoundTripper)` | ✅ | ❌ | Supply a custom HTTP transport (custom CA, mTLS, or proxy). Rejected on the kernel path — the kernel uses its own HTTP stack; use `WithKernelTrustedCerts` / `WithKernelProxy` there. | | `WithKernelTrustedCerts(pem)` | ❌ | ✅ | Add a PEM CA bundle on top of the system roots (for a re-signing proxy / on-prem CA). Needed because the kernel's TLS stack does not read `SSL_CERT_FILE`. | +| `WithKernelClientCertificate(certPEM, keyPEM)` | ❌ | ✅ | Configure a paired mTLS client certificate and unencrypted private key. Both must be non-empty; the certificate may include intermediates and PKCS#8 keys are recommended. | | `WithKernelSkipHostnameVerify()` | ❌ | ✅ | Skip **only** the hostname check while keeping chain validation (finer-grained than `WithSkipTLSHostVerify`). | ## Proxy diff --git a/KERNEL_REV b/KERNEL_REV index 0072fe06..a7088393 100644 --- a/KERNEL_REV +++ b/KERNEL_REV @@ -1 +1 @@ -f4c3556d4f57642cf813aef56437214f26685dc4 +e8d60c93b7459947d2e3e4113f62e6bda37fde8e diff --git a/README.md b/README.md index 33676483..1e110a50 100644 --- a/README.md +++ b/README.md @@ -330,6 +330,7 @@ token:@:443[path]?useCloudFetch=false | `WithSkipTLSHostVerify()` | Both | Disable TLS chain + hostname verification. **Use only for internal private-link hostnames** — this is susceptible to machine-in-the-middle attacks. | | `WithTransport(http.RoundTripper)` | Thrift only | Supply a custom HTTP transport (e.g. a custom CA, mTLS, or proxy). **Rejected** on the kernel path (wraps `ErrNotSupportedByKernel`) — the kernel uses its own HTTP stack; use `WithKernelTrustedCerts` / `WithKernelProxy` there. | | `WithKernelTrustedCerts(pem)` | SEA only | Add a PEM CA bundle on top of the system roots (for a re-signing proxy / on-prem CA). Needed because the kernel's TLS stack does not read `SSL_CERT_FILE`. | +| `WithKernelClientCertificate(certPEM, keyPEM)` | SEA only | Configure a paired mTLS client certificate and unencrypted private key. Both must be non-empty; PKCS#8 keys are recommended. | | `WithKernelSkipHostnameVerify()` | SEA only | Skip **only** the hostname check while keeping chain validation (finer-grained than `WithSkipTLSHostVerify`). | ## Proxy diff --git a/connector.go b/connector.go index 3e226bc3..b4c3471b 100644 --- a/connector.go +++ b/connector.go @@ -650,6 +650,27 @@ func WithKernelTrustedCerts(pem []byte) ConnOption { } } +// WithKernelClientCertificate configures the PEM-encoded client certificate and +// matching private key used when a server requires mutual TLS (mTLS). certPEM +// contains the leaf certificate followed by any intermediate certificates; +// keyPEM contains the matching unencrypted private key. PKCS#8 is recommended +// for portability across the kernel's TLS backends. +// +// Both values are required and must be non-empty. The driver copies them +// defensively and validates the pair at connect time. Server trust remains +// independent and strict by default; use WithKernelTrustedCerts when the server +// certificate chains to a private CA. +// +// EXPERIMENTAL, kernel-only: the default (Thrift) backend rejects this at connect. +func WithKernelClientCertificate(certPEM, keyPEM []byte) ConnOption { + return func(c *config.Config) { + ke := kernelExperimental(c) + ke.TLSClientCertConfigured = true + ke.TLSClientCertPEM = append([]byte(nil), certPEM...) + ke.TLSClientKeyPEM = append([]byte(nil), keyPEM...) + } +} + // WithKernelSkipHostnameVerify skips only the certificate hostname-vs-SNI check on // the kernel backend, while keeping chain validation. This is finer-grained than // WithSkipTLSHostVerify, which relaxes both chain and hostname checks. diff --git a/doc.go b/doc.go index b4d23d58..0dee82dd 100644 --- a/doc.go +++ b/doc.go @@ -244,6 +244,9 @@ WithKernel* prefix marks them experimental): - WithKernelTrustedCerts(pem) adds a PEM CA bundle on top of the system roots (for a re-signing proxy or on-prem CA). Required because the kernel's TLS stack does not read SSL_CERT_FILE. + - WithKernelClientCertificate(certPEM, keyPEM) configures a paired mTLS client + identity. Both PEM buffers must be non-empty; the certificate may include + intermediates and an unencrypted PKCS#8 private key is recommended. - WithKernelSkipHostnameVerify() skips only the hostname check while keeping chain validation (finer-grained than WithSkipTLSHostVerify). - WithKernelProxy(KernelProxy{URL, Username, Password, BypassHosts}) sets an explicit diff --git a/internal/backend/kernel/backend.go b/internal/backend/kernel/backend.go index 64a67dcf..4c236c9b 100644 --- a/internal/backend/kernel/backend.go +++ b/internal/backend/kernel/backend.go @@ -289,10 +289,9 @@ func (k *KernelBackend) OpenSession(ctx context.Context) error { } // applyKernelTLS forwards the experimental kernel-only TLS knobs to the session -// config: a custom CA bundle and an independent hostname-skip. Each is a no-op -// when its field is unset, so this is safe to call unconditionally. (mTLS client -// cert/key is a separate follow-up — it needs a kernel C-ABI setter that is not -// yet on kernel main.) +// config: a custom CA bundle, paired mTLS client identity, and an independent +// hostname-skip. Each is a no-op when its field is unset, so this is safe to call +// unconditionally. func (k *KernelBackend) applyKernelTLS(cfg *C.KernelSessionConfig) error { if len(k.cfg.TLSTrustedCertsPEM) > 0 { ca := newCBytes(k.cfg.TLSTrustedCertsPEM) @@ -303,6 +302,23 @@ func (k *KernelBackend) applyKernelTLS(cfg *C.KernelSessionConfig) error { return fmt.Errorf("kernel: set_tls_trusted_certs: %w", toConnError(err)) } } + if len(k.cfg.TLSClientCertPEM) > 0 && len(k.cfg.TLSClientKeyPEM) > 0 { + cert := newCBytes(k.cfg.TLSClientCertPEM) + defer cert.free() + key := newCBytes(k.cfg.TLSClientKeyPEM) + defer key.free() + if err := call(func() C.KernelStatusCode { + return C.kernel_session_config_set_tls_client_certificate( + cfg, + cert.ptr, + cert.len, + key.ptr, + key.len, + ) + }); err != nil { + return fmt.Errorf("kernel: set_tls_client_certificate: %w", toConnError(err)) + } + } if k.cfg.TLSSkipHostnameVerify { if err := call(func() C.KernelStatusCode { return C.kernel_session_config_set_tls_skip_hostname_verification(cfg, C.bool(true)) diff --git a/internal/backend/kernel/config.go b/internal/backend/kernel/config.go index 0ae2c7c0..a15f7227 100644 --- a/internal/backend/kernel/config.go +++ b/internal/backend/kernel/config.go @@ -34,9 +34,12 @@ type Config struct { // Experimental kernel-only TLS knobs (from the WithKernel* options). These // have no Thrift-path equivalent and are set via config.KernelExperimental. // Empty/false fields are simply not applied. TLSTrustedCertsPEM is a custom CA - // bundle added on top of the system roots; TLSSkipHostnameVerify skips only the + // bundle added on top of the system roots; TLSClientCertPEM/TLSClientKeyPEM + // are the paired mTLS client identity; TLSSkipHostnameVerify skips only the // hostname check (finer-grained than the blanket TLSSkipVerify above). TLSTrustedCertsPEM []byte + TLSClientCertPEM []byte + TLSClientKeyPEM []byte TLSSkipHostnameVerify bool // ProxyURL configures an HTTP proxy. It is either resolved for this endpoint diff --git a/internal/backend/kernel/kernel_test.go b/internal/backend/kernel/kernel_test.go index 04e061e2..4bf8f434 100644 --- a/internal/backend/kernel/kernel_test.go +++ b/internal/backend/kernel/kernel_test.go @@ -54,19 +54,26 @@ func TestSetAuthByMode(t *testing.T) { } // TestSetKernelTLS exercises the real cgo setters for the experimental kernel-only -// TLS knobs (the byte-buffer trusted-CA bundle + the hostname-skip bool) via the -// trySetKernelTLS seam — proving the (*C.uint8_t, C.size_t) marshalling and the C -// signatures. A failure here means the field→setter wiring or a C signature -// drifted. +// TLS knobs (trusted CA, paired mTLS identity, and hostname-skip bool) via the +// trySetKernelTLS seam — proving the (*C.uint8_t, C.size_t) marshalling and C +// signatures. A failure here means field→setter wiring or a C signature drifted. func TestSetKernelTLS(t *testing.T) { ca := []byte("-----BEGIN CERTIFICATE-----\nca\n-----END CERTIFICATE-----\n") + clientCert := []byte("client-cert") + clientKey := []byte("client-key") cases := []struct { name string cfg Config }{ {"trusted certs only", Config{TLSTrustedCertsPEM: ca}}, + {"mTLS identity only", Config{TLSClientCertPEM: clientCert, TLSClientKeyPEM: clientKey}}, {"skip hostname only", Config{TLSSkipHostnameVerify: true}}, - {"both together", Config{TLSTrustedCertsPEM: ca, TLSSkipHostnameVerify: true}}, + {"all together", Config{ + TLSTrustedCertsPEM: ca, + TLSClientCertPEM: clientCert, + TLSClientKeyPEM: clientKey, + TLSSkipHostnameVerify: true, + }}, {"none (no-op)", Config{}}, } for _, c := range cases { @@ -90,7 +97,7 @@ func TestSetProxy(t *testing.T) { }{ {"url only", Config{ProxyURL: "http://proxy:3128"}}, {"url + credentials", Config{ProxyURL: "http://proxy:3128", ProxyUsername: "u", ProxyPassword: "p"}}, - {"url + bypass", Config{ProxyURL: "http://proxy:3128", ProxyBypassHosts: "localhost,*.internal"}}, //nolint:gosec // G101: test literals, not real credentials + {"url + bypass", Config{ProxyURL: "http://proxy:3128", ProxyBypassHosts: "localhost,*.internal"}}, //nolint:gosec // G101: test literals, not real credentials {"all fields", Config{ProxyURL: "http://proxy:3128", ProxyUsername: "u", ProxyPassword: "p", ProxyBypassHosts: "localhost,*.internal"}}, //nolint:gosec // G101: test literals, not real credentials {"none (no-op)", Config{}}, } diff --git a/internal/config/config.go b/internal/config/config.go index 6434eb15..af95b1cc 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -72,6 +72,13 @@ type KernelExperimentalConfig struct { // Needed because the kernel's rustls stack ignores SSL_CERT_FILE, so a custom // CA must be handed to the kernel explicitly. TLSTrustedCertsPEM []byte + // TLSClientCertPEM / TLSClientKeyPEM are the paired mTLS client identity + // forwarded through kernel_session_config_set_tls_client_certificate. + // TLSClientCertConfigured distinguishes an explicit call with empty values + // from the option never being set, so invalid input cannot fail open. + TLSClientCertPEM []byte + TLSClientKeyPEM []byte + TLSClientCertConfigured bool // TLSSkipHostnameVerify skips only the certificate hostname check, independent // of the blanket InsecureSkipVerify (which relaxes both chain and hostname). // Maps to kernel_session_config_set_tls_skip_hostname_verification. @@ -121,18 +128,25 @@ func (k *KernelExperimentalConfig) DeepCopy() *KernelExperimentalConfig { return nil } cp := &KernelExperimentalConfig{ - TLSSkipHostnameVerify: k.TLSSkipHostnameVerify, - ProxyURL: k.ProxyURL, - ProxyUsername: k.ProxyUsername, - ProxyPassword: k.ProxyPassword, - ProxyBypassHosts: k.ProxyBypassHosts, - RetryOverallTimeout: k.RetryOverallTimeout, - MaxChunksInMemory: k.MaxChunksInMemory, - DecimalAsFloat: k.DecimalAsFloat, + TLSClientCertConfigured: k.TLSClientCertConfigured, + TLSSkipHostnameVerify: k.TLSSkipHostnameVerify, + ProxyURL: k.ProxyURL, + ProxyUsername: k.ProxyUsername, + ProxyPassword: k.ProxyPassword, + ProxyBypassHosts: k.ProxyBypassHosts, + RetryOverallTimeout: k.RetryOverallTimeout, + MaxChunksInMemory: k.MaxChunksInMemory, + DecimalAsFloat: k.DecimalAsFloat, } if k.TLSTrustedCertsPEM != nil { cp.TLSTrustedCertsPEM = append([]byte(nil), k.TLSTrustedCertsPEM...) } + if k.TLSClientCertPEM != nil { + cp.TLSClientCertPEM = append([]byte(nil), k.TLSClientCertPEM...) + } + if k.TLSClientKeyPEM != nil { + cp.TLSClientKeyPEM = append([]byte(nil), k.TLSClientKeyPEM...) + } return cp } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index c4160c25..4ef5a993 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -770,8 +770,11 @@ func TestConfig_DeepCopy(t *testing.T) { ThriftProtocolVersion: cli_service.TProtocolVersion_SPARK_CLI_SERVICE_PROTOCOL_V8, ThriftDebugClientProtocol: false, KernelExperimental: &KernelExperimentalConfig{ - TLSTrustedCertsPEM: []byte("ca-bundle"), - TLSSkipHostnameVerify: true, + TLSTrustedCertsPEM: []byte("ca-bundle"), + TLSClientCertPEM: []byte("client-cert"), + TLSClientKeyPEM: []byte("client-key"), + TLSClientCertConfigured: true, + TLSSkipHostnameVerify: true, }, } @@ -787,5 +790,11 @@ func TestConfig_DeepCopy(t *testing.T) { if cfg.KernelExperimental.TLSTrustedCertsPEM[0] == 'X' { t.Error("DeepCopy aliased the KernelExperimental CA byte slice") } + cfg_copy.KernelExperimental.TLSClientCertPEM[0] = 'X' + cfg_copy.KernelExperimental.TLSClientKeyPEM[0] = 'X' + if cfg.KernelExperimental.TLSClientCertPEM[0] == 'X' || + cfg.KernelExperimental.TLSClientKeyPEM[0] == 'X' { + t.Error("DeepCopy aliased the KernelExperimental mTLS byte slices") + } }) } diff --git a/kernel_config.go b/kernel_config.go index 9c67f751..00608cf2 100644 --- a/kernel_config.go +++ b/kernel_config.go @@ -113,6 +113,14 @@ func validateKernelConfigContext(ctx context.Context, cfg *config.Config) (kerne "(want a scheme and host, e.g. http://proxy:3128)", ke.ProxyURL, dbsqlerr.ErrInvalidKernelConfig) } } + if ke := cfg.KernelExperimental; ke != nil && ke.TLSClientCertConfigured { + if len(ke.TLSClientCertPEM) == 0 || len(ke.TLSClientKeyPEM) == 0 { + return kernel.Auth{}, fmt.Errorf( + "databricks: WithKernelClientCertificate requires a non-empty certificate and private key: %w", + dbsqlerr.ErrInvalidKernelConfig, + ) + } + } return kauth, nil } @@ -152,6 +160,8 @@ func buildKernelConfig(cfg *config.Config, kauth kernel.Auth) kernel.Config { // kernel C ABI in OpenSession. if ke := cfg.KernelExperimental; ke != nil { kc.TLSTrustedCertsPEM = ke.TLSTrustedCertsPEM + kc.TLSClientCertPEM = ke.TLSClientCertPEM + kc.TLSClientKeyPEM = ke.TLSClientKeyPEM kc.TLSSkipHostnameVerify = ke.TLSSkipHostnameVerify // Kernel-only CloudFetch in-memory-chunk knob (WithKernelMaxChunksInMemory). // Injected into the kernel backend's own SessionConf ONLY (not via diff --git a/kernel_config_test.go b/kernel_config_test.go index 3418e053..408ea907 100644 --- a/kernel_config_test.go +++ b/kernel_config_test.go @@ -322,6 +322,35 @@ func TestValidateKernelConfig(t *testing.T) { } }) + t.Run("valid WithKernelClientCertificate pair accepted", func(t *testing.T) { + c := baseKernelConfig() + WithKernelClientCertificate([]byte("cert"), []byte("key"))(c) + if _, err := validateKernelConfig(c); err != nil { + t.Errorf("a complete mTLS identity should validate, got %v", err) + } + }) + + t.Run("incomplete WithKernelClientCertificate rejected as ErrInvalidKernelConfig", func(t *testing.T) { + for _, tc := range []struct { + name string + cert []byte + key []byte + }{ + {"both empty", nil, nil}, + {"certificate empty", nil, []byte("key")}, + {"key empty", []byte("cert"), nil}, + } { + t.Run(tc.name, func(t *testing.T) { + c := baseKernelConfig() + WithKernelClientCertificate(tc.cert, tc.key)(c) + _, err := validateKernelConfig(c) + if !errors.Is(err, dbsqlerr.ErrInvalidKernelConfig) { + t.Errorf("incomplete mTLS identity should be ErrInvalidKernelConfig, got %v", err) + } + }) + } + }) + t.Run("malformed WithKernelProxy URL rejected as ErrInvalidKernelConfig", func(t *testing.T) { // A malformed URL must be caught in the Go layer with an errors.Is-able // config error, not surface as an opaque "kernel: set_proxy: …" wrap at @@ -457,8 +486,11 @@ func TestBuildKernelConfig(t *testing.T) { t.Run("experimental TLS fields forwarded", func(t *testing.T) { c := baseKernelConfig() c.KernelExperimental = &config.KernelExperimentalConfig{ - TLSTrustedCertsPEM: []byte("ca-bundle"), - TLSSkipHostnameVerify: true, + TLSTrustedCertsPEM: []byte("ca-bundle"), + TLSClientCertPEM: []byte("client-cert"), + TLSClientKeyPEM: []byte("client-key"), + TLSClientCertConfigured: true, + TLSSkipHostnameVerify: true, } kc := buildKernelConfig(c, kernel.Auth{Mode: kernel.AuthPAT, Token: "dapi-x"}) if got := string(kc.TLSTrustedCertsPEM); got != "ca-bundle" { @@ -467,14 +499,20 @@ func TestBuildKernelConfig(t *testing.T) { if !kc.TLSSkipHostnameVerify { t.Error("TLSSkipHostnameVerify = false, want true (WithKernelSkipHostnameVerify not forwarded)") } + if got := string(kc.TLSClientCertPEM); got != "client-cert" { + t.Errorf("TLSClientCertPEM = %q, want client-cert", got) + } + if got := string(kc.TLSClientKeyPEM); got != "client-key" { + t.Errorf("TLSClientKeyPEM = %q, want client-key", got) + } }) t.Run("nil KernelExperimental leaves TLS fields zero", func(t *testing.T) { c := baseKernelConfig() // KernelExperimental nil kc := buildKernelConfig(c, kernel.Auth{Mode: kernel.AuthPAT, Token: "dapi-x"}) - if kc.TLSTrustedCertsPEM != nil || kc.TLSSkipHostnameVerify { - t.Errorf("expected zero experimental TLS fields with nil KernelExperimental, got certs=%v skipHost=%v", - kc.TLSTrustedCertsPEM, kc.TLSSkipHostnameVerify) + if kc.TLSTrustedCertsPEM != nil || kc.TLSClientCertPEM != nil || + kc.TLSClientKeyPEM != nil || kc.TLSSkipHostnameVerify { + t.Errorf("expected zero experimental TLS fields with nil KernelExperimental, got %+v", kc) } }) diff --git a/kernel_experimental_test.go b/kernel_experimental_test.go index de9ef508..cb4dc8da 100644 --- a/kernel_experimental_test.go +++ b/kernel_experimental_test.go @@ -27,15 +27,18 @@ import ( // deliberate decision and a setter in KernelBackend.OpenSession so it can't be // silently dropped. var kernelExperimentalFieldDisposition = map[string]string{ - "TLSTrustedCertsPEM": "forwarded", // set_tls_trusted_certs - "TLSSkipHostnameVerify": "forwarded", // set_tls_skip_hostname_verification - "ProxyURL": "forwarded", // set_proxy (url) - "ProxyUsername": "forwarded", // set_proxy (username) - "ProxyPassword": "forwarded", // set_proxy (password) - "ProxyBypassHosts": "forwarded", // set_proxy (bypass_hosts) - "RetryOverallTimeout": "forwarded", // set_retry_config (overall_timeout_ms, 4th knob) - "MaxChunksInMemory": "forwarded", // set_session_conf (cloudfetch_max_chunks_in_memory, client-only) - "DecimalAsFloat": "forwarded", // kernel.Config.DecimalAsFloat → kernelOp → arrowscan (client-side scan choice) + "TLSTrustedCertsPEM": "forwarded", // set_tls_trusted_certs + "TLSClientCertPEM": "forwarded", // set_tls_client_certificate (cert) + "TLSClientKeyPEM": "forwarded", // set_tls_client_certificate (key) + "TLSClientCertConfigured": "validated", // distinguishes explicit empty input from unset + "TLSSkipHostnameVerify": "forwarded", // set_tls_skip_hostname_verification + "ProxyURL": "forwarded", // set_proxy (url) + "ProxyUsername": "forwarded", // set_proxy (username) + "ProxyPassword": "forwarded", // set_proxy (password) + "ProxyBypassHosts": "forwarded", // set_proxy (bypass_hosts) + "RetryOverallTimeout": "forwarded", // set_retry_config (overall_timeout_ms, 4th knob) + "MaxChunksInMemory": "forwarded", // set_session_conf (cloudfetch_max_chunks_in_memory, client-only) + "DecimalAsFloat": "forwarded", // kernel.Config.DecimalAsFloat → kernelOp → arrowscan (client-side scan choice) } func TestKernelExperimentalFieldsClassified(t *testing.T) { @@ -72,6 +75,10 @@ func TestWithKernelTLSOptionsSetExperimental(t *testing.T) { {"trusted certs", WithKernelTrustedCerts([]byte("ca")), func(k *config.KernelExperimentalConfig) bool { return string(k.TLSTrustedCertsPEM) == "ca" }}, + {"client certificate", WithKernelClientCertificate([]byte("cert"), []byte("key")), func(k *config.KernelExperimentalConfig) bool { + return k.TLSClientCertConfigured && string(k.TLSClientCertPEM) == "cert" && + string(k.TLSClientKeyPEM) == "key" + }}, {"skip hostname", WithKernelSkipHostnameVerify(), func(k *config.KernelExperimentalConfig) bool { return k.TLSSkipHostnameVerify }}, @@ -116,6 +123,7 @@ func TestWithKernelOptionsRejectedOnThriftPath(t *testing.T) { opt ConnOption }{ {"trusted certs", WithKernelTrustedCerts([]byte("ca"))}, + {"client certificate", WithKernelClientCertificate([]byte("cert"), []byte("key"))}, {"skip hostname", WithKernelSkipHostnameVerify()}, {"proxy", WithKernelProxy(KernelProxy{URL: "http://proxy:3128"})}, {"retry overall timeout", WithKernelRetryOverallTimeout(5 * time.Minute)}, @@ -175,19 +183,42 @@ func TestWithKernelTrustedCertsCopiesPEM(t *testing.T) { } } +func TestWithKernelClientCertificateCopiesPEM(t *testing.T) { + cert := []byte("client-cert") + key := []byte("client-key") + cfg := config.WithDefaults() + WithKernelClientCertificate(cert, key)(cfg) + + cert[0] = 'X' + key[0] = 'X' + + if cfg.KernelExperimental == nil { + t.Fatal("KernelExperimental should be non-nil after WithKernelClientCertificate") + } + if got := string(cfg.KernelExperimental.TLSClientCertPEM); got != "client-cert" { + t.Errorf("client certificate aliased caller input: got %q", got) + } + if got := string(cfg.KernelExperimental.TLSClientKeyPEM); got != "client-key" { + t.Errorf("client key aliased caller input: got %q", got) + } +} + // DeepCopy must copy the CA byte slice, not alias it — the connector may DeepCopy // the whole Config per conn, and a shared backing array would let one conn's // mutation reach another. func TestKernelExperimentalDeepCopy(t *testing.T) { orig := &config.KernelExperimentalConfig{ - TLSTrustedCertsPEM: []byte("ca-bundle"), - TLSSkipHostnameVerify: true, - ProxyURL: "http://proxy:3128", - ProxyUsername: "u", - ProxyPassword: "p", - ProxyBypassHosts: "*.internal", - RetryOverallTimeout: 5 * time.Minute, - MaxChunksInMemory: 4, + TLSTrustedCertsPEM: []byte("ca-bundle"), + TLSClientCertPEM: []byte("client-cert"), + TLSClientKeyPEM: []byte("client-key"), + TLSClientCertConfigured: true, + TLSSkipHostnameVerify: true, + ProxyURL: "http://proxy:3128", + ProxyUsername: "u", + ProxyPassword: "p", + ProxyBypassHosts: "*.internal", + RetryOverallTimeout: 5 * time.Minute, + MaxChunksInMemory: 4, } cp := orig.DeepCopy() if cp == nil || string(cp.TLSTrustedCertsPEM) != "ca-bundle" || !cp.TLSSkipHostnameVerify { @@ -203,10 +234,19 @@ func TestKernelExperimentalDeepCopy(t *testing.T) { if cp.MaxChunksInMemory != 4 { t.Errorf("DeepCopy lost MaxChunksInMemory: %v", cp.MaxChunksInMemory) } + if !cp.TLSClientCertConfigured || string(cp.TLSClientCertPEM) != "client-cert" || + string(cp.TLSClientKeyPEM) != "client-key" { + t.Errorf("DeepCopy lost mTLS fields: %+v", cp) + } cp.TLSTrustedCertsPEM[0] = 'X' if orig.TLSTrustedCertsPEM[0] == 'X' { t.Error("DeepCopy aliased the CA byte slice; a copy mutation reached the original") } + cp.TLSClientCertPEM[0] = 'X' + cp.TLSClientKeyPEM[0] = 'X' + if orig.TLSClientCertPEM[0] == 'X' || orig.TLSClientKeyPEM[0] == 'X' { + t.Error("DeepCopy aliased the mTLS byte slices") + } if (*config.KernelExperimentalConfig)(nil).DeepCopy() != nil { t.Error("nil.DeepCopy() should be nil") } diff --git a/kernel_mtls_test.go b/kernel_mtls_test.go new file mode 100644 index 00000000..6e731d9f --- /dev/null +++ b/kernel_mtls_test.go @@ -0,0 +1,194 @@ +//go:build cgo && databricks_kernel + +package dbsql + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "math/big" + "net" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" +) + +// This suite exercises the complete Go → cgo → kernel → rustls path against a +// local server that requires a verified client certificate. The server is not a +// SEA endpoint, so connection setup eventually fails at the application layer; +// reaching its handler proves the TLS handshake completed. + +type mtlsTestCertPair struct { + certPEM []byte + keyPEM []byte + tlsCert tls.Certificate +} + +func makeMTLSTestCA(t *testing.T) (*x509.Certificate, *ecdsa.PrivateKey, []byte) { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatalf("generate CA key: %v", err) + } + template := &x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: pkix.Name{CommonName: "databricks-sql-go mTLS test CA"}, + NotBefore: time.Unix(1_600_000_000, 0), + NotAfter: time.Unix(4_000_000_000, 0), + IsCA: true, + KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature, + BasicConstraintsValid: true, + } + der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key) + if err != nil { + t.Fatalf("create CA certificate: %v", err) + } + ca, err := x509.ParseCertificate(der) + if err != nil { + t.Fatalf("parse CA certificate: %v", err) + } + return ca, key, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) +} + +func makeMTLSTestLeaf( + t *testing.T, + ca *x509.Certificate, + caKey *ecdsa.PrivateKey, + commonName string, + serverIP net.IP, +) mtlsTestCertPair { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatalf("generate leaf key: %v", err) + } + template := &x509.Certificate{ + SerialNumber: big.NewInt(2), + Subject: pkix.Name{CommonName: commonName}, + NotBefore: time.Unix(1_600_000_000, 0), + NotAfter: time.Unix(4_000_000_000, 0), + KeyUsage: x509.KeyUsageDigitalSignature, + } + if serverIP != nil { + template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth} + template.IPAddresses = []net.IP{serverIP} + } else { + template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth} + } + der, err := x509.CreateCertificate(rand.Reader, template, ca, &key.PublicKey, caKey) + if err != nil { + t.Fatalf("create leaf certificate: %v", err) + } + certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) + keyDER, err := x509.MarshalPKCS8PrivateKey(key) + if err != nil { + t.Fatalf("marshal leaf key: %v", err) + } + keyPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER}) + tlsCert, err := tls.X509KeyPair(certPEM, keyPEM) + if err != nil { + t.Fatalf("parse leaf key pair: %v", err) + } + return mtlsTestCertPair{certPEM: certPEM, keyPEM: keyPEM, tlsCert: tlsCert} +} + +type mtlsProbe struct { + server *httptest.Server + reached atomic.Bool + sawCert atomic.Bool +} + +func startMTLSProbe( + t *testing.T, + serverCert tls.Certificate, + clientCAs *x509.CertPool, + clientAuth tls.ClientAuthType, +) *mtlsProbe { + t.Helper() + probe := &mtlsProbe{} + probe.server = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + probe.reached.Store(true) + probe.sawCert.Store(r.TLS != nil && len(r.TLS.PeerCertificates) > 0) + http.Error(w, "not a SEA endpoint", http.StatusServiceUnavailable) + })) + probe.server.TLS = &tls.Config{ + Certificates: []tls.Certificate{serverCert}, + ClientAuth: clientAuth, + ClientCAs: clientCAs, + MinVersion: tls.VersionTLS12, + } + probe.server.StartTLS() + t.Cleanup(probe.server.Close) + return probe +} + +func runMTLSKernelConnect(t *testing.T, host string, options ...ConnOption) { + t.Helper() + base := []ConnOption{ + WithServerHostname(host), + WithHTTPPath("/sql/1.0/warehouses/hermetic"), + WithAccessToken("dapi-hermetic-placeholder"), + WithUseKernel(true), + WithRetries(-1, 0, 0), + } + connector, err := NewConnector(append(base, options...)...) + if err != nil { + t.Fatalf("NewConnector: %v", err) + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if conn, err := connector.Connect(ctx); err == nil { + _ = conn.Close() + } +} + +func TestKernelMTLSHandshake(t *testing.T) { + ca, caKey, caPEM := makeMTLSTestCA(t) + serverCert := makeMTLSTestLeaf(t, ca, caKey, "127.0.0.1", net.ParseIP("127.0.0.1")) + clientCert := makeMTLSTestLeaf(t, ca, caKey, "hermetic-client", nil) + clientCAs := x509.NewCertPool() + clientCAs.AddCert(ca) + + t.Run("client identity reaches server", func(t *testing.T) { + probe := startMTLSProbe(t, serverCert.tlsCert, clientCAs, tls.RequireAndVerifyClientCert) + runMTLSKernelConnect( + t, + probe.server.Listener.Addr().String(), + WithKernelTrustedCerts(caPEM), + WithKernelClientCertificate(clientCert.certPEM, clientCert.keyPEM), + ) + if !probe.reached.Load() { + t.Fatal("server handler not reached: mTLS handshake did not complete") + } + if !probe.sawCert.Load() { + t.Fatal("server handler reached without the configured client certificate") + } + }) + + t.Run("unset client identity is not presented", func(t *testing.T) { + // The kernel repository's C-ABI E2E suite proves a server requiring a + // certificate rejects an anonymous client. Here the server requests and + // verifies a certificate when present but permits anonymity, which proves + // the Go option's unset path without provoking a peer-closed TLS write that + // can deliver SIGPIPE from the linked native stack. + probe := startMTLSProbe(t, serverCert.tlsCert, clientCAs, tls.VerifyClientCertIfGiven) + runMTLSKernelConnect( + t, + probe.server.Listener.Addr().String(), + WithKernelTrustedCerts(caPEM), + ) + if !probe.reached.Load() { + t.Fatal("server handler not reached for anonymous TLS connection") + } + if probe.sawCert.Load() { + t.Fatal("server saw a client certificate although the option was unset") + } + }) +}