From d5a6fdf7cbb535be85b80da5498830714c30a138 Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:25:16 +0000 Subject: [PATCH 01/17] feat(kernel): honor WithPort on the kernel backend The kernel backend rejected any WithPort other than 443. The kernel has no port setter, but it keeps a `host:port` authority in its host, so the connector now folds a non-default port into the host it passes to the kernel. - kernelHostWithPort adds a non-default port with net.JoinHostPort (IPv6-safe). The default 443 and an unset port add nothing. - validateKernelHostPort rejects an out-of-range port, a host with unbalanced IPv6 brackets (for example `[::1` or `h.databricks.com]`), and a supplied port that disagrees with a port embedded in the host. An unset port (WithDefaults fills 443) defers to the embedded port. An explicit WithPort(443) or DSN port is supplied, so it must match an embedded port too (AC-P3: never drop a port). - UserConfig gains an internal PortExplicit flag, set by WithPort and the DSN parser. It is not a public option: internal/ is not importable by users. - Non-https protocols and the other kernel rejections are unchanged. With OAuth (M2M and U2M) and a non-default port, the kernel reaches the OAuth endpoints at the same host:port as the connection. Thrift keeps OAuth on the bare host. This is documented in CONNECTION_PARAMETERS.md, the README and the CHANGELOG, and is not guarded. Tests: one table-driven TestKernelCustomPort covers the host mapping, the validation (accept and reject, including explicit 443 and unbalanced brackets), and the kernel Host. The config, connector and driver tests expect PortExplicit where WithPort or the DSN set the port. Co-authored-by: Isaac Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> --- CHANGELOG.md | 2 + CONNECTION_PARAMETERS.md | 2 +- README.md | 2 +- connector.go | 1 + connector_test.go | 1 + driver_test.go | 1 + internal/config/config.go | 11 +++-- internal/config/config_test.go | 25 ++++++++++ kernel_config.go | 66 +++++++++++++++++++++---- kernel_config_test.go | 90 ++++++++++++++++++++++++++++++++-- 10 files changed, 182 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d92df406..29847d143 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased (v2.0.0 prototype) +- Honor `WithPort` / DSN port on the kernel backend: a non-default port is folded into the host (`host:port`, IPv6-safe) instead of being rejected, and a port that conflicts with one embedded in the host, or is out of range, is rejected with `ErrInvalidKernelConfig`. With OAuth and a non-default port, the kernel uses the same `host:port` for OAuth; Thrift keeps OAuth on the bare host (documented, not guarded). + - Fix the module-root package conflict when building, linting, or running Gazelle with the `tools` build tag (databricks/databricks-sql-go#162). - **Behavior change:** Report declared DECIMAL precision and scale through `sql.ColumnType.DecimalSize()` on Thrift and SEA, including zero-row results. Tools such as ORM migrators can now act on these qualifiers (databricks/databricks-sql-go#500). - **Behavior change:** Support Arrow TIME results on Thrift and SEA as UTC `time.Time` values on `0001-01-01`, preserving precision and using clock-only nested JSON. TIME metadata now reports `TIME`/`time.Time` with no length, including empty and NULL-only results; previously Thrift reported `STRING`/`string` with unbounded length, and SEA reported an empty name with `*interface{}` (databricks/databricks-sql-go#505). diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 28624b378..7d06a0659 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -40,7 +40,7 @@ wire. They are listed under [Kernel client-result confs](#kernel-client-result-c |---|---|:---:|:---:|---|---| | *(host)* | `WithServerHostname` | ✅ | ✅ | *(required)* | Workspace hostname. | | *(path)* | `WithHTTPPath` | ✅ | ✅ | required on Thrift except localhost; required on kernel unless `warehouseId` is set | Warehouse/endpoint HTTP path. On the kernel path, a bare warehouse id can be used instead. | -| *(port)* | `WithPort` | ✅ | ⚠️ | `443` for connector options; required in a DSN | Kernel accepts **443 only** and rejects any other port. | +| *(port)* | `WithPort` | ✅ | ✅ | `443` for connector options; required in a DSN | Kernel folds a non-default port into the host it connects to; an out-of-range or conflicting port (including an explicit `WithPort(443)` against a host port) is rejected at connect. With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | | *(scheme)* | *(via `WithServerHostname`)* | ✅ | ⚠️ | `https` | Kernel accepts `https` only and rejects `http`. A bare `localhost` passed to `WithServerHostname` selects `http`; a scheme-less DSN, including localhost, is prefixed with `https`. | | `warehouseId` | `WithWarehouseID` | ⚠️ | ✅ | | Bare warehouse id. The kernel normally prefers it over the HTTP path; a canonical path carrying `?o=` takes precedence so workspace-org routing is preserved. The Thrift backend **silently ignores** it. | | `catalog` | `WithInitialNamespace` | ✅ | ✅ | | Initial catalog. Kernel applies it post-connect via `USE CATALOG`. | diff --git a/README.md b/README.md index c6b98b85c..8f784bfd6 100644 --- a/README.md +++ b/README.md @@ -240,7 +240,7 @@ session parameter on both backends. |---|---|---|---|---| | *(host)* | `WithServerHostname` | Both | *(required)* | Workspace hostname. | | *(path)* | `WithHTTPPath` | Both | *(required)* | Warehouse/endpoint HTTP path. | -| *(port)* | `WithPort` | Thrift only | `443` | Kernel connects on **443 only** and rejects any other port. | +| *(port)* | `WithPort` | Both | `443` | Kernel folds a non-default port into the host it connects to; an out-of-range or conflicting port is rejected at connect. With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | | `warehouseId` | `WithWarehouseID` | SEA only | | Bare warehouse id; the kernel routes by it (preferred over the HTTP path). **The Thrift backend ignores it.** | | `catalog` | `WithInitialNamespace` | Both | | Initial catalog. Kernel applies it post-connect via `USE CATALOG`. | | `schema` | `WithInitialNamespace` | Both | | Initial schema. Kernel applies it post-connect via `USE SCHEMA`. | diff --git a/connector.go b/connector.go index 1b72c6190..34c1350d4 100644 --- a/connector.go +++ b/connector.go @@ -367,6 +367,7 @@ func parseHostName(host string) (protocol, hostname string) { func WithPort(port int) ConnOption { return func(c *config.Config) { c.Port = port + c.PortExplicit = true } } diff --git a/connector_test.go b/connector_test.go index 684a8646f..2ecb02667 100644 --- a/connector_test.go +++ b/connector_test.go @@ -174,6 +174,7 @@ func TestNewConnector(t *testing.T) { expectedUserConfig := config.UserConfig{ Host: host, Port: port, + PortExplicit: true, Protocol: "https", AccessToken: accessToken, Authenticator: &pat.PATAuth{AccessToken: accessToken}, diff --git a/driver_test.go b/driver_test.go index 53aba0eb6..5aa6f4e8c 100644 --- a/driver_test.go +++ b/driver_test.go @@ -21,6 +21,7 @@ func TestOOpenConnector(t *testing.T) { expectedUserConfig := config.UserConfig{ Host: host, Port: port, + PortExplicit: true, Protocol: "https", AccessToken: accessToken, HTTPPath: "/" + httpPath, diff --git a/internal/config/config.go b/internal/config/config.go index f9c5143e2..3d808970b 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -265,9 +265,12 @@ func (c *Config) DeepCopy() *Config { // UserConfig is the set of configurations exposed to users type UserConfig struct { - Protocol string - Host string // from databricks UI - Port int // from databricks UI + Protocol string + Host string // from databricks UI + Port int // from databricks UI + // PortExplicit is true once WithPort or the DSN supplied Port (WithDefaults fills 443 otherwise). + // Internal only: kernel validation uses it to reject an explicit port that conflicts with a host port. + PortExplicit bool HTTPPath string // from databricks UI Catalog string Schema string @@ -342,6 +345,7 @@ func (ucfg UserConfig) DeepCopy() UserConfig { Protocol: ucfg.Protocol, Host: ucfg.Host, Port: ucfg.Port, + PortExplicit: ucfg.PortExplicit, HTTPPath: ucfg.HTTPPath, Catalog: ucfg.Catalog, Schema: ucfg.Schema, @@ -455,6 +459,7 @@ func ParseDSN(dsn string) (UserConfig, error) { return UserConfig{}, dbsqlerrint.NewRequestError(context.TODO(), dbsqlerr.ErrInvalidDSNPort, err) } ucfg.Port = port + ucfg.PortExplicit = true ucfg.HTTPPath = parsedURL.Path diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 518ccaf29..07c1bf7f2 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -38,6 +38,7 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 443, + PortExplicit: true, MaxRows: defaultMaxRows, Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, AccessToken: "supersecret", @@ -58,6 +59,7 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 443, + PortExplicit: true, MaxRows: defaultMaxRows, AccessToken: "supersecret", Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, @@ -78,6 +80,7 @@ func TestParseConfig(t *testing.T) { Protocol: "http", Host: "localhost", Port: 8080, + PortExplicit: true, MaxRows: defaultMaxRows, Authenticator: &noop.NoopAuth{}, HTTPPath: "/sql/1.0/endpoints/12346a5b5b0e123a", @@ -97,6 +100,7 @@ func TestParseConfig(t *testing.T) { Protocol: "http", Host: "localhost", Port: 8080, + PortExplicit: true, Authenticator: &noop.NoopAuth{}, MaxRows: defaultMaxRows, SessionParams: make(map[string]string), @@ -115,6 +119,7 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, + PortExplicit: true, AccessToken: "supersecret", Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, HTTPPath: "/sql/1.0/endpoints/12346a5b5b0e123a", @@ -136,6 +141,7 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, + PortExplicit: true, AccessToken: "supersecret", Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, HTTPPath: "/sql/1.0/endpoints/12346a5b5b0e123a", @@ -159,6 +165,7 @@ func TestParseConfig(t *testing.T) { Host: "example.cloud.databricks.com", Authenticator: &noop.NoopAuth{}, Port: 8000, + PortExplicit: true, MaxRows: defaultMaxRows, HTTPPath: "/sql/1.0/endpoints/12346a5b5b0e123a", SessionParams: make(map[string]string), @@ -177,6 +184,7 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, + PortExplicit: true, MaxRows: defaultMaxRows, AccessToken: "supersecret", Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, @@ -198,6 +206,7 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, + PortExplicit: true, MaxRows: defaultMaxRows, AccessToken: "supersecret", Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, @@ -219,6 +228,7 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, + PortExplicit: true, MaxRows: defaultMaxRows, AccessToken: "supersecret2", Authenticator: &pat.PATAuth{AccessToken: "supersecret2"}, @@ -240,6 +250,7 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, + PortExplicit: true, MaxRows: defaultMaxRows, AccessToken: "supersecret", Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, @@ -265,6 +276,7 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, + PortExplicit: true, MaxRows: defaultMaxRows, AccessToken: "supersecret", Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, @@ -286,6 +298,7 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, + PortExplicit: true, MaxRows: defaultMaxRows, AccessToken: "supersecret", Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, @@ -312,6 +325,7 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, + PortExplicit: true, AccessToken: "supersecret2", Authenticator: &pat.PATAuth{AccessToken: "supersecret2"}, HTTPPath: "/sql/1.0/endpoints/12346a5b5b0e123a", @@ -342,6 +356,7 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 443, + PortExplicit: true, MaxRows: defaultMaxRows, AccessToken: "supersecret", Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, @@ -362,6 +377,7 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 443, + PortExplicit: true, AccessToken: "supersecret2", Authenticator: &pat.PATAuth{AccessToken: "supersecret2"}, QueryTimeout: 100 * time.Second, @@ -419,6 +435,7 @@ func TestParseConfig(t *testing.T) { args: args{dsn: "token:supersecret2@:443?catalog=default&schema=system&timeout=100&maxRows=1000"}, wantCfg: UserConfig{ Port: 443, + PortExplicit: true, Protocol: "https", AccessToken: "supersecret2", Authenticator: &pat.PATAuth{AccessToken: "supersecret2"}, @@ -443,6 +460,7 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, + PortExplicit: true, AccessToken: "supersecret2", Authenticator: &pat.PATAuth{AccessToken: "supersecret2"}, HTTPPath: "/sql/1.0/endpoints/12346a5b5b0e123a", @@ -467,6 +485,7 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, + PortExplicit: true, AccessToken: "supersecret2", Authenticator: &pat.PATAuth{AccessToken: "supersecret2"}, HTTPPath: "/sql/1.0/endpoints/12346a5b5b0e123a", @@ -491,6 +510,7 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, + PortExplicit: true, AccessToken: "supersecret2", Authenticator: &pat.PATAuth{AccessToken: "supersecret2"}, HTTPPath: "/sql/1.0/endpoints/12346a5b5b0e123a", @@ -545,6 +565,7 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, + PortExplicit: true, Authenticator: m2m.NewAuthenticator("client_id", "client_secret", "example.cloud.databricks.com"), HTTPPath: "/sql/1.0/endpoints/12346a5b5b0e123a", QueryTimeout: 100 * time.Second, @@ -571,6 +592,7 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 443, + PortExplicit: true, MaxRows: defaultMaxRows, Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, AccessToken: "supersecret", @@ -597,6 +619,7 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 443, + PortExplicit: true, MaxRows: defaultMaxRows, Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, AccessToken: "supersecret", @@ -625,6 +648,7 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 443, + PortExplicit: true, MaxRows: defaultMaxRows, Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, AccessToken: "supersecret", @@ -646,6 +670,7 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 443, + PortExplicit: true, MaxRows: defaultMaxRows, Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, AccessToken: "supersecret", diff --git a/kernel_config.go b/kernel_config.go index 21a9f3cb1..c6c3a4ddf 100644 --- a/kernel_config.go +++ b/kernel_config.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "net" "net/url" "strconv" "strings" @@ -73,18 +74,14 @@ func validateKernelConfigContext(ctx context.Context, cfg *config.Config) (kerne // folds its server conf (spark.sql.thriftserver.metadata.metricview.enabled=true) // into SessionConf backend-neutrally, so the kernel path sends the identical conf // the Thrift path does. No per-backend handling needed here. - // Port / Protocol: the kernel C ABI takes only a bare host and connects over - // https:443; it has no port or scheme setter. The Thrift path honors a custom - // port/scheme via ToEndpointURL, so a non-default value here would be silently - // ignored on the kernel path (it would just hit 443) — reject it instead, per - // the "nothing silently ignored" contract. Defaults (https/443) are fine. + // Protocol: the kernel always connects over https, so a non-https value would be ignored. if cfg.Protocol != "" && cfg.Protocol != "https" { return kernel.Auth{}, fmt.Errorf("databricks: a non-https protocol is %w "+ "(it connects over https); use the default (Thrift) backend", dbsqlerr.ErrNotSupportedByKernel) } - if cfg.Port != 0 && cfg.Port != 443 { - return kernel.Auth{}, fmt.Errorf("databricks: a non-default port (WithPort) is %w "+ - "(it connects on 443); omit it or use the default (Thrift) backend", dbsqlerr.ErrNotSupportedByKernel) + // Port: the kernel folds host:port (see kernelHostWithPort); reject a bad port or a conflict here. + if err := validateKernelHostPort(cfg.Host, cfg.Port, cfg.PortExplicit); err != nil { + return kernel.Auth{}, err } // Transport (WithTransport, a custom http.RoundTripper carrying a custom CA // bundle / mTLS / proxy): the kernel uses its own Rust HTTP stack below the C @@ -155,7 +152,7 @@ func validateKernelConfigContext(ctx context.Context, cfg *config.Config) (kerne // with newKernelBackend's kernel.Config assembly. func buildKernelConfig(cfg *config.Config, kauth kernel.Auth) kernel.Config { kc := kernel.Config{ - Host: cfg.Host, + Host: kernelHostWithPort(cfg.Host, cfg.Port), HTTPPath: cfg.HTTPPath, WarehouseID: cfg.WarehouseID, Auth: kauth, @@ -239,6 +236,57 @@ func buildKernelConfig(cfg *config.Config, kauth kernel.Auth) kernel.Config { return kc } +// unbalancedBrackets reports a host whose IPv6 brackets do not pair up: an unclosed `[`, text +// after the closing `]` other than a `:port`, or a stray bracket in a plain name. +func unbalancedBrackets(host string) bool { + if !strings.HasPrefix(host, "[") { + return strings.ContainsAny(host, "[]") + } + end := strings.IndexByte(host, ']') + return end < 0 || (end+1 < len(host) && host[end+1] != ':') +} + +// validateKernelHostPort rejects an out-of-range port, a host with unbalanced IPv6 brackets, and a +// supplied port that disagrees with a port embedded in the host. explicit is true when WithPort or +// the DSN set the port. WithDefaults fills 443 otherwise, so an unset 443 defers to the embedded port. +func validateKernelHostPort(host string, port int, explicit bool) error { + if port < 0 || port > 65535 { + return fmt.Errorf("databricks: WithPort %d is out of range (want 1..65535): %w", port, dbsqlerr.ErrInvalidKernelConfig) + } + if unbalancedBrackets(host) { + return fmt.Errorf("databricks: host %q has unbalanced IPv6 brackets: %w", host, dbsqlerr.ErrInvalidKernelConfig) + } + _, p, err := net.SplitHostPort(host) + if err != nil { + return nil // no embedded port + } + embedded, err := strconv.Atoi(p) + if err != nil || embedded < 1 || embedded > 65535 { + return fmt.Errorf("databricks: host %q carries an invalid port %q (want 1..65535): %w", host, p, dbsqlerr.ErrInvalidKernelConfig) + } + if supplied := port != 0 && (explicit || port != 443); supplied && port != embedded { + return fmt.Errorf("databricks: host %q carries port %d but WithPort is %d: %w", host, embedded, port, dbsqlerr.ErrInvalidKernelConfig) + } + return nil +} + +// kernelHostWithPort returns the Host the kernel connects to. The kernel has no port setter but +// keeps a `host:port` authority, so a non-default port is folded in (IPv6-safe). 0 and 443 add +// nothing, and a host that already carries a port is returned unchanged. +func kernelHostWithPort(host string, port int) string { + if port == 0 || port == 443 { + return host + } + if _, _, err := net.SplitHostPort(host); err == nil { + return host + } + name := host + if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") { + name = host[1 : len(host)-1] + } + return net.JoinHostPort(name, strconv.Itoa(port)) +} + func kernelTelemetryConfig(cfg *config.Config) *kernel.TelemetryConfig { var enabled *bool if val, isSet := cfg.EnableTelemetry.Get(); isSet { diff --git a/kernel_config_test.go b/kernel_config_test.go index d8cd3c0c4..302826894 100644 --- a/kernel_config_test.go +++ b/kernel_config_test.go @@ -121,7 +121,6 @@ func TestValidateKernelConfig(t *testing.T) { }{ {"query timeout", func(c *config.Config) { c.QueryTimeout = 30 * time.Second }}, {"non-https protocol", func(c *config.Config) { c.Protocol = "http" }}, - {"non-default port", func(c *config.Config) { c.Port = 8443 }}, {"custom transport", func(c *config.Config) { c.Transport = http.DefaultTransport }}, } for _, tc := range rejections { @@ -443,10 +442,11 @@ var kernelConfigFieldDisposition = map[string]string{ "Schema": "forwarded", // Rejected loudly by validateKernelConfig. - "QueryTimeout": "rejected", // when > 0 (WithTimeout) - "Protocol": "rejected", // kernel is https-only; non-default rejected - "Port": "rejected", // kernel connects on 443; non-default rejected - "Transport": "rejected", // custom RoundTripper; kernel uses its own HTTP stack, so reject rather than drop + "QueryTimeout": "rejected", // when > 0 (WithTimeout) + "Protocol": "rejected", // kernel is https-only; non-default rejected + "Port": "forwarded", // folded into the kernel Host by kernelHostWithPort; validated by validateKernelHostPort + "PortExplicit": "forwarded", // set by WithPort / the DSN; consumed by validation, not sent to the kernel + "Transport": "rejected", // custom RoundTripper; kernel uses its own HTTP stack, so reject rather than drop // Forwarded to the kernel's HTTP retry config via kernelRetryConfig → // set_retry_config (WithRetries: backoff bounds + max attempts, incl. disable). @@ -972,3 +972,83 @@ func TestKernelRetryConfig(t *testing.T) { } }) } + +// TestKernelCustomPort covers WithPort on the kernel backend (AC-P1, AC-P3): a non-default port is +// folded into the kernel Host, 0 and 443 add nothing, and an out-of-range port, unbalanced IPv6 +// brackets, or a supplied port that disagrees with an embedded port is rejected with +// ErrInvalidKernelConfig. +func TestKernelCustomPort(t *testing.T) { + cases := []struct { + name string + host string + port int + explicit bool + wantHost string // kernelHostWithPort result for an accepted pair + wantErr bool + }{ + {"default 443 adds nothing", "h.databricks.com", 443, false, "h.databricks.com", false}, + {"unset port adds nothing", "h.databricks.com", 0, false, "h.databricks.com", false}, + {"custom port", "h.databricks.com", 8443, false, "h.databricks.com:8443", false}, + {"IPv4 literal", "127.0.0.1", 8443, false, "127.0.0.1:8443", false}, + {"bare IPv6 is bracketed", "::1", 8443, false, "[::1]:8443", false}, + {"bracketed IPv6", "[::1]", 8443, false, "[::1]:8443", false}, + {"port 1", "h.databricks.com", 1, false, "h.databricks.com:1", false}, + {"port 65535", "h.databricks.com", 65535, false, "h.databricks.com:65535", false}, + {"embedded port equal", "h.databricks.com:8443", 8443, true, "h.databricks.com:8443", false}, + {"embedded port equal, IPv6", "[::1]:8443", 8443, true, "[::1]:8443", false}, + {"unset 443 defers to embedded", "h.databricks.com:8443", 443, false, "h.databricks.com:8443", false}, + {"explicit 443 matches embedded", "h.databricks.com:443", 443, true, "h.databricks.com:443", false}, + {"explicit 443 conflicts with embedded", "h.databricks.com:8443", 443, true, "", true}, + {"negative port", "h.databricks.com", -1, false, "", true}, + {"port above range", "h.databricks.com", 65536, false, "", true}, + {"embedded port differs", "h.databricks.com:7000", 8443, false, "", true}, + {"embedded port differs, IPv6", "[::1]:7000", 8443, false, "", true}, + {"embedded port not a number", "h.databricks.com:notaport", 8443, false, "", true}, + {"embedded port out of range", "h.databricks.com:70000", 0, false, "", true}, + {"embedded port zero", "h.databricks.com:0", 0, false, "", true}, + {"unclosed IPv6 bracket", "[::1", 8443, false, "", true}, + {"text after IPv6 bracket", "[::1]x", 8443, false, "", true}, + {"stray closing bracket", "h.databricks.com]", 8443, false, "", true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := validateKernelHostPort(tc.host, tc.port, tc.explicit) + if tc.wantErr { + if !errors.Is(err, dbsqlerr.ErrInvalidKernelConfig) { + t.Errorf("err = %v, want ErrInvalidKernelConfig", err) + } + return + } + if err != nil { + t.Errorf("unexpected err %v", err) + } + if got := kernelHostWithPort(tc.host, tc.port); got != tc.wantHost { + t.Errorf("kernelHostWithPort(%q, %d) = %q, want %q", tc.host, tc.port, got, tc.wantHost) + } + }) + } + + t.Run("explicit WithPort(443) conflicting with an embedded port is rejected", func(t *testing.T) { + c := baseKernelConfig() + c.Host = "h.databricks.com:8443" + WithPort(443)(c) + if _, err := validateKernelConfig(c); !errors.Is(err, dbsqlerr.ErrInvalidKernelConfig) { + t.Errorf("err = %v, want ErrInvalidKernelConfig", err) + } + }) + + t.Run("kernel Host: unset port keeps the embedded port, custom port folds in", func(t *testing.T) { + c := baseKernelConfig() + c.Host = "h.databricks.com:8443" + kauth, err := validateKernelConfig(c) + if err != nil || buildKernelConfig(c, kauth).Host != "h.databricks.com:8443" { + t.Errorf("embedded port: err=%v host=%q", err, buildKernelConfig(c, kauth).Host) + } + c = baseKernelConfig() + WithPort(8443)(c) + kauth, err = validateKernelConfig(c) + if err != nil || buildKernelConfig(c, kauth).Host != "h.databricks.com:8443" { + t.Errorf("WithPort(8443): err=%v host=%q", err, buildKernelConfig(c, kauth).Host) + } + }) +} From ba84162a6778679fd3ee504df71f74b1fe62c7fb Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:26:48 +0000 Subject: [PATCH 02/17] fix(kernel): proxy lookup uses the kernel host authority proxyForEndpointFunc appended the port to cfg.Host even when the host already carried one, so host:8443 with Port 8443 built an invalid endpoint, the proxy was dropped and HTTPS_PROXY was ignored. It now uses the same authority as kernelHostWithPort, which leaves an embedded port alone and brackets IPv6 literals. Co-authored-by: Isaac Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> --- kernel_proxy.go | 7 +++---- kernel_proxy_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/kernel_proxy.go b/kernel_proxy.go index 9975e0abb..1c37b4450 100644 --- a/kernel_proxy.go +++ b/kernel_proxy.go @@ -43,10 +43,9 @@ func proxyForEndpointFunc(cfg *config.Config, resolve func(*http.Request) (*url. if scheme == "" { scheme = "https" } - endpoint := fmt.Sprintf("%s://%s", scheme, cfg.Host) - if cfg.Port != 0 { - endpoint = fmt.Sprintf("%s://%s:%d", scheme, cfg.Host, cfg.Port) - } + // Same authority the kernel connects to: an embedded port is not appended twice + // and an IPv6 literal is bracketed (kernelHostWithPort). + endpoint := fmt.Sprintf("%s://%s", scheme, kernelHostWithPort(cfg.Host, cfg.Port)) req, err := http.NewRequest(http.MethodPost, endpoint, nil) if err != nil { return "" diff --git a/kernel_proxy_test.go b/kernel_proxy_test.go index 3bfed8711..0e16f190f 100644 --- a/kernel_proxy_test.go +++ b/kernel_proxy_test.go @@ -55,6 +55,37 @@ func TestProxyForEndpoint(t *testing.T) { resolve: func(*http.Request) (*url.URL, error) { return proxyURL, nil }, want: "http://corp-proxy:3128", }, + { + name: "embedded port equal to Port is not doubled", + cfg: func() *config.Config { + c := config.WithDefaults() + c.Host = "my-workspace.databricks.com:8443" + c.Port = 8443 + c.HTTPPath = "/sql/1.0/warehouses/abc" + return c + }(), + resolve: func(*http.Request) (*url.URL, error) { return proxyURL, nil }, + want: "http://corp-proxy:3128", + }, + { + // An unbracketed IPv6 literal with a port must be bracketed in the endpoint, + // the same way the kernel Host is built. + name: "IPv6 literal with Port is bracketed", + cfg: func() *config.Config { + c := config.WithDefaults() + c.Host = "::1" + c.Port = 8443 + c.HTTPPath = "/sql/1.0/warehouses/abc" + return c + }(), + resolve: func(req *http.Request) (*url.URL, error) { + if req.URL.Host != "[::1]:8443" { + t.Errorf("endpoint host = %q, want %q", req.URL.Host, "[::1]:8443") + } + return proxyURL, nil + }, + want: "http://corp-proxy:3128", + }, { name: "host excluded by NO_PROXY -> direct", cfg: validCfg(), From 263c7415951fdd8c18a67736e0694d25393dc2dc Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:10:05 +0000 Subject: [PATCH 03/17] test(kernel): cover custom port on Reyden recovery; clarify port range Address the review nits on the kernel custom-port change: - The out-of-range WithPort error now says 0 is accepted as the default. - PortExplicit is classified as "validated", not "forwarded": it is consumed by validateKernelHostPort and never sent to the kernel. - A Reyden recovery test with WithPort(8443) asserts that the kernel Host is host:8443 after the Thrift KP001 rejection. The CHANGELOG entry mentions the recovery path. Co-authored-by: Isaac Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> --- CHANGELOG.md | 2 +- connector_reyden_test.go | 23 +++++++++++++++++++++++ kernel_config.go | 2 +- kernel_config_test.go | 2 +- 4 files changed, 26 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 29847d143..fec9afee6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased (v2.0.0 prototype) -- Honor `WithPort` / DSN port on the kernel backend: a non-default port is folded into the host (`host:port`, IPv6-safe) instead of being rejected, and a port that conflicts with one embedded in the host, or is out of range, is rejected with `ErrInvalidKernelConfig`. With OAuth and a non-default port, the kernel uses the same `host:port` for OAuth; Thrift keeps OAuth on the bare host (documented, not guarded). +- Honor `WithPort` / DSN port on the kernel backend, including the automatic Reyden recovery onto the kernel: a non-default port is folded into the host (`host:port`, IPv6-safe) instead of being rejected, and a port that conflicts with one embedded in the host, or is out of range, is rejected with `ErrInvalidKernelConfig`. With OAuth and a non-default port, the kernel uses the same `host:port` for OAuth; Thrift keeps OAuth on the bare host (documented, not guarded). - Fix the module-root package conflict when building, linting, or running Gazelle with the `tools` build tag (databricks/databricks-sql-go#162). - **Behavior change:** Report declared DECIMAL precision and scale through `sql.ColumnType.DecimalSize()` on Thrift and SEA, including zero-row results. Tools such as ORM migrators can now act on these qualifiers (databricks/databricks-sql-go#500). diff --git a/connector_reyden_test.go b/connector_reyden_test.go index 858d8ca35..0a89b3ea8 100644 --- a/connector_reyden_test.go +++ b/connector_reyden_test.go @@ -216,6 +216,29 @@ func TestReydenReactiveRecovery(t *testing.T) { assert.True(t, warehouse_cache.IsKnownReyden(tt.host, tt.warehouseID), "warehouse should be marked Reyden after the rejection") }) + + t.Run("recovery onto the kernel keeps a custom WithPort", func(t *testing.T) { + defer warehouse_cache.ClearCache() + + tt := NewTestReydenFallback() + var kernelHost string + conn := tt.makeConnector( + func(ctx context.Context, cfg *config.Config, client *http.Client) (backend.Backend, error) { + return &fakeThriftBackend{openSessionErr: dbsqlerrint.NewReydenThriftUnsupportedError( + "Lakehouse/RT is not supported for Thrift protocol")}, nil + }, + func(ctx context.Context, cfg *config.Config) (backend.Backend, error) { + require.NoError(t, validateKernelHostPort(cfg.Host, cfg.Port, cfg.PortExplicit)) + kernelHost = buildKernelConfig(cfg, kernel.Auth{Mode: kernel.AuthPAT, Token: "test-token"}).Host + return &fakeKernelBackend{}, nil + }, + ) + WithPort(8443)(conn.cfg) + + _, _, err := conn.openSessionWithReydenFallback(context.Background()) + require.NoError(t, err) + assert.Equal(t, "reyden.example.com:8443", kernelHost) + }) } func TestReydenPreCheck(t *testing.T) { diff --git a/kernel_config.go b/kernel_config.go index c6c3a4ddf..dabc3b9a0 100644 --- a/kernel_config.go +++ b/kernel_config.go @@ -251,7 +251,7 @@ func unbalancedBrackets(host string) bool { // the DSN set the port. WithDefaults fills 443 otherwise, so an unset 443 defers to the embedded port. func validateKernelHostPort(host string, port int, explicit bool) error { if port < 0 || port > 65535 { - return fmt.Errorf("databricks: WithPort %d is out of range (want 1..65535): %w", port, dbsqlerr.ErrInvalidKernelConfig) + return fmt.Errorf("databricks: WithPort %d is out of range (want 1..65535, or 0 for the default): %w", port, dbsqlerr.ErrInvalidKernelConfig) } if unbalancedBrackets(host) { return fmt.Errorf("databricks: host %q has unbalanced IPv6 brackets: %w", host, dbsqlerr.ErrInvalidKernelConfig) diff --git a/kernel_config_test.go b/kernel_config_test.go index 302826894..5e49d5e56 100644 --- a/kernel_config_test.go +++ b/kernel_config_test.go @@ -445,7 +445,7 @@ var kernelConfigFieldDisposition = map[string]string{ "QueryTimeout": "rejected", // when > 0 (WithTimeout) "Protocol": "rejected", // kernel is https-only; non-default rejected "Port": "forwarded", // folded into the kernel Host by kernelHostWithPort; validated by validateKernelHostPort - "PortExplicit": "forwarded", // set by WithPort / the DSN; consumed by validation, not sent to the kernel + "PortExplicit": "validated", // set by WithPort / the DSN; consumed by validation, not sent to the kernel "Transport": "rejected", // custom RoundTripper; kernel uses its own HTTP stack, so reject rather than drop // Forwarded to the kernel's HTTP retry config via kernelRetryConfig → From 7bc6a2ae823670091c5b39201520d647a37b2a9c Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:13:04 +0000 Subject: [PATCH 04/17] kernel: normalise trailing slash and embedded-port precedence for WithPort Fold a trailing "/" in the host before any port handling, matching the kernel's normalise_host, so WithServerHostname("https://h/") plus WithPort(8443) connects to h:8443 instead of h/:8443, and "https://h:8443/" keeps working. Port precedence now matches the Node and Python kernel paths: - A port embedded in the host wins over a differing WithPort. The driver logs a warning naming both ports and connects to the embedded port. - A zero (unset) WithPort means the default, with no :443 added. - A host with a path, query or fragment after the trimmed "/" is rejected with ErrInvalidKernelConfig. Base also rejected it: the kernel builds {host}/api/2.0/sql, so h/x sent requests to /x/api/2.0/sql. - Out-of-range WithPort and out-of-range or malformed embedded ports stay rejected. Thrift also fails on them: an embedded port plus the default 443 yields an unparseable https://h:8443:443 URL, -1 is an invalid port, and 70000 fails to dial. Base behavior (origin/main): validateKernelConfigContext rejected any WithPort other than 0 or 443 with ErrNotSupportedByKernel, and passed the host through unchanged, so an embedded port connected to that port. Tests: table cases for h/, h:8443/, h/x, [::1]/, embedded-vs-WithPort (warn, embedded wins), explicit 443 against an embedded port, and an invalid port (still rejected). Proxy endpoint test for a trailing-slash host. Kernel loopback probe: embedded port dialed, explicit port never. Co-authored-by: Isaac Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> --- CHANGELOG.md | 2 +- CONNECTION_PARAMETERS.md | 2 +- README.md | 2 +- kernel_config.go | 50 ++++++++++++++++++++++++++++++++-------- kernel_config_test.go | 50 +++++++++++++++++++++++++++++++++++----- kernel_proxy_test.go | 19 +++++++++++++++ 6 files changed, 107 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fec9afee6..9bf41163f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased (v2.0.0 prototype) -- Honor `WithPort` / DSN port on the kernel backend, including the automatic Reyden recovery onto the kernel: a non-default port is folded into the host (`host:port`, IPv6-safe) instead of being rejected, and a port that conflicts with one embedded in the host, or is out of range, is rejected with `ErrInvalidKernelConfig`. With OAuth and a non-default port, the kernel uses the same `host:port` for OAuth; Thrift keeps OAuth on the bare host (documented, not guarded). +- Honor `WithPort` / DSN port on the kernel backend, including the automatic Reyden recovery onto the kernel: a non-default port is folded into the host (`host:port`, IPv6-safe) instead of being rejected. A port embedded in the host wins over a differing `WithPort` (a warning is logged), a zero port means the default, and a trailing `/` on the host is ignored. An out-of-range port, or a host with a path, query or fragment, is rejected with `ErrInvalidKernelConfig`. With OAuth and a non-default port, the kernel uses the same `host:port` for OAuth; Thrift keeps OAuth on the bare host (documented, not guarded). - Fix the module-root package conflict when building, linting, or running Gazelle with the `tools` build tag (databricks/databricks-sql-go#162). - **Behavior change:** Report declared DECIMAL precision and scale through `sql.ColumnType.DecimalSize()` on Thrift and SEA, including zero-row results. Tools such as ORM migrators can now act on these qualifiers (databricks/databricks-sql-go#500). diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 7d06a0659..b7013f284 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -40,7 +40,7 @@ wire. They are listed under [Kernel client-result confs](#kernel-client-result-c |---|---|:---:|:---:|---|---| | *(host)* | `WithServerHostname` | ✅ | ✅ | *(required)* | Workspace hostname. | | *(path)* | `WithHTTPPath` | ✅ | ✅ | required on Thrift except localhost; required on kernel unless `warehouseId` is set | Warehouse/endpoint HTTP path. On the kernel path, a bare warehouse id can be used instead. | -| *(port)* | `WithPort` | ✅ | ✅ | `443` for connector options; required in a DSN | Kernel folds a non-default port into the host it connects to; an out-of-range or conflicting port (including an explicit `WithPort(443)` against a host port) is rejected at connect. With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | +| *(port)* | `WithPort` | ✅ | ✅ | `443` for connector options; required in a DSN | Kernel folds a non-default port into the host it connects to. A port embedded in the host wins over a differing `WithPort` (a warning is logged and the embedded port is used); an out-of-range port, or a host with a path, query or fragment, is rejected at connect. With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | | *(scheme)* | *(via `WithServerHostname`)* | ✅ | ⚠️ | `https` | Kernel accepts `https` only and rejects `http`. A bare `localhost` passed to `WithServerHostname` selects `http`; a scheme-less DSN, including localhost, is prefixed with `https`. | | `warehouseId` | `WithWarehouseID` | ⚠️ | ✅ | | Bare warehouse id. The kernel normally prefers it over the HTTP path; a canonical path carrying `?o=` takes precedence so workspace-org routing is preserved. The Thrift backend **silently ignores** it. | | `catalog` | `WithInitialNamespace` | ✅ | ✅ | | Initial catalog. Kernel applies it post-connect via `USE CATALOG`. | diff --git a/README.md b/README.md index 8f784bfd6..df43fa705 100644 --- a/README.md +++ b/README.md @@ -240,7 +240,7 @@ session parameter on both backends. |---|---|---|---|---| | *(host)* | `WithServerHostname` | Both | *(required)* | Workspace hostname. | | *(path)* | `WithHTTPPath` | Both | *(required)* | Warehouse/endpoint HTTP path. | -| *(port)* | `WithPort` | Both | `443` | Kernel folds a non-default port into the host it connects to; an out-of-range or conflicting port is rejected at connect. With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | +| *(port)* | `WithPort` | Both | `443` | Kernel folds a non-default port into the host it connects to. A port embedded in the host wins over a differing `WithPort` (a warning is logged); an out-of-range port, or a host with a path, query or fragment, is rejected at connect. With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | | `warehouseId` | `WithWarehouseID` | SEA only | | Bare warehouse id; the kernel routes by it (preferred over the HTTP path). **The Thrift backend ignores it.** | | `catalog` | `WithInitialNamespace` | Both | | Initial catalog. Kernel applies it post-connect via `USE CATALOG`. | | `schema` | `WithInitialNamespace` | Both | | Initial schema. Kernel applies it post-connect via `USE SCHEMA`. | diff --git a/kernel_config.go b/kernel_config.go index dabc3b9a0..b63f6673d 100644 --- a/kernel_config.go +++ b/kernel_config.go @@ -16,6 +16,7 @@ import ( "github.com/databricks/databricks-sql-go/internal/backend/kernel" "github.com/databricks/databricks-sql-go/internal/client" "github.com/databricks/databricks-sql-go/internal/config" + "github.com/databricks/databricks-sql-go/logger" "github.com/databricks/databricks-sql-go/telemetry" ) @@ -79,10 +80,12 @@ func validateKernelConfigContext(ctx context.Context, cfg *config.Config) (kerne return kernel.Auth{}, fmt.Errorf("databricks: a non-https protocol is %w "+ "(it connects over https); use the default (Thrift) backend", dbsqlerr.ErrNotSupportedByKernel) } - // Port: the kernel folds host:port (see kernelHostWithPort); reject a bad port or a conflict here. + // Port: the kernel folds host:port (see kernelHostWithPort); reject a bad port or host here. An + // embedded host port wins over a differing WithPort, with a warning rather than an error. if err := validateKernelHostPort(cfg.Host, cfg.Port, cfg.PortExplicit); err != nil { return kernel.Auth{}, err } + warnEmbeddedPortWins(cfg.Host, cfg.Port, cfg.PortExplicit) // Transport (WithTransport, a custom http.RoundTripper carrying a custom CA // bundle / mTLS / proxy): the kernel uses its own Rust HTTP stack below the C // ABI and never sees a Go RoundTripper, so a custom Transport would be silently @@ -246,13 +249,26 @@ func unbalancedBrackets(host string) bool { return end < 0 || (end+1 < len(host) && host[end+1] != ':') } -// validateKernelHostPort rejects an out-of-range port, a host with unbalanced IPv6 brackets, and a -// supplied port that disagrees with a port embedded in the host. explicit is true when WithPort or -// the DSN set the port. WithDefaults fills 443 otherwise, so an unset 443 defers to the embedded port. +// normaliseKernelHost trims trailing "/" the way the kernel's normalise_host does, so the port +// logic below sees the same authority the kernel connects to. +func normaliseKernelHost(host string) string { + return strings.TrimRight(host, "/") +} + +// validateKernelHostPort rejects an out-of-range WithPort, a host with a path, query or fragment, +// unbalanced IPv6 brackets, and an out-of-range or malformed port embedded in the host. explicit is +// true when WithPort or the DSN set the port. WithDefaults fills 443 otherwise. A port embedded in +// the host wins over WithPort (see warnEmbeddedPortWins), so a differing WithPort is not an error. func validateKernelHostPort(host string, port int, explicit bool) error { if port < 0 || port > 65535 { return fmt.Errorf("databricks: WithPort %d is out of range (want 1..65535, or 0 for the default): %w", port, dbsqlerr.ErrInvalidKernelConfig) } + host = normaliseKernelHost(host) + // A path, query or fragment after the host made the kernel URL point at the wrong place + // (the kernel appends /api/2.0/sql to the host), so it was never accepted. + if strings.ContainsAny(host, "/?#") { + return fmt.Errorf("databricks: host %q has a path, query or fragment: %w", host, dbsqlerr.ErrInvalidKernelConfig) + } if unbalancedBrackets(host) { return fmt.Errorf("databricks: host %q has unbalanced IPv6 brackets: %w", host, dbsqlerr.ErrInvalidKernelConfig) } @@ -264,16 +280,32 @@ func validateKernelHostPort(host string, port int, explicit bool) error { if err != nil || embedded < 1 || embedded > 65535 { return fmt.Errorf("databricks: host %q carries an invalid port %q (want 1..65535): %w", host, p, dbsqlerr.ErrInvalidKernelConfig) } - if supplied := port != 0 && (explicit || port != 443); supplied && port != embedded { - return fmt.Errorf("databricks: host %q carries port %d but WithPort is %d: %w", host, embedded, port, dbsqlerr.ErrInvalidKernelConfig) - } return nil } +// warnEmbeddedPortWins logs when a supplied port (WithPort or the DSN) differs from the port embedded +// in the host. The embedded port is used, as on the kernel path before WithPort was honored. +func warnEmbeddedPortWins(host string, port int, explicit bool) { + if port == 0 || (!explicit && port == 443) { + return + } + _, p, err := net.SplitHostPort(normaliseKernelHost(host)) + if err != nil { + return + } + embedded, err := strconv.Atoi(p) + if err != nil || embedded == port { + return + } + logger.Warn().Msgf("databricks: the host carries port %d, which differs from WithPort %d; connecting to port %d from the host", + embedded, port, embedded) +} + // kernelHostWithPort returns the Host the kernel connects to. The kernel has no port setter but -// keeps a `host:port` authority, so a non-default port is folded in (IPv6-safe). 0 and 443 add -// nothing, and a host that already carries a port is returned unchanged. +// keeps a `host:port` authority, so a non-default port is folded in (IPv6-safe). A trailing "/" is +// trimmed first. 0 and 443 add nothing, and a host that already carries a port is returned unchanged. func kernelHostWithPort(host string, port int) string { + host = normaliseKernelHost(host) if port == 0 || port == 443 { return host } diff --git a/kernel_config_test.go b/kernel_config_test.go index 5e49d5e56..885a10992 100644 --- a/kernel_config_test.go +++ b/kernel_config_test.go @@ -998,11 +998,20 @@ func TestKernelCustomPort(t *testing.T) { {"embedded port equal, IPv6", "[::1]:8443", 8443, true, "[::1]:8443", false}, {"unset 443 defers to embedded", "h.databricks.com:8443", 443, false, "h.databricks.com:8443", false}, {"explicit 443 matches embedded", "h.databricks.com:443", 443, true, "h.databricks.com:443", false}, - {"explicit 443 conflicts with embedded", "h.databricks.com:8443", 443, true, "", true}, + {"explicit 443 differs from embedded: embedded wins", "h.databricks.com:8443", 443, true, "h.databricks.com:8443", false}, + {"embedded port differs: embedded wins", "h.databricks.com:7000", 8443, false, "h.databricks.com:7000", false}, + {"embedded port differs, IPv6: embedded wins", "[::1]:7000", 8443, false, "[::1]:7000", false}, + {"trailing slash on bare host", "h.databricks.com/", 8443, false, "h.databricks.com:8443", false}, + {"trailing slash on bare host, default port", "h.databricks.com/", 443, false, "h.databricks.com", false}, + {"trailing slash with embedded port, default port", "h.databricks.com:8443/", 443, false, "h.databricks.com:8443", false}, + {"trailing slash with embedded port, equal port", "h.databricks.com:8443/", 8443, true, "h.databricks.com:8443", false}, + {"trailing slash, IPv6", "[::1]/", 8443, false, "[::1]:8443", false}, + {"path after host", "h.databricks.com/x", 8443, false, "", true}, + {"path after host, default port", "h.databricks.com/x", 443, false, "", true}, + {"query after host", "h.databricks.com?x", 8443, false, "", true}, + {"fragment after host", "h.databricks.com#x", 8443, false, "", true}, {"negative port", "h.databricks.com", -1, false, "", true}, {"port above range", "h.databricks.com", 65536, false, "", true}, - {"embedded port differs", "h.databricks.com:7000", 8443, false, "", true}, - {"embedded port differs, IPv6", "[::1]:7000", 8443, false, "", true}, {"embedded port not a number", "h.databricks.com:notaport", 8443, false, "", true}, {"embedded port out of range", "h.databricks.com:70000", 0, false, "", true}, {"embedded port zero", "h.databricks.com:0", 0, false, "", true}, @@ -1028,12 +1037,41 @@ func TestKernelCustomPort(t *testing.T) { }) } - t.Run("explicit WithPort(443) conflicting with an embedded port is rejected", func(t *testing.T) { + t.Run("explicit WithPort(443) differing from an embedded port connects to the embedded port", func(t *testing.T) { c := baseKernelConfig() c.Host = "h.databricks.com:8443" WithPort(443)(c) - if _, err := validateKernelConfig(c); !errors.Is(err, dbsqlerr.ErrInvalidKernelConfig) { - t.Errorf("err = %v, want ErrInvalidKernelConfig", err) + kauth, err := validateKernelConfig(c) + if err != nil { + t.Fatalf("unexpected err %v", err) + } + if got := buildKernelConfig(c, kauth).Host; got != "h.databricks.com:8443" { + t.Errorf("kernel Host = %q, want the embedded port h.databricks.com:8443", got) + } + }) + + t.Run("WithServerHostname with a trailing slash plus WithPort folds to host:port", func(t *testing.T) { + c := baseKernelConfig() + WithServerHostname("https://h.databricks.com/")(c) + WithPort(8443)(c) + kauth, err := validateKernelConfig(c) + if err != nil { + t.Fatalf("unexpected err %v", err) + } + if got := buildKernelConfig(c, kauth).Host; got != "h.databricks.com:8443" { + t.Errorf("kernel Host = %q, want h.databricks.com:8443", got) + } + }) + + t.Run("WithServerHostname with an embedded port and a trailing slash is still accepted", func(t *testing.T) { + c := baseKernelConfig() + WithServerHostname("https://h.databricks.com:8443/")(c) + kauth, err := validateKernelConfig(c) + if err != nil { + t.Fatalf("unexpected err %v", err) + } + if got := buildKernelConfig(c, kauth).Host; got != "h.databricks.com:8443" { + t.Errorf("kernel Host = %q, want h.databricks.com:8443", got) } }) diff --git a/kernel_proxy_test.go b/kernel_proxy_test.go index 0e16f190f..9316e4706 100644 --- a/kernel_proxy_test.go +++ b/kernel_proxy_test.go @@ -111,6 +111,25 @@ func TestProxyForEndpoint(t *testing.T) { }, want: "", }, + { + // A trailing "/" (WithServerHostname("https://h/")) is trimmed before the port is + // folded, so the endpoint is h:8443, not h/:8443. + name: "trailing slash host with Port folds to host:port", + cfg: func() *config.Config { + c := config.WithDefaults() + c.Host = "my-workspace.databricks.com/" + c.Port = 8443 + c.HTTPPath = "/sql/1.0/warehouses/abc" + return c + }(), + resolve: func(req *http.Request) (*url.URL, error) { + if req.URL.Host != "my-workspace.databricks.com:8443" { + t.Errorf("endpoint host = %q, want %q", req.URL.Host, "my-workspace.databricks.com:8443") + } + return proxyURL, nil + }, + want: "http://corp-proxy:3128", + }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { From 5615750373d4e90ad008c396bb73df8dd73f255c Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:21:23 +0000 Subject: [PATCH 05/17] kernel: reject paths before the embedded-port parse; no warning for explicit 443 - A host with a path or query is rejected before the embedded-port parse, so "h.io/path:8443" with an explicit port cannot slip through. The old code passed the host verbatim to the kernel, which builds {host}/api/2.0/sql, so these configs never connected. - The differing-port warning is skipped for an explicit 443 (the default). - Thrift is unchanged. TestThriftEndpointUnchanged pins its current endpoint strings for the same port inputs, including the embedded-port-plus-443 case. Co-authored-by: Isaac Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> --- internal/config/thrift_endpoint_test.go | 32 +++++++++++++++++++++++++ kernel_config.go | 11 +++++---- kernel_config_test.go | 4 ++++ 3 files changed, 42 insertions(+), 5 deletions(-) create mode 100644 internal/config/thrift_endpoint_test.go diff --git a/internal/config/thrift_endpoint_test.go b/internal/config/thrift_endpoint_test.go new file mode 100644 index 000000000..efdcf13b1 --- /dev/null +++ b/internal/config/thrift_endpoint_test.go @@ -0,0 +1,32 @@ +package config + +import "testing" + +// TestThriftEndpointUnchanged pins the Thrift endpoint for the port inputs the kernel custom-port +// change decides on. Thrift is not changed by that work, so these strings are what it builds today. +// An embedded host port plus the default 443 yields an unparseable URL on Thrift; that is the baseline. +func TestThriftEndpointUnchanged(t *testing.T) { + cases := []struct { + name string + host string + port int + want string + }{ + {"bare host, default port", "h.io", 443, "https://h.io:443/sql/1.0/warehouses/x"}, + {"bare host, WithPort", "h.io", 8443, "https://h.io:8443/sql/1.0/warehouses/x"}, + {"embedded port, default port", "h.io:8443", 443, "https://h.io:8443:443/sql/1.0/warehouses/x"}, + {"embedded port, WithPort", "h.io:8443", 8443, "https://h.io:8443:8443/sql/1.0/warehouses/x"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + c := &Config{Protocol: "https", Host: tc.host, Port: tc.port, HTTPPath: "/sql/1.0/warehouses/x"} + got, err := c.ToEndpointURL() + if err != nil { + t.Fatalf("unexpected err %v", err) + } + if got != tc.want { + t.Errorf("ToEndpointURL() = %q, want %q", got, tc.want) + } + }) + } +} diff --git a/kernel_config.go b/kernel_config.go index b63f6673d..0c1dd280b 100644 --- a/kernel_config.go +++ b/kernel_config.go @@ -85,7 +85,7 @@ func validateKernelConfigContext(ctx context.Context, cfg *config.Config) (kerne if err := validateKernelHostPort(cfg.Host, cfg.Port, cfg.PortExplicit); err != nil { return kernel.Auth{}, err } - warnEmbeddedPortWins(cfg.Host, cfg.Port, cfg.PortExplicit) + warnEmbeddedPortWins(cfg.Host, cfg.Port) // Transport (WithTransport, a custom http.RoundTripper carrying a custom CA // bundle / mTLS / proxy): the kernel uses its own Rust HTTP stack below the C // ABI and never sees a Go RoundTripper, so a custom Transport would be silently @@ -283,10 +283,11 @@ func validateKernelHostPort(host string, port int, explicit bool) error { return nil } -// warnEmbeddedPortWins logs when a supplied port (WithPort or the DSN) differs from the port embedded -// in the host. The embedded port is used, as on the kernel path before WithPort was honored. -func warnEmbeddedPortWins(host string, port int, explicit bool) { - if port == 0 || (!explicit && port == 443) { +// warnEmbeddedPortWins logs when a non-default port (WithPort or the DSN) differs from the port embedded +// in the host. The embedded port is used, as on the kernel path before WithPort was honored. An +// explicit 443 is the default and is not warned about. +func warnEmbeddedPortWins(host string, port int) { + if port == 0 || port == 443 { return } _, p, err := net.SplitHostPort(normaliseKernelHost(host)) diff --git a/kernel_config_test.go b/kernel_config_test.go index 885a10992..d60865b77 100644 --- a/kernel_config_test.go +++ b/kernel_config_test.go @@ -1007,6 +1007,10 @@ func TestKernelCustomPort(t *testing.T) { {"trailing slash with embedded port, equal port", "h.databricks.com:8443/", 8443, true, "h.databricks.com:8443", false}, {"trailing slash, IPv6", "[::1]/", 8443, false, "[::1]:8443", false}, {"path after host", "h.databricks.com/x", 8443, false, "", true}, + {"path with embedded port and WithPort", "h.io/path:8443", 8443, true, "", true}, + {"path with embedded port, default port", "h.io/path:8443", 443, false, "", true}, + {"query before embedded port", "h.io?q=1:8443", 8443, true, "", true}, + {"explicit 443 with embedded port: embedded wins", "h.io:8443", 443, true, "h.io:8443", false}, {"path after host, default port", "h.databricks.com/x", 443, false, "", true}, {"query after host", "h.databricks.com?x", 8443, false, "", true}, {"fragment after host", "h.databricks.com#x", 8443, false, "", true}, From 52bd5ac9567549480c3bdee0e6179d67b360d7e5 Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:31:59 +0000 Subject: [PATCH 06/17] kernel: keep path hosts unchanged on the default port; drop PortExplicit - A host with a path, query or fragment is now rejected only when a non-default WithPort would have to be folded into it. The check still runs after the trailing "/" trim and before the embedded-port parse. With no port or 443 the host goes to the kernel unchanged, as on the base branch, where the kernel keeps a path prefix ({host}/api/2.0/sql). The base branch rejected every non-default WithPort, so nothing that worked before is rejected now. - Remove the internal PortExplicit field. Once an explicit 443 stopped warning, nothing read it, so WithPort, ParseDSN, DeepCopy and their tests are back to the base branch. Co-authored-by: Isaac Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> --- CHANGELOG.md | 2 +- CONNECTION_PARAMETERS.md | 2 +- README.md | 2 +- connector.go | 1 - connector_reyden_test.go | 2 +- connector_test.go | 1 - driver_test.go | 1 - internal/config/config.go | 11 ++--- internal/config/config_test.go | 25 ---------- kernel_config.go | 23 ++++++---- kernel_config_test.go | 83 ++++++++++++++++------------------ 11 files changed, 61 insertions(+), 92 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9bf41163f..bc66df216 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased (v2.0.0 prototype) -- Honor `WithPort` / DSN port on the kernel backend, including the automatic Reyden recovery onto the kernel: a non-default port is folded into the host (`host:port`, IPv6-safe) instead of being rejected. A port embedded in the host wins over a differing `WithPort` (a warning is logged), a zero port means the default, and a trailing `/` on the host is ignored. An out-of-range port, or a host with a path, query or fragment, is rejected with `ErrInvalidKernelConfig`. With OAuth and a non-default port, the kernel uses the same `host:port` for OAuth; Thrift keeps OAuth on the bare host (documented, not guarded). +- Honor `WithPort` / DSN port on the kernel backend, including the automatic Reyden recovery onto the kernel: a non-default port is folded into the host (`host:port`, IPv6-safe) instead of being rejected. A port embedded in the host wins over a differing `WithPort` (a warning is logged), a zero port means the default, and a trailing `/` on the host is ignored. An out-of-range port, or a non-default port with a host that has a path, query or fragment, is rejected with `ErrInvalidKernelConfig`. With OAuth and a non-default port, the kernel uses the same `host:port` for OAuth; Thrift keeps OAuth on the bare host (documented, not guarded). - Fix the module-root package conflict when building, linting, or running Gazelle with the `tools` build tag (databricks/databricks-sql-go#162). - **Behavior change:** Report declared DECIMAL precision and scale through `sql.ColumnType.DecimalSize()` on Thrift and SEA, including zero-row results. Tools such as ORM migrators can now act on these qualifiers (databricks/databricks-sql-go#500). diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index b7013f284..3d09179b6 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -40,7 +40,7 @@ wire. They are listed under [Kernel client-result confs](#kernel-client-result-c |---|---|:---:|:---:|---|---| | *(host)* | `WithServerHostname` | ✅ | ✅ | *(required)* | Workspace hostname. | | *(path)* | `WithHTTPPath` | ✅ | ✅ | required on Thrift except localhost; required on kernel unless `warehouseId` is set | Warehouse/endpoint HTTP path. On the kernel path, a bare warehouse id can be used instead. | -| *(port)* | `WithPort` | ✅ | ✅ | `443` for connector options; required in a DSN | Kernel folds a non-default port into the host it connects to. A port embedded in the host wins over a differing `WithPort` (a warning is logged and the embedded port is used); an out-of-range port, or a host with a path, query or fragment, is rejected at connect. With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | +| *(port)* | `WithPort` | ✅ | ✅ | `443` for connector options; required in a DSN | Kernel folds a non-default port into the host it connects to. A port embedded in the host wins over a differing `WithPort` (a warning is logged and the embedded port is used); an out-of-range port, or a non-default port with a host that has a path, query or fragment, is rejected at connect. With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | | *(scheme)* | *(via `WithServerHostname`)* | ✅ | ⚠️ | `https` | Kernel accepts `https` only and rejects `http`. A bare `localhost` passed to `WithServerHostname` selects `http`; a scheme-less DSN, including localhost, is prefixed with `https`. | | `warehouseId` | `WithWarehouseID` | ⚠️ | ✅ | | Bare warehouse id. The kernel normally prefers it over the HTTP path; a canonical path carrying `?o=` takes precedence so workspace-org routing is preserved. The Thrift backend **silently ignores** it. | | `catalog` | `WithInitialNamespace` | ✅ | ✅ | | Initial catalog. Kernel applies it post-connect via `USE CATALOG`. | diff --git a/README.md b/README.md index df43fa705..0dae21b15 100644 --- a/README.md +++ b/README.md @@ -240,7 +240,7 @@ session parameter on both backends. |---|---|---|---|---| | *(host)* | `WithServerHostname` | Both | *(required)* | Workspace hostname. | | *(path)* | `WithHTTPPath` | Both | *(required)* | Warehouse/endpoint HTTP path. | -| *(port)* | `WithPort` | Both | `443` | Kernel folds a non-default port into the host it connects to. A port embedded in the host wins over a differing `WithPort` (a warning is logged); an out-of-range port, or a host with a path, query or fragment, is rejected at connect. With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | +| *(port)* | `WithPort` | Both | `443` | Kernel folds a non-default port into the host it connects to. A port embedded in the host wins over a differing `WithPort` (a warning is logged); an out-of-range port, or a non-default port with a host that has a path, query or fragment, is rejected at connect. With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | | `warehouseId` | `WithWarehouseID` | SEA only | | Bare warehouse id; the kernel routes by it (preferred over the HTTP path). **The Thrift backend ignores it.** | | `catalog` | `WithInitialNamespace` | Both | | Initial catalog. Kernel applies it post-connect via `USE CATALOG`. | | `schema` | `WithInitialNamespace` | Both | | Initial schema. Kernel applies it post-connect via `USE SCHEMA`. | diff --git a/connector.go b/connector.go index 34c1350d4..1b72c6190 100644 --- a/connector.go +++ b/connector.go @@ -367,7 +367,6 @@ func parseHostName(host string) (protocol, hostname string) { func WithPort(port int) ConnOption { return func(c *config.Config) { c.Port = port - c.PortExplicit = true } } diff --git a/connector_reyden_test.go b/connector_reyden_test.go index 0a89b3ea8..d789631c0 100644 --- a/connector_reyden_test.go +++ b/connector_reyden_test.go @@ -228,7 +228,7 @@ func TestReydenReactiveRecovery(t *testing.T) { "Lakehouse/RT is not supported for Thrift protocol")}, nil }, func(ctx context.Context, cfg *config.Config) (backend.Backend, error) { - require.NoError(t, validateKernelHostPort(cfg.Host, cfg.Port, cfg.PortExplicit)) + require.NoError(t, validateKernelHostPort(cfg.Host, cfg.Port)) kernelHost = buildKernelConfig(cfg, kernel.Auth{Mode: kernel.AuthPAT, Token: "test-token"}).Host return &fakeKernelBackend{}, nil }, diff --git a/connector_test.go b/connector_test.go index 2ecb02667..684a8646f 100644 --- a/connector_test.go +++ b/connector_test.go @@ -174,7 +174,6 @@ func TestNewConnector(t *testing.T) { expectedUserConfig := config.UserConfig{ Host: host, Port: port, - PortExplicit: true, Protocol: "https", AccessToken: accessToken, Authenticator: &pat.PATAuth{AccessToken: accessToken}, diff --git a/driver_test.go b/driver_test.go index 5aa6f4e8c..53aba0eb6 100644 --- a/driver_test.go +++ b/driver_test.go @@ -21,7 +21,6 @@ func TestOOpenConnector(t *testing.T) { expectedUserConfig := config.UserConfig{ Host: host, Port: port, - PortExplicit: true, Protocol: "https", AccessToken: accessToken, HTTPPath: "/" + httpPath, diff --git a/internal/config/config.go b/internal/config/config.go index 3d808970b..f9c5143e2 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -265,12 +265,9 @@ func (c *Config) DeepCopy() *Config { // UserConfig is the set of configurations exposed to users type UserConfig struct { - Protocol string - Host string // from databricks UI - Port int // from databricks UI - // PortExplicit is true once WithPort or the DSN supplied Port (WithDefaults fills 443 otherwise). - // Internal only: kernel validation uses it to reject an explicit port that conflicts with a host port. - PortExplicit bool + Protocol string + Host string // from databricks UI + Port int // from databricks UI HTTPPath string // from databricks UI Catalog string Schema string @@ -345,7 +342,6 @@ func (ucfg UserConfig) DeepCopy() UserConfig { Protocol: ucfg.Protocol, Host: ucfg.Host, Port: ucfg.Port, - PortExplicit: ucfg.PortExplicit, HTTPPath: ucfg.HTTPPath, Catalog: ucfg.Catalog, Schema: ucfg.Schema, @@ -459,7 +455,6 @@ func ParseDSN(dsn string) (UserConfig, error) { return UserConfig{}, dbsqlerrint.NewRequestError(context.TODO(), dbsqlerr.ErrInvalidDSNPort, err) } ucfg.Port = port - ucfg.PortExplicit = true ucfg.HTTPPath = parsedURL.Path diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 07c1bf7f2..518ccaf29 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -38,7 +38,6 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 443, - PortExplicit: true, MaxRows: defaultMaxRows, Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, AccessToken: "supersecret", @@ -59,7 +58,6 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 443, - PortExplicit: true, MaxRows: defaultMaxRows, AccessToken: "supersecret", Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, @@ -80,7 +78,6 @@ func TestParseConfig(t *testing.T) { Protocol: "http", Host: "localhost", Port: 8080, - PortExplicit: true, MaxRows: defaultMaxRows, Authenticator: &noop.NoopAuth{}, HTTPPath: "/sql/1.0/endpoints/12346a5b5b0e123a", @@ -100,7 +97,6 @@ func TestParseConfig(t *testing.T) { Protocol: "http", Host: "localhost", Port: 8080, - PortExplicit: true, Authenticator: &noop.NoopAuth{}, MaxRows: defaultMaxRows, SessionParams: make(map[string]string), @@ -119,7 +115,6 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, - PortExplicit: true, AccessToken: "supersecret", Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, HTTPPath: "/sql/1.0/endpoints/12346a5b5b0e123a", @@ -141,7 +136,6 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, - PortExplicit: true, AccessToken: "supersecret", Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, HTTPPath: "/sql/1.0/endpoints/12346a5b5b0e123a", @@ -165,7 +159,6 @@ func TestParseConfig(t *testing.T) { Host: "example.cloud.databricks.com", Authenticator: &noop.NoopAuth{}, Port: 8000, - PortExplicit: true, MaxRows: defaultMaxRows, HTTPPath: "/sql/1.0/endpoints/12346a5b5b0e123a", SessionParams: make(map[string]string), @@ -184,7 +177,6 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, - PortExplicit: true, MaxRows: defaultMaxRows, AccessToken: "supersecret", Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, @@ -206,7 +198,6 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, - PortExplicit: true, MaxRows: defaultMaxRows, AccessToken: "supersecret", Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, @@ -228,7 +219,6 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, - PortExplicit: true, MaxRows: defaultMaxRows, AccessToken: "supersecret2", Authenticator: &pat.PATAuth{AccessToken: "supersecret2"}, @@ -250,7 +240,6 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, - PortExplicit: true, MaxRows: defaultMaxRows, AccessToken: "supersecret", Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, @@ -276,7 +265,6 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, - PortExplicit: true, MaxRows: defaultMaxRows, AccessToken: "supersecret", Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, @@ -298,7 +286,6 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, - PortExplicit: true, MaxRows: defaultMaxRows, AccessToken: "supersecret", Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, @@ -325,7 +312,6 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, - PortExplicit: true, AccessToken: "supersecret2", Authenticator: &pat.PATAuth{AccessToken: "supersecret2"}, HTTPPath: "/sql/1.0/endpoints/12346a5b5b0e123a", @@ -356,7 +342,6 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 443, - PortExplicit: true, MaxRows: defaultMaxRows, AccessToken: "supersecret", Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, @@ -377,7 +362,6 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 443, - PortExplicit: true, AccessToken: "supersecret2", Authenticator: &pat.PATAuth{AccessToken: "supersecret2"}, QueryTimeout: 100 * time.Second, @@ -435,7 +419,6 @@ func TestParseConfig(t *testing.T) { args: args{dsn: "token:supersecret2@:443?catalog=default&schema=system&timeout=100&maxRows=1000"}, wantCfg: UserConfig{ Port: 443, - PortExplicit: true, Protocol: "https", AccessToken: "supersecret2", Authenticator: &pat.PATAuth{AccessToken: "supersecret2"}, @@ -460,7 +443,6 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, - PortExplicit: true, AccessToken: "supersecret2", Authenticator: &pat.PATAuth{AccessToken: "supersecret2"}, HTTPPath: "/sql/1.0/endpoints/12346a5b5b0e123a", @@ -485,7 +467,6 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, - PortExplicit: true, AccessToken: "supersecret2", Authenticator: &pat.PATAuth{AccessToken: "supersecret2"}, HTTPPath: "/sql/1.0/endpoints/12346a5b5b0e123a", @@ -510,7 +491,6 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, - PortExplicit: true, AccessToken: "supersecret2", Authenticator: &pat.PATAuth{AccessToken: "supersecret2"}, HTTPPath: "/sql/1.0/endpoints/12346a5b5b0e123a", @@ -565,7 +545,6 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 8000, - PortExplicit: true, Authenticator: m2m.NewAuthenticator("client_id", "client_secret", "example.cloud.databricks.com"), HTTPPath: "/sql/1.0/endpoints/12346a5b5b0e123a", QueryTimeout: 100 * time.Second, @@ -592,7 +571,6 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 443, - PortExplicit: true, MaxRows: defaultMaxRows, Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, AccessToken: "supersecret", @@ -619,7 +597,6 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 443, - PortExplicit: true, MaxRows: defaultMaxRows, Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, AccessToken: "supersecret", @@ -648,7 +625,6 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 443, - PortExplicit: true, MaxRows: defaultMaxRows, Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, AccessToken: "supersecret", @@ -670,7 +646,6 @@ func TestParseConfig(t *testing.T) { Protocol: "https", Host: "example.cloud.databricks.com", Port: 443, - PortExplicit: true, MaxRows: defaultMaxRows, Authenticator: &pat.PATAuth{AccessToken: "supersecret"}, AccessToken: "supersecret", diff --git a/kernel_config.go b/kernel_config.go index 0c1dd280b..d841d30b8 100644 --- a/kernel_config.go +++ b/kernel_config.go @@ -82,7 +82,7 @@ func validateKernelConfigContext(ctx context.Context, cfg *config.Config) (kerne } // Port: the kernel folds host:port (see kernelHostWithPort); reject a bad port or host here. An // embedded host port wins over a differing WithPort, with a warning rather than an error. - if err := validateKernelHostPort(cfg.Host, cfg.Port, cfg.PortExplicit); err != nil { + if err := validateKernelHostPort(cfg.Host, cfg.Port); err != nil { return kernel.Auth{}, err } warnEmbeddedPortWins(cfg.Host, cfg.Port) @@ -255,19 +255,24 @@ func normaliseKernelHost(host string) string { return strings.TrimRight(host, "/") } -// validateKernelHostPort rejects an out-of-range WithPort, a host with a path, query or fragment, -// unbalanced IPv6 brackets, and an out-of-range or malformed port embedded in the host. explicit is -// true when WithPort or the DSN set the port. WithDefaults fills 443 otherwise. A port embedded in -// the host wins over WithPort (see warnEmbeddedPortWins), so a differing WithPort is not an error. -func validateKernelHostPort(host string, port int, explicit bool) error { +// validateKernelHostPort rejects an out-of-range WithPort, a non-default WithPort with a host that has +// a path, query or fragment, unbalanced IPv6 brackets, and an out-of-range or malformed port embedded +// in the host. WithDefaults fills 443 when no port is set. A port embedded in the host wins over +// WithPort (see warnEmbeddedPortWins), so a differing WithPort is not an error. +func validateKernelHostPort(host string, port int) error { if port < 0 || port > 65535 { return fmt.Errorf("databricks: WithPort %d is out of range (want 1..65535, or 0 for the default): %w", port, dbsqlerr.ErrInvalidKernelConfig) } host = normaliseKernelHost(host) - // A path, query or fragment after the host made the kernel URL point at the wrong place - // (the kernel appends /api/2.0/sql to the host), so it was never accepted. + // A path, query or fragment is checked before the embedded-port parse. With the default port the + // host goes to the kernel unchanged, as before (the kernel appends its API paths after it). A + // non-default port cannot be folded into such a host, and was rejected before, so reject it. if strings.ContainsAny(host, "/?#") { - return fmt.Errorf("databricks: host %q has a path, query or fragment: %w", host, dbsqlerr.ErrInvalidKernelConfig) + if port != 0 && port != 443 { + return fmt.Errorf("databricks: host %q has a path, query or fragment, so WithPort %d cannot be applied: %w", + host, port, dbsqlerr.ErrInvalidKernelConfig) + } + return nil } if unbalancedBrackets(host) { return fmt.Errorf("databricks: host %q has unbalanced IPv6 brackets: %w", host, dbsqlerr.ErrInvalidKernelConfig) diff --git a/kernel_config_test.go b/kernel_config_test.go index d60865b77..0926fb4b1 100644 --- a/kernel_config_test.go +++ b/kernel_config_test.go @@ -445,7 +445,6 @@ var kernelConfigFieldDisposition = map[string]string{ "QueryTimeout": "rejected", // when > 0 (WithTimeout) "Protocol": "rejected", // kernel is https-only; non-default rejected "Port": "forwarded", // folded into the kernel Host by kernelHostWithPort; validated by validateKernelHostPort - "PortExplicit": "validated", // set by WithPort / the DSN; consumed by validation, not sent to the kernel "Transport": "rejected", // custom RoundTripper; kernel uses its own HTTP stack, so reject rather than drop // Forwarded to the kernel's HTTP retry config via kernelRetryConfig → @@ -973,59 +972,57 @@ func TestKernelRetryConfig(t *testing.T) { }) } -// TestKernelCustomPort covers WithPort on the kernel backend (AC-P1, AC-P3): a non-default port is -// folded into the kernel Host, 0 and 443 add nothing, and an out-of-range port, unbalanced IPv6 -// brackets, or a supplied port that disagrees with an embedded port is rejected with -// ErrInvalidKernelConfig. +// TestKernelCustomPort covers WithPort on the kernel backend: a non-default port is folded into the +// kernel Host, 0 and 443 add nothing, a port embedded in the host wins, a trailing "/" is trimmed, +// and a host with a path passes through unchanged unless a non-default port would be folded into it. +// An out-of-range port or unbalanced IPv6 brackets are rejected with ErrInvalidKernelConfig. func TestKernelCustomPort(t *testing.T) { cases := []struct { name string host string port int - explicit bool wantHost string // kernelHostWithPort result for an accepted pair wantErr bool }{ - {"default 443 adds nothing", "h.databricks.com", 443, false, "h.databricks.com", false}, - {"unset port adds nothing", "h.databricks.com", 0, false, "h.databricks.com", false}, - {"custom port", "h.databricks.com", 8443, false, "h.databricks.com:8443", false}, - {"IPv4 literal", "127.0.0.1", 8443, false, "127.0.0.1:8443", false}, - {"bare IPv6 is bracketed", "::1", 8443, false, "[::1]:8443", false}, - {"bracketed IPv6", "[::1]", 8443, false, "[::1]:8443", false}, - {"port 1", "h.databricks.com", 1, false, "h.databricks.com:1", false}, - {"port 65535", "h.databricks.com", 65535, false, "h.databricks.com:65535", false}, - {"embedded port equal", "h.databricks.com:8443", 8443, true, "h.databricks.com:8443", false}, - {"embedded port equal, IPv6", "[::1]:8443", 8443, true, "[::1]:8443", false}, - {"unset 443 defers to embedded", "h.databricks.com:8443", 443, false, "h.databricks.com:8443", false}, - {"explicit 443 matches embedded", "h.databricks.com:443", 443, true, "h.databricks.com:443", false}, - {"explicit 443 differs from embedded: embedded wins", "h.databricks.com:8443", 443, true, "h.databricks.com:8443", false}, - {"embedded port differs: embedded wins", "h.databricks.com:7000", 8443, false, "h.databricks.com:7000", false}, - {"embedded port differs, IPv6: embedded wins", "[::1]:7000", 8443, false, "[::1]:7000", false}, - {"trailing slash on bare host", "h.databricks.com/", 8443, false, "h.databricks.com:8443", false}, - {"trailing slash on bare host, default port", "h.databricks.com/", 443, false, "h.databricks.com", false}, - {"trailing slash with embedded port, default port", "h.databricks.com:8443/", 443, false, "h.databricks.com:8443", false}, - {"trailing slash with embedded port, equal port", "h.databricks.com:8443/", 8443, true, "h.databricks.com:8443", false}, - {"trailing slash, IPv6", "[::1]/", 8443, false, "[::1]:8443", false}, - {"path after host", "h.databricks.com/x", 8443, false, "", true}, - {"path with embedded port and WithPort", "h.io/path:8443", 8443, true, "", true}, - {"path with embedded port, default port", "h.io/path:8443", 443, false, "", true}, - {"query before embedded port", "h.io?q=1:8443", 8443, true, "", true}, - {"explicit 443 with embedded port: embedded wins", "h.io:8443", 443, true, "h.io:8443", false}, - {"path after host, default port", "h.databricks.com/x", 443, false, "", true}, - {"query after host", "h.databricks.com?x", 8443, false, "", true}, - {"fragment after host", "h.databricks.com#x", 8443, false, "", true}, - {"negative port", "h.databricks.com", -1, false, "", true}, - {"port above range", "h.databricks.com", 65536, false, "", true}, - {"embedded port not a number", "h.databricks.com:notaport", 8443, false, "", true}, - {"embedded port out of range", "h.databricks.com:70000", 0, false, "", true}, - {"embedded port zero", "h.databricks.com:0", 0, false, "", true}, - {"unclosed IPv6 bracket", "[::1", 8443, false, "", true}, - {"text after IPv6 bracket", "[::1]x", 8443, false, "", true}, - {"stray closing bracket", "h.databricks.com]", 8443, false, "", true}, + {"default 443 adds nothing", "h.databricks.com", 443, "h.databricks.com", false}, + {"unset port adds nothing", "h.databricks.com", 0, "h.databricks.com", false}, + {"custom port", "h.databricks.com", 8443, "h.databricks.com:8443", false}, + {"IPv4 literal", "127.0.0.1", 8443, "127.0.0.1:8443", false}, + {"bare IPv6 is bracketed", "::1", 8443, "[::1]:8443", false}, + {"bracketed IPv6", "[::1]", 8443, "[::1]:8443", false}, + {"port 1", "h.databricks.com", 1, "h.databricks.com:1", false}, + {"port 65535", "h.databricks.com", 65535, "h.databricks.com:65535", false}, + {"embedded port equal", "h.databricks.com:8443", 8443, "h.databricks.com:8443", false}, + {"embedded port equal, IPv6", "[::1]:8443", 8443, "[::1]:8443", false}, + {"443 with embedded 443", "h.databricks.com:443", 443, "h.databricks.com:443", false}, + {"443 with embedded port: embedded wins", "h.databricks.com:8443", 443, "h.databricks.com:8443", false}, + {"embedded port differs: embedded wins", "h.databricks.com:7000", 8443, "h.databricks.com:7000", false}, + {"embedded port differs, IPv6: embedded wins", "[::1]:7000", 8443, "[::1]:7000", false}, + {"trailing slash on bare host", "h.databricks.com/", 8443, "h.databricks.com:8443", false}, + {"trailing slash on bare host, default port", "h.databricks.com/", 443, "h.databricks.com", false}, + {"trailing slash with embedded port, default port", "h.databricks.com:8443/", 443, "h.databricks.com:8443", false}, + {"trailing slash with embedded port, equal port", "h.databricks.com:8443/", 8443, "h.databricks.com:8443", false}, + {"trailing slash, IPv6", "[::1]/", 8443, "[::1]:8443", false}, + {"path, default port: unchanged", "h.databricks.com/x", 443, "h.databricks.com/x", false}, + {"path, unset port: unchanged", "h.databricks.com/x", 0, "h.databricks.com/x", false}, + {"path with colon, default port: unchanged", "h.io/path:8443", 443, "h.io/path:8443", false}, + {"path with custom port", "h.databricks.com/x", 8443, "", true}, + {"path with colon and custom port", "h.io/path:8443", 8443, "", true}, + {"query with colon and custom port", "h.io?q=1:8443", 8443, "", true}, + {"query with custom port", "h.databricks.com?x", 8443, "", true}, + {"fragment with custom port", "h.databricks.com#x", 8443, "", true}, + {"negative port", "h.databricks.com", -1, "", true}, + {"port above range", "h.databricks.com", 65536, "", true}, + {"embedded port not a number", "h.databricks.com:notaport", 8443, "", true}, + {"embedded port out of range", "h.databricks.com:70000", 0, "", true}, + {"embedded port zero", "h.databricks.com:0", 0, "", true}, + {"unclosed IPv6 bracket", "[::1", 8443, "", true}, + {"text after IPv6 bracket", "[::1]x", 8443, "", true}, + {"stray closing bracket", "h.databricks.com]", 8443, "", true}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - err := validateKernelHostPort(tc.host, tc.port, tc.explicit) + err := validateKernelHostPort(tc.host, tc.port) if tc.wantErr { if !errors.Is(err, dbsqlerr.ErrInvalidKernelConfig) { t.Errorf("err = %v, want ErrInvalidKernelConfig", err) From c2bcd489ccf5f83d1f1ef4c73259b58c13634f9a Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:56:30 +0000 Subject: [PATCH 07/17] kernel: parse the kernel host with net/url The kernel path folds WithPort into cfg.Host. The host is now parsed once per call with net/url, as the https authority the kernel connects to, instead of net.SplitHostPort plus hand-written bracket and path scans. Rules (unchanged unless noted): - A trailing "/" is trimmed first. With the default port (0 or 443) the host passes through unchanged. - A port embedded in the host wins over a differing WithPort, with a warning. An explicit 443, or 0, is the default and is never warned about. - WithPort outside 1..65535 is rejected. An embedded port that is empty, non-numeric or outside 1..65535 is rejected. - With a non-default port, a host with a path, query, fragment (including an empty "h#" or "h?") or user info is rejected. Unbalanced brackets are rejected. - Errors wrap ErrInvalidKernelConfig as before. Behavior changes from the reviewed revision (52bd5ac): - An IPv6 literal must be bracketed. A bare "::1" is rejected at any port (net/url cannot parse it). It never connected on main either: the kernel prepends https:// and its parse rejects it. - A host with a password ("user:pw@h") is rejected at any port. - A host net/url cannot parse (for example "h%zz" or a space) is rejected even at the default port, where it used to pass through to the kernel. The parse-once wrappers and the separate warning helper are gone: validateKernelHostPort logs the embedded-port warning, and kernelHostWithPort is the only fold, so buildKernelConfig and resolveKernelProxy keep their reviewed signatures. Co-authored-by: Isaac Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> --- CHANGELOG.md | 2 +- CONNECTION_PARAMETERS.md | 2 +- README.md | 2 +- kernel_config.go | 129 +++++++++++++++++++++------------------ kernel_config_test.go | 32 +++++++++- kernel_proxy_test.go | 6 +- 6 files changed, 104 insertions(+), 69 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d4ff273c7..f25e63f59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased (v2.0.0 prototype) -- Honor `WithPort` / DSN port on the kernel backend, including the automatic Reyden recovery onto the kernel: a non-default port is folded into the host (`host:port`, IPv6-safe) instead of being rejected. A port embedded in the host wins over a differing `WithPort` (a warning is logged), a zero port means the default, and a trailing `/` on the host is ignored. An out-of-range port, or a non-default port with a host that has a path, query or fragment, is rejected with `ErrInvalidKernelConfig`. With OAuth and a non-default port, the kernel uses the same `host:port` for OAuth; Thrift keeps OAuth on the bare host (documented, not guarded). +- Honor `WithPort` / DSN port on the kernel backend, including the automatic Reyden recovery onto the kernel: a non-default port is folded into the host (`host:port`; an IPv6 literal must be bracketed, as `[::1]:8443`) instead of being rejected. A port embedded in the host wins over a differing `WithPort` (a warning is logged), a zero port means the default, and a trailing `/` on the host is ignored. An out-of-range port, a malformed or empty port in the host, or a non-default port with a host that has a path, query, fragment or credentials, is rejected with `ErrInvalidKernelConfig`. With OAuth and a non-default port, the kernel uses the same `host:port` for OAuth; Thrift keeps OAuth on the bare host (documented, not guarded). - Render non-finite FLOAT / DOUBLE values inside ARRAY / MAP / STRUCT results as the JSON strings `"NaN"`, `"Infinity"`, and `"-Infinity"` on both backends instead of failing row iteration. SQL NULL remains `null`; top-level floats remain numeric (databricks/databricks-sql-go#573). - **Behavior change:** Non-finite floating-point MAP keys use the same spellings as values on both backends. On the kernel backend, keys previously rendered as `"+Inf"` and `"-Inf"` now render as `"Infinity"` and `"-Infinity"`; `"NaN"` is unchanged. On Thrift, these keys previously failed row iteration (databricks/databricks-sql-go#573). - Fix the module-root package conflict when building, linting, or running Gazelle with the `tools` build tag (databricks/databricks-sql-go#162). diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 3d09179b6..18920a258 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -40,7 +40,7 @@ wire. They are listed under [Kernel client-result confs](#kernel-client-result-c |---|---|:---:|:---:|---|---| | *(host)* | `WithServerHostname` | ✅ | ✅ | *(required)* | Workspace hostname. | | *(path)* | `WithHTTPPath` | ✅ | ✅ | required on Thrift except localhost; required on kernel unless `warehouseId` is set | Warehouse/endpoint HTTP path. On the kernel path, a bare warehouse id can be used instead. | -| *(port)* | `WithPort` | ✅ | ✅ | `443` for connector options; required in a DSN | Kernel folds a non-default port into the host it connects to. A port embedded in the host wins over a differing `WithPort` (a warning is logged and the embedded port is used); an out-of-range port, or a non-default port with a host that has a path, query or fragment, is rejected at connect. With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | +| *(port)* | `WithPort` | ✅ | ✅ | `443` for connector options; required in a DSN | Kernel folds a non-default port into the host it connects to. A port embedded in the host wins over a differing `WithPort` (a warning is logged and the embedded port is used); an out-of-range port, a malformed port in the host, or a non-default port with a host that has a path, query, fragment or credentials, is rejected at connect. An IPv6 literal must be bracketed (`[::1]`, not `::1`). With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | | *(scheme)* | *(via `WithServerHostname`)* | ✅ | ⚠️ | `https` | Kernel accepts `https` only and rejects `http`. A bare `localhost` passed to `WithServerHostname` selects `http`; a scheme-less DSN, including localhost, is prefixed with `https`. | | `warehouseId` | `WithWarehouseID` | ⚠️ | ✅ | | Bare warehouse id. The kernel normally prefers it over the HTTP path; a canonical path carrying `?o=` takes precedence so workspace-org routing is preserved. The Thrift backend **silently ignores** it. | | `catalog` | `WithInitialNamespace` | ✅ | ✅ | | Initial catalog. Kernel applies it post-connect via `USE CATALOG`. | diff --git a/README.md b/README.md index ef83c70a1..e187e97ce 100644 --- a/README.md +++ b/README.md @@ -240,7 +240,7 @@ session parameter on both backends. |---|---|---|---|---| | *(host)* | `WithServerHostname` | Both | *(required)* | Workspace hostname. | | *(path)* | `WithHTTPPath` | Both | *(required)* | Warehouse/endpoint HTTP path. | -| *(port)* | `WithPort` | Both | `443` | Kernel folds a non-default port into the host it connects to. A port embedded in the host wins over a differing `WithPort` (a warning is logged); an out-of-range port, or a non-default port with a host that has a path, query or fragment, is rejected at connect. With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | +| *(port)* | `WithPort` | Both | `443` | Kernel folds a non-default port into the host it connects to. A port embedded in the host wins over a differing `WithPort` (a warning is logged); an out-of-range port, a malformed port in the host, or a non-default port with a host that has a path, query, fragment or credentials, is rejected at connect. An IPv6 literal must be bracketed (`[::1]`, not `::1`). With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | | `warehouseId` | `WithWarehouseID` | SEA only | | Bare warehouse id; the kernel routes by it (preferred over the HTTP path). **The Thrift backend ignores it.** | | `catalog` | `WithInitialNamespace` | Both | | Initial catalog. Kernel applies it post-connect via `USE CATALOG`. | | `schema` | `WithInitialNamespace` | Both | | Initial schema. Kernel applies it post-connect via `USE SCHEMA`. | diff --git a/kernel_config.go b/kernel_config.go index d841d30b8..b1c04f0dc 100644 --- a/kernel_config.go +++ b/kernel_config.go @@ -85,7 +85,6 @@ func validateKernelConfigContext(ctx context.Context, cfg *config.Config) (kerne if err := validateKernelHostPort(cfg.Host, cfg.Port); err != nil { return kernel.Auth{}, err } - warnEmbeddedPortWins(cfg.Host, cfg.Port) // Transport (WithTransport, a custom http.RoundTripper carrying a custom CA // bundle / mTLS / proxy): the kernel uses its own Rust HTTP stack below the C // ABI and never sees a Go RoundTripper, so a custom Transport would be silently @@ -239,90 +238,98 @@ func buildKernelConfig(cfg *config.Config, kauth kernel.Auth) kernel.Config { return kc } -// unbalancedBrackets reports a host whose IPv6 brackets do not pair up: an unclosed `[`, text -// after the closing `]` other than a `:port`, or a stray bracket in a plain name. -func unbalancedBrackets(host string) bool { - if !strings.HasPrefix(host, "[") { - return strings.ContainsAny(host, "[]") - } - end := strings.IndexByte(host, ']') - return end < 0 || (end+1 < len(host) && host[end+1] != ':') +// kernelHost is cfg.Host split by net/url: the parts the kernel port logic needs. +type kernelHost struct { + raw string // cfg.Host with a trailing "/" trimmed; the kernel gets it unchanged when no port is folded + name string // host name without IPv6 brackets (url.URL.Hostname) + port string // digits after the authority's ":"; "" when there is none + hasPort bool // the authority has a ":", even with no digits after it ("h:") + hasPath bool // a path, query or fragment follows the host, or a bare "#" (url.URL drops an empty fragment) + userinfo bool // a user@ prefix is present + password bool // the user@ prefix carries a password } -// normaliseKernelHost trims trailing "/" the way the kernel's normalise_host does, so the port -// logic below sees the same authority the kernel connects to. -func normaliseKernelHost(host string) string { - return strings.TrimRight(host, "/") +// parseKernelHost parses cfg.Host (trailing "/" trimmed) as the authority of an https URL, which is the +// form the kernel connects to. The error is url.Parse's; the fields are set only when it is nil. +func parseKernelHost(host string) (kernelHost, error) { + h := kernelHost{raw: strings.TrimRight(host, "/")} + u, err := url.Parse("https://" + h.raw) + if err != nil { + return h, err + } + h.name = u.Hostname() + h.port = u.Port() + h.hasPort = h.port != "" || strings.HasSuffix(u.Host, ":") + h.hasPath = u.Path != "" || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || strings.Contains(h.raw, "#") + h.userinfo = u.User != nil + _, h.password = u.User.Password() + return h, nil } -// validateKernelHostPort rejects an out-of-range WithPort, a non-default WithPort with a host that has -// a path, query or fragment, unbalanced IPv6 brackets, and an out-of-range or malformed port embedded -// in the host. WithDefaults fills 443 when no port is set. A port embedded in the host wins over -// WithPort (see warnEmbeddedPortWins), so a differing WithPort is not an error. +// validateKernelHostPort rejects an out-of-range WithPort, a host that net/url cannot parse (an IPv6 +// literal must be bracketed), and a non-default WithPort with a host that has a path, query, fragment or +// credentials. It also rejects unbalanced brackets and an empty, out-of-range or malformed port embedded +// in the host. WithDefaults fills 443 when no port is set. A port embedded in the host wins over a +// differing WithPort, with a warning rather than an error. func validateKernelHostPort(host string, port int) error { if port < 0 || port > 65535 { return fmt.Errorf("databricks: WithPort %d is out of range (want 1..65535, or 0 for the default): %w", port, dbsqlerr.ErrInvalidKernelConfig) } - host = normaliseKernelHost(host) + h, err := parseKernelHost(host) + if err != nil { + return fmt.Errorf("databricks: host %q is not a valid host (bracket an IPv6 literal): %v: %w", h.raw, err, dbsqlerr.ErrInvalidKernelConfig) + } + nonDefault := port != 0 && port != 443 // A path, query or fragment is checked before the embedded-port parse. With the default port the // host goes to the kernel unchanged, as before (the kernel appends its API paths after it). A - // non-default port cannot be folded into such a host, and was rejected before, so reject it. - if strings.ContainsAny(host, "/?#") { - if port != 0 && port != 443 { + // non-default port cannot be folded into such a host, so reject it. + if h.hasPath { + if nonDefault { return fmt.Errorf("databricks: host %q has a path, query or fragment, so WithPort %d cannot be applied: %w", - host, port, dbsqlerr.ErrInvalidKernelConfig) + h.raw, port, dbsqlerr.ErrInvalidKernelConfig) } return nil } - if unbalancedBrackets(host) { - return fmt.Errorf("databricks: host %q has unbalanced IPv6 brackets: %w", host, dbsqlerr.ErrInvalidKernelConfig) + // Credentials are kept only at the default port: a non-default port would have to be folded in without them. + if h.userinfo && nonDefault { + return fmt.Errorf("databricks: host %q carries credentials, so WithPort %d cannot be applied: %w", + h.raw, port, dbsqlerr.ErrInvalidKernelConfig) } - _, p, err := net.SplitHostPort(host) - if err != nil { - return nil // no embedded port + if h.password { + return fmt.Errorf("databricks: host %q carries a password: %w", h.raw, dbsqlerr.ErrInvalidKernelConfig) } - embedded, err := strconv.Atoi(p) - if err != nil || embedded < 1 || embedded > 65535 { - return fmt.Errorf("databricks: host %q carries an invalid port %q (want 1..65535): %w", host, p, dbsqlerr.ErrInvalidKernelConfig) + // url.Parse accepts a stray "]" in a plain name, so brackets are checked on the parsed host name + // (IPv6 brackets are already removed from it). + if strings.ContainsAny(h.name, "[]") { + return fmt.Errorf("databricks: host %q has unbalanced IPv6 brackets: %w", h.raw, dbsqlerr.ErrInvalidKernelConfig) } - return nil -} - -// warnEmbeddedPortWins logs when a non-default port (WithPort or the DSN) differs from the port embedded -// in the host. The embedded port is used, as on the kernel path before WithPort was honored. An -// explicit 443 is the default and is not warned about. -func warnEmbeddedPortWins(host string, port int) { - if port == 0 || port == 443 { - return + if !h.hasPort { + return nil // no embedded port } - _, p, err := net.SplitHostPort(normaliseKernelHost(host)) - if err != nil { - return + embedded, err := strconv.Atoi(h.port) + if err != nil || embedded < 1 || embedded > 65535 { + return fmt.Errorf("databricks: host %q carries an invalid port %q (want 1..65535): %w", h.raw, h.port, dbsqlerr.ErrInvalidKernelConfig) } - embedded, err := strconv.Atoi(p) - if err != nil || embedded == port { - return + // The embedded port is used, as on the kernel path before WithPort was honored. An explicit 443 is + // the default and is not warned about. + if nonDefault && embedded != port { + logger.Warn().Msgf("databricks: the host carries port %d, which differs from WithPort %d; connecting to port %d from the host", + embedded, port, embedded) } - logger.Warn().Msgf("databricks: the host carries port %d, which differs from WithPort %d; connecting to port %d from the host", - embedded, port, embedded) + return nil } -// kernelHostWithPort returns the Host the kernel connects to. The kernel has no port setter but -// keeps a `host:port` authority, so a non-default port is folded in (IPv6-safe). A trailing "/" is -// trimmed first. 0 and 443 add nothing, and a host that already carries a port is returned unchanged. +// kernelHostWithPort returns the Host the kernel connects to. The kernel has no port setter but keeps a +// `host:port` authority, so a non-default port is folded in with net.JoinHostPort, which brackets an IPv6 +// literal. A trailing "/" is trimmed first. 0 and 443 add nothing. A host that already carries a port, a +// path, query or fragment, or credentials is returned unchanged; validateKernelHostPort rejects the last +// two with a non-default port before the kernel is built. func kernelHostWithPort(host string, port int) string { - host = normaliseKernelHost(host) - if port == 0 || port == 443 { - return host - } - if _, _, err := net.SplitHostPort(host); err == nil { - return host - } - name := host - if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") { - name = host[1 : len(host)-1] + h, err := parseKernelHost(host) + if err != nil || port == 0 || port == 443 || h.hasPort || h.hasPath || h.userinfo { + return h.raw } - return net.JoinHostPort(name, strconv.Itoa(port)) + return net.JoinHostPort(h.name, strconv.Itoa(port)) } func kernelTelemetryConfig(cfg *config.Config) *kernel.TelemetryConfig { diff --git a/kernel_config_test.go b/kernel_config_test.go index 0926fb4b1..75f1a3e40 100644 --- a/kernel_config_test.go +++ b/kernel_config_test.go @@ -975,7 +975,8 @@ func TestKernelRetryConfig(t *testing.T) { // TestKernelCustomPort covers WithPort on the kernel backend: a non-default port is folded into the // kernel Host, 0 and 443 add nothing, a port embedded in the host wins, a trailing "/" is trimmed, // and a host with a path passes through unchanged unless a non-default port would be folded into it. -// An out-of-range port or unbalanced IPv6 brackets are rejected with ErrInvalidKernelConfig. +// Host parsing uses net/url. An out-of-range port, unbalanced IPv6 brackets, or a bare (unbracketed) +// IPv6 literal are rejected with ErrInvalidKernelConfig, so an IPv6 literal must be bracketed. func TestKernelCustomPort(t *testing.T) { cases := []struct { name string @@ -988,7 +989,7 @@ func TestKernelCustomPort(t *testing.T) { {"unset port adds nothing", "h.databricks.com", 0, "h.databricks.com", false}, {"custom port", "h.databricks.com", 8443, "h.databricks.com:8443", false}, {"IPv4 literal", "127.0.0.1", 8443, "127.0.0.1:8443", false}, - {"bare IPv6 is bracketed", "::1", 8443, "[::1]:8443", false}, + {"bare IPv6 is rejected: an IPv6 literal must be bracketed", "::1", 8443, "", true}, {"bracketed IPv6", "[::1]", 8443, "[::1]:8443", false}, {"port 1", "h.databricks.com", 1, "h.databricks.com:1", false}, {"port 65535", "h.databricks.com", 65535, "h.databricks.com:65535", false}, @@ -1019,6 +1020,33 @@ func TestKernelCustomPort(t *testing.T) { {"unclosed IPv6 bracket", "[::1", 8443, "", true}, {"text after IPv6 bracket", "[::1]x", 8443, "", true}, {"stray closing bracket", "h.databricks.com]", 8443, "", true}, + {"stray closing bracket, default port", "h.databricks.com]", 443, "", true}, + {"text after IPv6 bracket, default port", "[::1]x", 443, "", true}, + {"unclosed IPv6 bracket, default port", "[::1", 443, "", true}, + // net/url rules: an empty port, credentials, an empty fragment and bare IPv6 literals. + {"empty port after colon", "h:", 8443, "", true}, + {"empty port after colon, default port", "h:", 443, "", true}, + {"bare IPv6, default port: rejected (bracket it)", "::1", 443, "", true}, + {"bare IPv6 with zone is rejected", "fe80::1%eth0", 8443, "", true}, + {"userinfo, default port: unchanged", "user@h", 443, "user@h", false}, + {"userinfo, custom port: rejected", "user@h", 8443, "", true}, + {"userinfo with an embedded port, custom port: rejected", "user@h:8443", 9443, "", true}, + {"userinfo with an embedded port, default port: unchanged", "user@h:8443", 443, "user@h:8443", false}, + {"password, default port: rejected", "user:pw@h", 443, "", true}, + {"password, custom port: rejected", "user:pw@h", 8443, "", true}, + {"empty fragment, custom port: rejected (h#)", "h#", 8443, "", true}, + {"empty fragment, default port: unchanged (h#)", "h#", 443, "h#", false}, + {"embedded port out of range (h:70000)", "h:70000", 8443, "", true}, + {"embedded port not a number (h:abc)", "h:abc", 8443, "", true}, + {"mixed-case host is kept (custom port)", "H.Example.COM", 8443, "H.Example.COM:8443", false}, + {"mixed-case host is kept (default port)", "H.Example.COM", 443, "H.Example.COM", false}, + {"trailing slash after embedded port", "h:8443/", 8443, "h:8443", false}, + {"path with custom port (h/x)", "h/x", 8443, "", true}, + {"path, default port: unchanged (h/x)", "h/x", 443, "h/x", false}, + {"query with custom port (h?q)", "h?q", 8443, "", true}, + {"query, default port: unchanged (h?q)", "h?q", 443, "h?q", false}, + {"fragment with custom port (h#f)", "h#f", 8443, "", true}, + {"fragment, default port: unchanged (h#f)", "h#f", 443, "h#f", false}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { diff --git a/kernel_proxy_test.go b/kernel_proxy_test.go index 9316e4706..4890c7425 100644 --- a/kernel_proxy_test.go +++ b/kernel_proxy_test.go @@ -68,12 +68,12 @@ func TestProxyForEndpoint(t *testing.T) { want: "http://corp-proxy:3128", }, { - // An unbracketed IPv6 literal with a port must be bracketed in the endpoint, + // A bracketed IPv6 literal with a port is folded into the endpoint as [addr]:port, // the same way the kernel Host is built. - name: "IPv6 literal with Port is bracketed", + name: "bracketed IPv6 literal with Port is folded", cfg: func() *config.Config { c := config.WithDefaults() - c.Host = "::1" + c.Host = "[::1]" c.Port = 8443 c.HTTPPath = "/sql/1.0/warehouses/abc" return c From 79f43a0cf51eebe31fc70bcdf555481000d555a3 Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:35:50 +0000 Subject: [PATCH 08/17] fix(kernel): bracket bare IPv6 hosts and redact host credentials in errors Bracket a bare IPv6 literal before the kernel host is parsed, so "::1" and "[::1]" both fold to "[::1]:8443" on every Go version. A DSN IPv6 host reaches the same path, since ParseDSN strips the brackets. ParseDSN itself is unchanged. Host-bearing errors now show user info as "@h". url.Parse's text is withheld when the host has user info, because it quotes the whole URL and a bad escape quotes the password. A password is still rejected at every port, except that the default port keeps a host with a path, query or fragment unchanged, as before. Document that rule in CHANGELOG, README and CONNECTION_PARAMETERS. Co-authored-by: Isaac Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> --- CHANGELOG.md | 2 +- CONNECTION_PARAMETERS.md | 2 +- README.md | 2 +- kernel_config.go | 79 ++++++++++++++++++++------- kernel_config_test.go | 113 +++++++++++++++++++++++++++++++++++++-- kernel_proxy_test.go | 18 +++++++ 6 files changed, 190 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f25e63f59..8930b24d2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased (v2.0.0 prototype) -- Honor `WithPort` / DSN port on the kernel backend, including the automatic Reyden recovery onto the kernel: a non-default port is folded into the host (`host:port`; an IPv6 literal must be bracketed, as `[::1]:8443`) instead of being rejected. A port embedded in the host wins over a differing `WithPort` (a warning is logged), a zero port means the default, and a trailing `/` on the host is ignored. An out-of-range port, a malformed or empty port in the host, or a non-default port with a host that has a path, query, fragment or credentials, is rejected with `ErrInvalidKernelConfig`. With OAuth and a non-default port, the kernel uses the same `host:port` for OAuth; Thrift keeps OAuth on the bare host (documented, not guarded). +- Honor `WithPort` / DSN port on the kernel backend, including the automatic Reyden recovery onto the kernel: a non-default port is folded into the host (`host:port`) instead of being rejected. An IPv6 literal may be bare (`::1`) or bracketed (`[::1]`), and both fold to `[::1]:8443`. A port embedded in the host wins over a differing `WithPort` (a warning is logged), a zero port means the default, and a trailing `/` on the host is ignored. An out-of-range port, a malformed or empty port in the host, or a non-default port with a host that has a path, query, fragment or credentials, is rejected with `ErrInvalidKernelConfig`. A host with a password (`user:pw@h`) is rejected at every port, except that the default port keeps a host with a path, query or fragment unchanged. Error messages show the host with its credentials replaced by ``. With OAuth and a non-default port, the kernel uses the same `host:port` for OAuth; Thrift keeps OAuth on the bare host (documented, not guarded). - Render non-finite FLOAT / DOUBLE values inside ARRAY / MAP / STRUCT results as the JSON strings `"NaN"`, `"Infinity"`, and `"-Infinity"` on both backends instead of failing row iteration. SQL NULL remains `null`; top-level floats remain numeric (databricks/databricks-sql-go#573). - **Behavior change:** Non-finite floating-point MAP keys use the same spellings as values on both backends. On the kernel backend, keys previously rendered as `"+Inf"` and `"-Inf"` now render as `"Infinity"` and `"-Infinity"`; `"NaN"` is unchanged. On Thrift, these keys previously failed row iteration (databricks/databricks-sql-go#573). - Fix the module-root package conflict when building, linting, or running Gazelle with the `tools` build tag (databricks/databricks-sql-go#162). diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 18920a258..d71d1ebfe 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -40,7 +40,7 @@ wire. They are listed under [Kernel client-result confs](#kernel-client-result-c |---|---|:---:|:---:|---|---| | *(host)* | `WithServerHostname` | ✅ | ✅ | *(required)* | Workspace hostname. | | *(path)* | `WithHTTPPath` | ✅ | ✅ | required on Thrift except localhost; required on kernel unless `warehouseId` is set | Warehouse/endpoint HTTP path. On the kernel path, a bare warehouse id can be used instead. | -| *(port)* | `WithPort` | ✅ | ✅ | `443` for connector options; required in a DSN | Kernel folds a non-default port into the host it connects to. A port embedded in the host wins over a differing `WithPort` (a warning is logged and the embedded port is used); an out-of-range port, a malformed port in the host, or a non-default port with a host that has a path, query, fragment or credentials, is rejected at connect. An IPv6 literal must be bracketed (`[::1]`, not `::1`). With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | +| *(port)* | `WithPort` | ✅ | ✅ | `443` for connector options; required in a DSN | Kernel folds a non-default port into the host it connects to. A port embedded in the host wins over a differing `WithPort` (a warning is logged and the embedded port is used); an out-of-range port, a malformed port in the host, or a non-default port with a host that has a path, query, fragment or credentials, is rejected at connect. A host with a password (`user:pw@h`) is rejected at every port, except that the default port keeps a host with a path, query or fragment unchanged. Errors show the host with its credentials redacted. An IPv6 literal may be bare (`::1`) or bracketed (`[::1]`). With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | | *(scheme)* | *(via `WithServerHostname`)* | ✅ | ⚠️ | `https` | Kernel accepts `https` only and rejects `http`. A bare `localhost` passed to `WithServerHostname` selects `http`; a scheme-less DSN, including localhost, is prefixed with `https`. | | `warehouseId` | `WithWarehouseID` | ⚠️ | ✅ | | Bare warehouse id. The kernel normally prefers it over the HTTP path; a canonical path carrying `?o=` takes precedence so workspace-org routing is preserved. The Thrift backend **silently ignores** it. | | `catalog` | `WithInitialNamespace` | ✅ | ✅ | | Initial catalog. Kernel applies it post-connect via `USE CATALOG`. | diff --git a/README.md b/README.md index e187e97ce..853082a95 100644 --- a/README.md +++ b/README.md @@ -240,7 +240,7 @@ session parameter on both backends. |---|---|---|---|---| | *(host)* | `WithServerHostname` | Both | *(required)* | Workspace hostname. | | *(path)* | `WithHTTPPath` | Both | *(required)* | Warehouse/endpoint HTTP path. | -| *(port)* | `WithPort` | Both | `443` | Kernel folds a non-default port into the host it connects to. A port embedded in the host wins over a differing `WithPort` (a warning is logged); an out-of-range port, a malformed port in the host, or a non-default port with a host that has a path, query, fragment or credentials, is rejected at connect. An IPv6 literal must be bracketed (`[::1]`, not `::1`). With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | +| *(port)* | `WithPort` | Both | `443` | Kernel folds a non-default port into the host it connects to. A port embedded in the host wins over a differing `WithPort` (a warning is logged); an out-of-range port, a malformed port in the host, or a non-default port with a host that has a path, query, fragment or credentials, is rejected at connect. A host with a password (`user:pw@h`) is rejected at every port, except that the default port keeps a host with a path, query or fragment unchanged. Errors show the host with its credentials redacted. An IPv6 literal may be bare (`::1`) or bracketed (`[::1]`). With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | | `warehouseId` | `WithWarehouseID` | SEA only | | Bare warehouse id; the kernel routes by it (preferred over the HTTP path). **The Thrift backend ignores it.** | | `catalog` | `WithInitialNamespace` | Both | | Initial catalog. Kernel applies it post-connect via `USE CATALOG`. | | `schema` | `WithInitialNamespace` | Both | | Initial schema. Kernel applies it post-connect via `USE SCHEMA`. | diff --git a/kernel_config.go b/kernel_config.go index b1c04f0dc..2c7fad0f2 100644 --- a/kernel_config.go +++ b/kernel_config.go @@ -240,7 +240,8 @@ func buildKernelConfig(cfg *config.Config, kauth kernel.Auth) kernel.Config { // kernelHost is cfg.Host split by net/url: the parts the kernel port logic needs. type kernelHost struct { - raw string // cfg.Host with a trailing "/" trimmed; the kernel gets it unchanged when no port is folded + raw string // cfg.Host with a trailing "/" trimmed and a bare IPv6 literal bracketed; the kernel gets it unchanged when no port is folded + redacted string // raw with any user[:password] replaced by ""; the only form of the host that goes into an error name string // host name without IPv6 brackets (url.URL.Hostname) port string // digits after the authority's ":"; "" when there is none hasPort bool // the authority has a ":", even with no digits after it ("h:") @@ -249,13 +250,53 @@ type kernelHost struct { password bool // the user@ prefix carries a password } -// parseKernelHost parses cfg.Host (trailing "/" trimmed) as the authority of an https URL, which is the -// form the kernel connects to. The error is url.Parse's; the fields are set only when it is nil. +// splitAuthority splits a host string at its first "/", "?" or "#": the authority, and the rest. +func splitAuthority(raw string) (authority, rest string) { + if i := strings.IndexAny(raw, "/?#"); i >= 0 { + return raw[:i], raw[i:] + } + return raw, "" +} + +// bracketBareIPv6 wraps a bare IPv6 literal (after any user@ prefix) in brackets. net/url parses +// "https://[::1]" the same way on every Go version, but "https://::1" differs: a newer net/url rejects it, +// and an older one reads the last group as a port. So a DSN host (ParseDSN strips the brackets) and a +// bare WithServerHostname("::1") both reach the kernel path in the bracketed form. +func bracketBareIPv6(raw string) string { + authority, rest := splitAuthority(raw) + start := strings.LastIndex(authority, "@") + 1 + if host := authority[start:]; strings.Contains(host, ":") && net.ParseIP(host) != nil { + return authority[:start] + "[" + host + "]" + rest + } + return raw +} + +// redactUserinfo replaces the user[:password] of a host with "", keeping the host itself. +func redactUserinfo(raw string) string { + authority, rest := splitAuthority(raw) + at := strings.LastIndex(authority, "@") + if at < 0 { + return raw + } + return "@" + authority[at+1:] + rest +} + +// parseKernelHost parses cfg.Host (trailing "/" trimmed, bare IPv6 bracketed) as the authority of an https +// URL, which is the form the kernel connects to. The fields are set only when the error is nil. The error +// never carries the host or url.Parse's text: url.Parse quotes the whole URL, and an invalid escape quotes +// the password itself, so a host with user info gets a generic reason. func parseKernelHost(host string) (kernelHost, error) { - h := kernelHost{raw: strings.TrimRight(host, "/")} - u, err := url.Parse("https://" + h.raw) + raw := bracketBareIPv6(strings.TrimRight(host, "/")) + h := kernelHost{raw: raw, redacted: redactUserinfo(raw)} + u, err := url.Parse("https://" + raw) if err != nil { - return h, err + authority, _ := splitAuthority(raw) + reason := "it does not parse as a host" + var ue *url.Error + if !strings.Contains(authority, "@") && errors.As(err, &ue) { + reason = ue.Err.Error() + } + return h, errors.New(reason) } h.name = u.Hostname() h.port = u.Port() @@ -266,18 +307,20 @@ func parseKernelHost(host string) (kernelHost, error) { return h, nil } -// validateKernelHostPort rejects an out-of-range WithPort, a host that net/url cannot parse (an IPv6 -// literal must be bracketed), and a non-default WithPort with a host that has a path, query, fragment or -// credentials. It also rejects unbalanced brackets and an empty, out-of-range or malformed port embedded -// in the host. WithDefaults fills 443 when no port is set. A port embedded in the host wins over a -// differing WithPort, with a warning rather than an error. +// validateKernelHostPort rejects an out-of-range WithPort, a host that net/url cannot parse, and a +// non-default WithPort with a host that has a path, query, fragment or credentials. A password is +// rejected at every port, except that the default port keeps a host with a path, query or fragment +// unchanged (checked before the password, as before). It also rejects unbalanced brackets and an empty, out-of-range or malformed +// port embedded in the host. An IPv6 literal may be bare or bracketed. WithDefaults fills 443 when no port +// is set. A port embedded in the host wins over a differing WithPort, with a warning rather than an error. +// Every error names the host with its credentials redacted. func validateKernelHostPort(host string, port int) error { if port < 0 || port > 65535 { return fmt.Errorf("databricks: WithPort %d is out of range (want 1..65535, or 0 for the default): %w", port, dbsqlerr.ErrInvalidKernelConfig) } h, err := parseKernelHost(host) if err != nil { - return fmt.Errorf("databricks: host %q is not a valid host (bracket an IPv6 literal): %v: %w", h.raw, err, dbsqlerr.ErrInvalidKernelConfig) + return fmt.Errorf("databricks: host %q is not a valid host (want a host name, an IPv4 address or an IPv6 literal): %v: %w", h.redacted, err, dbsqlerr.ErrInvalidKernelConfig) } nonDefault := port != 0 && port != 443 // A path, query or fragment is checked before the embedded-port parse. With the default port the @@ -286,29 +329,29 @@ func validateKernelHostPort(host string, port int) error { if h.hasPath { if nonDefault { return fmt.Errorf("databricks: host %q has a path, query or fragment, so WithPort %d cannot be applied: %w", - h.raw, port, dbsqlerr.ErrInvalidKernelConfig) + h.redacted, port, dbsqlerr.ErrInvalidKernelConfig) } return nil } // Credentials are kept only at the default port: a non-default port would have to be folded in without them. if h.userinfo && nonDefault { return fmt.Errorf("databricks: host %q carries credentials, so WithPort %d cannot be applied: %w", - h.raw, port, dbsqlerr.ErrInvalidKernelConfig) + h.redacted, port, dbsqlerr.ErrInvalidKernelConfig) } if h.password { - return fmt.Errorf("databricks: host %q carries a password: %w", h.raw, dbsqlerr.ErrInvalidKernelConfig) + return fmt.Errorf("databricks: host %q carries a password: %w", h.redacted, dbsqlerr.ErrInvalidKernelConfig) } // url.Parse accepts a stray "]" in a plain name, so brackets are checked on the parsed host name // (IPv6 brackets are already removed from it). if strings.ContainsAny(h.name, "[]") { - return fmt.Errorf("databricks: host %q has unbalanced IPv6 brackets: %w", h.raw, dbsqlerr.ErrInvalidKernelConfig) + return fmt.Errorf("databricks: host %q has unbalanced IPv6 brackets: %w", h.redacted, dbsqlerr.ErrInvalidKernelConfig) } if !h.hasPort { return nil // no embedded port } embedded, err := strconv.Atoi(h.port) if err != nil || embedded < 1 || embedded > 65535 { - return fmt.Errorf("databricks: host %q carries an invalid port %q (want 1..65535): %w", h.raw, h.port, dbsqlerr.ErrInvalidKernelConfig) + return fmt.Errorf("databricks: host %q carries an invalid port %q (want 1..65535): %w", h.redacted, h.port, dbsqlerr.ErrInvalidKernelConfig) } // The embedded port is used, as on the kernel path before WithPort was honored. An explicit 443 is // the default and is not warned about. @@ -321,7 +364,7 @@ func validateKernelHostPort(host string, port int) error { // kernelHostWithPort returns the Host the kernel connects to. The kernel has no port setter but keeps a // `host:port` authority, so a non-default port is folded in with net.JoinHostPort, which brackets an IPv6 -// literal. A trailing "/" is trimmed first. 0 and 443 add nothing. A host that already carries a port, a +// literal. A trailing "/" is trimmed first, and a bare IPv6 literal is bracketed. 0 and 443 add nothing. A host that already carries a port, a // path, query or fragment, or credentials is returned unchanged; validateKernelHostPort rejects the last // two with a non-default port before the kernel is built. func kernelHostWithPort(host string, port int) string { diff --git a/kernel_config_test.go b/kernel_config_test.go index 75f1a3e40..e82b7e67a 100644 --- a/kernel_config_test.go +++ b/kernel_config_test.go @@ -6,6 +6,7 @@ import ( "fmt" "net/http" "reflect" + "strings" "testing" "time" @@ -975,8 +976,9 @@ func TestKernelRetryConfig(t *testing.T) { // TestKernelCustomPort covers WithPort on the kernel backend: a non-default port is folded into the // kernel Host, 0 and 443 add nothing, a port embedded in the host wins, a trailing "/" is trimmed, // and a host with a path passes through unchanged unless a non-default port would be folded into it. -// Host parsing uses net/url. An out-of-range port, unbalanced IPv6 brackets, or a bare (unbracketed) -// IPv6 literal are rejected with ErrInvalidKernelConfig, so an IPv6 literal must be bracketed. +// Host parsing uses net/url. A bare IPv6 literal is bracketed before it is parsed, so it folds the same +// way as its bracketed form on every Go version. An out-of-range port or unbalanced IPv6 brackets are +// rejected with ErrInvalidKernelConfig. func TestKernelCustomPort(t *testing.T) { cases := []struct { name string @@ -989,8 +991,14 @@ func TestKernelCustomPort(t *testing.T) { {"unset port adds nothing", "h.databricks.com", 0, "h.databricks.com", false}, {"custom port", "h.databricks.com", 8443, "h.databricks.com:8443", false}, {"IPv4 literal", "127.0.0.1", 8443, "127.0.0.1:8443", false}, - {"bare IPv6 is rejected: an IPv6 literal must be bracketed", "::1", 8443, "", true}, + {"bare IPv6 is bracketed and folded", "::1", 8443, "[::1]:8443", false}, + {"bare IPv6, full form", "2001:db8::1", 8443, "[2001:db8::1]:8443", false}, + {"bare IPv6, trailing slash", "::1/", 8443, "[::1]:8443", false}, + {"bare IPv6, default port: bracketed", "::1", 443, "[::1]", false}, + {"bare IPv6, unset port: bracketed", "::1", 0, "[::1]", false}, + {"bare IPv6, default port, trailing slash", "::1/", 443, "[::1]", false}, {"bracketed IPv6", "[::1]", 8443, "[::1]:8443", false}, + {"bracketed IPv6, default port: unchanged", "[::1]", 443, "[::1]", false}, {"port 1", "h.databricks.com", 1, "h.databricks.com:1", false}, {"port 65535", "h.databricks.com", 65535, "h.databricks.com:65535", false}, {"embedded port equal", "h.databricks.com:8443", 8443, "h.databricks.com:8443", false}, @@ -1023,17 +1031,21 @@ func TestKernelCustomPort(t *testing.T) { {"stray closing bracket, default port", "h.databricks.com]", 443, "", true}, {"text after IPv6 bracket, default port", "[::1]x", 443, "", true}, {"unclosed IPv6 bracket, default port", "[::1", 443, "", true}, - // net/url rules: an empty port, credentials, an empty fragment and bare IPv6 literals. + // net/url rules: an empty port, credentials, an empty fragment and an IPv6 zone. {"empty port after colon", "h:", 8443, "", true}, {"empty port after colon, default port", "h:", 443, "", true}, - {"bare IPv6, default port: rejected (bracket it)", "::1", 443, "", true}, {"bare IPv6 with zone is rejected", "fe80::1%eth0", 8443, "", true}, + {"bare IPv6 with zone, default port: rejected", "fe80::1%eth0", 443, "", true}, + {"userinfo with bare IPv6, custom port: rejected", "user@::1", 8443, "", true}, + {"userinfo with bare IPv6, default port: bracketed", "user@::1", 443, "user@[::1]", false}, {"userinfo, default port: unchanged", "user@h", 443, "user@h", false}, {"userinfo, custom port: rejected", "user@h", 8443, "", true}, {"userinfo with an embedded port, custom port: rejected", "user@h:8443", 9443, "", true}, {"userinfo with an embedded port, default port: unchanged", "user@h:8443", 443, "user@h:8443", false}, {"password, default port: rejected", "user:pw@h", 443, "", true}, {"password, custom port: rejected", "user:pw@h", 8443, "", true}, + {"password with a path, default port: unchanged (path check runs first)", "user:pw@h/x", 443, "user:pw@h/x", false}, + {"password with a path, custom port: rejected", "user:pw@h/x", 8443, "", true}, {"empty fragment, custom port: rejected (h#)", "h#", 8443, "", true}, {"empty fragment, default port: unchanged (h#)", "h#", 443, "h#", false}, {"embedded port out of range (h:70000)", "h:70000", 8443, "", true}, @@ -1119,3 +1131,94 @@ func TestKernelCustomPort(t *testing.T) { } }) } + +// TestKernelIPv6FromDSN checks that a DSN IPv6 host reaches the kernel the same way as its bracketed form. +// ParseDSN strips the brackets (url.Hostname), so the kernel path gets a bare "::1" and the port separately. +func TestKernelIPv6FromDSN(t *testing.T) { + cases := []struct { + name string + dsn string + wantHost string + }{ + {"bracketed IPv6 with custom port", "token:x@[::1]:8443/sql/1.0/warehouses/abc", "[::1]:8443"}, + {"bracketed IPv6 with default port", "token:x@[::1]:443/sql/1.0/warehouses/abc", "[::1]"}, + {"IPv4 with custom port", "token:x@10.0.0.1:8443/sql/1.0/warehouses/abc", "10.0.0.1:8443"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + ucfg, err := config.ParseDSN(tc.dsn) + if err != nil { + t.Fatalf("ParseDSN: %v", err) + } + con, err := NewConnector(withUserConfig(ucfg)) + if err != nil { + t.Fatalf("NewConnector: %v", err) + } + coni, ok := con.(*connector) + if !ok { + t.Fatalf("connector type = %T", con) + } + kauth, err := validateKernelConfig(coni.cfg) + if err != nil { + t.Fatalf("validateKernelConfig: %v", err) + } + if got := buildKernelConfig(coni.cfg, kauth).Host; got != tc.wantHost { + t.Errorf("kernel Host = %q, want %q", got, tc.wantHost) + } + }) + } +} + +// TestKernelHostErrorsRedactCredentials checks that no host error carries the password or the user part. +// The password includes a bad escape, so url.Parse's own text would quote it; that text is withheld when +// the host has user info. Every error still names the host with the credentials replaced by . +func TestKernelHostErrorsRedactCredentials(t *testing.T) { + const secret = "pSecret" + cases := []struct { + name string + host string + port int + }{ + {"password with a bad escape, default port (url.Parse fails)", "user:" + secret + "%zz@h", 443}, + {"password with a bad escape, custom port (url.Parse fails)", "user:" + secret + "%zz@h", 8443}, + {"password, custom port", "user:" + secret + "@h", 8443}, + {"password, default port", "user:" + secret + "@h", 443}, + {"password with an embedded port", "user:" + secret + "@h:8443", 443}, + {"password with an invalid embedded port", "user:" + secret + "@h:bad", 443}, + {"password with unbalanced bracket", "user:" + secret + "@h]", 443}, + {"password with a path, custom port", "user:" + secret + "@h/x", 8443}, + {"password with a query, custom port", "user:" + secret + "@h?x", 8443}, + {"password with an IPv6 literal", "user:" + secret + "@[::1]", 443}, + {"password with a bad IPv6 bracket", "user:" + secret + "@[::1", 443}, + {"password with a bare IPv6 literal", "user:" + secret + "@::1", 443}, + } + check := func(t *testing.T, err error) { + t.Helper() + if err == nil { + t.Fatal("expected an error") + } + if !errors.Is(err, dbsqlerr.ErrInvalidKernelConfig) { + t.Errorf("err = %v, want ErrInvalidKernelConfig", err) + } + msg := err.Error() + for _, leak := range []string{"Secret", "%zz", "user:", "user@"} { + if strings.Contains(msg, leak) { + t.Errorf("error %q leaks %q", msg, leak) + } + } + if !strings.Contains(msg, "@") { + t.Errorf("error %q does not name the redacted host", msg) + } + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + check(t, validateKernelHostPort(tc.host, tc.port)) + }) + } + t.Run("through validateKernelConfig", func(t *testing.T) { + c := baseKernelConfig() + c.Host = "user:" + secret + "@h" + _, err := validateKernelConfig(c) + check(t, err) + }) +} diff --git a/kernel_proxy_test.go b/kernel_proxy_test.go index 4890c7425..49d64cd05 100644 --- a/kernel_proxy_test.go +++ b/kernel_proxy_test.go @@ -111,6 +111,24 @@ func TestProxyForEndpoint(t *testing.T) { }, want: "", }, + { + // A bare IPv6 literal is bracketed before the port is folded, so the endpoint is [::1]:8443. + name: "bare IPv6 host with Port folds to a bracketed endpoint", + cfg: func() *config.Config { + c := config.WithDefaults() + c.Host = "::1" + c.Port = 8443 + c.HTTPPath = "/sql/1.0/warehouses/abc" + return c + }(), + resolve: func(req *http.Request) (*url.URL, error) { + if req.URL.Host != "[::1]:8443" { + t.Errorf("endpoint host = %q, want %q", req.URL.Host, "[::1]:8443") + } + return proxyURL, nil + }, + want: "http://corp-proxy:3128", + }, { // A trailing "/" (WithServerHostname("https://h/")) is trimmed before the port is // folded, so the endpoint is h:8443, not h/:8443. From 18c3b83bebe8928d4f3a06d821c07b040614bfed Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:26:21 +0000 Subject: [PATCH 09/17] fix(kernel): keep ErrNotSupportedByKernel on port rejections; reject empty host Before WithPort was honored, any non-default port on the kernel path returned ErrNotSupportedByKernel, which doc.go tells callers to check to fall back to the default backend. The new host/port checks returned only ErrInvalidKernelConfig, so that fallback stopped firing for the inputs they reject (a path or credentials with a non-default port, an invalid port). Each rejection that involves a non-default WithPort now wraps both errors. A default-port rejection, such as a password in the host, wraps ErrInvalidKernelConfig only, as before. An empty host with a non-default port reached the kernel as ":". It is now rejected. An empty host with the default port is unchanged. Co-authored-by: Isaac Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> --- CHANGELOG.md | 2 +- kernel_config.go | 35 ++++++++++++++++++++++++----------- kernel_config_test.go | 9 +++++++++ 3 files changed, 34 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ffddc1427..e37fd9369 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased (v2.0.0 prototype) -- Honor `WithPort` / DSN port on the kernel backend, including the automatic Reyden recovery onto the kernel: a non-default port is folded into the host (`host:port`) instead of being rejected. An IPv6 literal may be bare (`::1`) or bracketed (`[::1]`), and both fold to `[::1]:8443`. A port embedded in the host wins over a differing `WithPort` (a warning is logged), a zero port means the default, and a trailing `/` on the host is ignored. An out-of-range port, a malformed or empty port in the host, or a non-default port with a host that has a path, query, fragment or credentials, is rejected with `ErrInvalidKernelConfig`. A host with a password (`user:pw@h`) is rejected at every port, except that the default port keeps a host with a path, query or fragment unchanged. Error messages show the host with its credentials replaced by ``. With OAuth and a non-default port, the kernel uses the same `host:port` for OAuth; Thrift keeps OAuth on the bare host (documented, not guarded). +- Honor `WithPort` / DSN port on the kernel backend, including the automatic Reyden recovery onto the kernel: a non-default port is folded into the host (`host:port`) instead of being rejected. An IPv6 literal may be bare (`::1`) or bracketed (`[::1]`), and both fold to `[::1]:8443`. A port embedded in the host wins over a differing `WithPort` (a warning is logged), a zero port means the default, and a trailing `/` on the host is ignored. An out-of-range port, a malformed or empty port in the host, or a non-default port with an empty host or a host that has a path, query, fragment or credentials, is rejected with `ErrInvalidKernelConfig`. When such a rejection involves a non-default `WithPort`, it also wraps `ErrNotSupportedByKernel`, as every non-default port did before, so a fallback to the default backend on that error still works. A host with a password (`user:pw@h`) is rejected at every port, except that the default port keeps a host with a path, query or fragment unchanged. Error messages show the host with its credentials replaced by ``. With OAuth and a non-default port, the kernel uses the same `host:port` for OAuth; Thrift keeps OAuth on the bare host (documented, not guarded). - Fix leaked HTTP connections after failed or retry-exhausted requests, which could exhaust a connector's connection pool. Remove the MPL-2.0 go-retryablehttp and go-cleanhttp dependencies while preserving first-send bodies, streaming trailers and retry behavior (databricks/databricks-sql-go#177). - Fix OAuth M2M token requests hanging indefinitely when the token endpoint stops responding. Each request now uses a copy of `http.DefaultClient` with a timeout of at most 60s; `WithRetries` repeats failed fetches (databricks/databricks-sql-go#475). - **Behavior change:** Top-level GEOMETRY and GEOGRAPHY columns report server SQL names including SRIDs on Thrift and SEA. With `WithEnableGeoSpatialSupport(true)` (`enableGeoSpatialSupport=true`, available since v1.17.0), previously bare `GEOMETRY` / `GEOGRAPHY` names now include the declared SRID, such as `GEOMETRY(0)`, `GEOGRAPHY(4326)` or `GEOMETRY(ANY)`; match the family before `(` when selecting a decoder. String mode previously reported `STRING`; values, scan types, lengths and raw Arrow schemas are unchanged, and Thrift retains `STRING` without a readable Arrow schema (databricks/databricks-sql-go#474). diff --git a/kernel_config.go b/kernel_config.go index a075f046f..27966c36e 100644 --- a/kernel_config.go +++ b/kernel_config.go @@ -313,45 +313,58 @@ func parseKernelHost(host string) (kernelHost, error) { // unchanged (checked before the password, as before). It also rejects unbalanced brackets and an empty, out-of-range or malformed // port embedded in the host. An IPv6 literal may be bare or bracketed. WithDefaults fills 443 when no port // is set. A port embedded in the host wins over a differing WithPort, with a warning rather than an error. -// Every error names the host with its credentials redacted. +// Every error names the host with its credentials redacted, and wraps ErrInvalidKernelConfig. With a +// non-default WithPort it also wraps ErrNotSupportedByKernel: before WithPort was honored, any non-default +// port was that error on the kernel path, so a caller that falls back to the default backend on +// errors.Is(err, ErrNotSupportedByKernel) still does. func validateKernelHostPort(host string, port int) error { + nonDefault := port != 0 && port != 443 + reject := func(err error) error { + if nonDefault { + return fmt.Errorf("%w: %w", err, dbsqlerr.ErrNotSupportedByKernel) + } + return err + } if port < 0 || port > 65535 { - return fmt.Errorf("databricks: WithPort %d is out of range (want 1..65535, or 0 for the default): %w", port, dbsqlerr.ErrInvalidKernelConfig) + return reject(fmt.Errorf("databricks: WithPort %d is out of range (want 1..65535, or 0 for the default): %w", port, dbsqlerr.ErrInvalidKernelConfig)) + } + // An empty host cannot take a port: it would reach the kernel as ":". + if nonDefault && strings.TrimSpace(host) == "" { + return reject(fmt.Errorf("databricks: WithPort %d needs a host (WithServerHostname is empty): %w", port, dbsqlerr.ErrInvalidKernelConfig)) } h, err := parseKernelHost(host) if err != nil { - return fmt.Errorf("databricks: host %q is not a valid host (want a host name, an IPv4 address or an IPv6 literal): %v: %w", h.redacted, err, dbsqlerr.ErrInvalidKernelConfig) + return reject(fmt.Errorf("databricks: host %q is not a valid host (want a host name, an IPv4 address or an IPv6 literal): %v: %w", h.redacted, err, dbsqlerr.ErrInvalidKernelConfig)) } - nonDefault := port != 0 && port != 443 // A path, query or fragment is checked before the embedded-port parse. With the default port the // host goes to the kernel unchanged, as before (the kernel appends its API paths after it). A // non-default port cannot be folded into such a host, so reject it. if h.hasPath { if nonDefault { - return fmt.Errorf("databricks: host %q has a path, query or fragment, so WithPort %d cannot be applied: %w", - h.redacted, port, dbsqlerr.ErrInvalidKernelConfig) + return reject(fmt.Errorf("databricks: host %q has a path, query or fragment, so WithPort %d cannot be applied: %w", + h.redacted, port, dbsqlerr.ErrInvalidKernelConfig)) } return nil } // Credentials are kept only at the default port: a non-default port would have to be folded in without them. if h.userinfo && nonDefault { - return fmt.Errorf("databricks: host %q carries credentials, so WithPort %d cannot be applied: %w", - h.redacted, port, dbsqlerr.ErrInvalidKernelConfig) + return reject(fmt.Errorf("databricks: host %q carries credentials, so WithPort %d cannot be applied: %w", + h.redacted, port, dbsqlerr.ErrInvalidKernelConfig)) } if h.password { - return fmt.Errorf("databricks: host %q carries a password: %w", h.redacted, dbsqlerr.ErrInvalidKernelConfig) + return reject(fmt.Errorf("databricks: host %q carries a password: %w", h.redacted, dbsqlerr.ErrInvalidKernelConfig)) } // url.Parse accepts a stray "]" in a plain name, so brackets are checked on the parsed host name // (IPv6 brackets are already removed from it). if strings.ContainsAny(h.name, "[]") { - return fmt.Errorf("databricks: host %q has unbalanced IPv6 brackets: %w", h.redacted, dbsqlerr.ErrInvalidKernelConfig) + return reject(fmt.Errorf("databricks: host %q has unbalanced IPv6 brackets: %w", h.redacted, dbsqlerr.ErrInvalidKernelConfig)) } if !h.hasPort { return nil // no embedded port } embedded, err := strconv.Atoi(h.port) if err != nil || embedded < 1 || embedded > 65535 { - return fmt.Errorf("databricks: host %q carries an invalid port %q (want 1..65535): %w", h.redacted, h.port, dbsqlerr.ErrInvalidKernelConfig) + return reject(fmt.Errorf("databricks: host %q carries an invalid port %q (want 1..65535): %w", h.redacted, h.port, dbsqlerr.ErrInvalidKernelConfig)) } // The embedded port is used, as on the kernel path before WithPort was honored. An explicit 443 is // the default and is not warned about. diff --git a/kernel_config_test.go b/kernel_config_test.go index e82b7e67a..51eb8640d 100644 --- a/kernel_config_test.go +++ b/kernel_config_test.go @@ -1059,6 +1059,9 @@ func TestKernelCustomPort(t *testing.T) { {"query, default port: unchanged (h?q)", "h?q", 443, "h?q", false}, {"fragment with custom port (h#f)", "h#f", 8443, "", true}, {"fragment, default port: unchanged (h#f)", "h#f", 443, "h#f", false}, + {"empty host, custom port: rejected", "", 8443, "", true}, + {"empty host, unset port: unchanged", "", 0, "", false}, + {"empty host, default port: unchanged", "", 443, "", false}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -1067,6 +1070,12 @@ func TestKernelCustomPort(t *testing.T) { if !errors.Is(err, dbsqlerr.ErrInvalidKernelConfig) { t.Errorf("err = %v, want ErrInvalidKernelConfig", err) } + // Before WithPort was honored, a non-default port was ErrNotSupportedByKernel on the kernel + // path, so a rejection with one still wraps it; a default-port rejection does not. + nonDefault := tc.port != 0 && tc.port != 443 + if got := errors.Is(err, dbsqlerr.ErrNotSupportedByKernel); got != nonDefault { + t.Errorf("errors.Is(err, ErrNotSupportedByKernel) = %v, want %v (err %v)", got, nonDefault, err) + } return } if err != nil { From e561594ebeb15c4d70a82c9cc97654d24695f4ec Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:25:46 +0000 Subject: [PATCH 10/17] fix(kernel): redact userinfo up to the last @ of the whole host A password containing '/', '?' or '#' (for example user:p/w@h) ends the authority before the '@', so redactUserinfo found no '@' and returned the raw host, and url.Parse's reason (invalid port ":p") was kept. Both reached the error text with the password in them. Redaction now cuts at the last '@' anywhere in the host, and the parser's reason is withheld whenever an '@' appears. Tests cover passwords containing '/', '?' and '#'; they fail on the previous code. Co-authored-by: Isaac Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> --- kernel_config.go | 14 ++++++++------ kernel_config_test.go | 6 ++++++ 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/kernel_config.go b/kernel_config.go index 27966c36e..451c12664 100644 --- a/kernel_config.go +++ b/kernel_config.go @@ -271,14 +271,15 @@ func bracketBareIPv6(raw string) string { return raw } -// redactUserinfo replaces the user[:password] of a host with "", keeping the host itself. +// redactUserinfo replaces everything up to the last "@" of a host with "". The whole string is +// searched, not only the authority: a password may contain "/", "?" or "#" (e.g. "user:p/w@h"), which would +// otherwise end the authority before the "@" and leave the password in the text. func redactUserinfo(raw string) string { - authority, rest := splitAuthority(raw) - at := strings.LastIndex(authority, "@") + at := strings.LastIndex(raw, "@") if at < 0 { return raw } - return "@" + authority[at+1:] + rest + return "@" + raw[at+1:] } // parseKernelHost parses cfg.Host (trailing "/" trimmed, bare IPv6 bracketed) as the authority of an https @@ -290,10 +291,11 @@ func parseKernelHost(host string) (kernelHost, error) { h := kernelHost{raw: raw, redacted: redactUserinfo(raw)} u, err := url.Parse("https://" + raw) if err != nil { - authority, _ := splitAuthority(raw) + // The parser's reason can quote part of the userinfo (e.g. `invalid port ":p"` for "user:p/w@h"), so it + // is withheld whenever an "@" appears anywhere in the host. reason := "it does not parse as a host" var ue *url.Error - if !strings.Contains(authority, "@") && errors.As(err, &ue) { + if !strings.Contains(raw, "@") && errors.As(err, &ue) { reason = ue.Err.Error() } return h, errors.New(reason) diff --git a/kernel_config_test.go b/kernel_config_test.go index 51eb8640d..2479678f3 100644 --- a/kernel_config_test.go +++ b/kernel_config_test.go @@ -1200,6 +1200,12 @@ func TestKernelHostErrorsRedactCredentials(t *testing.T) { {"password with an IPv6 literal", "user:" + secret + "@[::1]", 443}, {"password with a bad IPv6 bracket", "user:" + secret + "@[::1", 443}, {"password with a bare IPv6 literal", "user:" + secret + "@::1", 443}, + // A "/", "?" or "#" inside the password ends the authority before the "@", so redaction must not rely + // on the authority split. + {"password containing a slash, default port", "user:" + secret + "/part@h", 443}, + {"password containing a slash, custom port", "user:" + secret + "/part@h", 8443}, + {"password containing a question mark", "user:" + secret + "?part@h", 443}, + {"password containing a hash", "user:" + secret + "#part@h", 8443}, } check := func(t *testing.T, err error) { t.Helper() From d8e6d026f9fdcf5d96853317d01bb365ada4611a Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:34:48 +0000 Subject: [PATCH 11/17] refactor(kernel): let the kernel apply WithPort The driver no longer folds the port into the host. It passes cfg.Host through unchanged and sets the port with kernel_session_config_set_port after the host, so the kernel applies the port and validates the host/port pair. KERNEL_REV moves to b5aac45d54bb4842b7e04dd7fbf2368216b6de4e, which adds the setter to the C ABI. The driver keeps the WithPort range check (0..65535, for the uint16 conversion) and the error contract: a kernel InvalidArgument for a non-default port wraps both ErrInvalidKernelConfig and ErrNotSupportedByKernel, and the default port wraps only ErrInvalidKernelConfig. The kernel's messages are already redacted, so the driver adds no host text. The proxy endpoint uses a small helper (kernelEndpointHost) that applies the kernel's simple port rule without validation, so HTTPS_PROXY and NO_PROXY see the same host:port the kernel dials. Removed: the driver's host/port validation and folding (path, userinfo, IPv6 and embedded-port handling, kernelHostWithPort and its helpers). Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac --- CHANGELOG.md | 2 +- CONNECTION_PARAMETERS.md | 2 +- KERNEL_REV | 2 +- README.md | 2 +- connector_reyden_test.go | 10 +- internal/backend/kernel/backend.go | 15 +- internal/backend/kernel/config.go | 3 +- internal/backend/kernel/errors_classify.go | 26 ++ .../backend/kernel/errors_classify_test.go | 46 +++ .../kernel/include/databricks_kernel.h | 15 + internal/backend/kernel/port_test.go | 38 +++ kernel_config.go | 168 +--------- kernel_config_test.go | 288 +++++------------- kernel_proxy.go | 26 +- 14 files changed, 266 insertions(+), 377 deletions(-) create mode 100644 internal/backend/kernel/port_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 137433e51..1ed8afaf3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased (v2.0.0 prototype) -- Honor `WithPort` / DSN port on the kernel backend, including the automatic Reyden recovery onto the kernel: a non-default port is folded into the host (`host:port`) instead of being rejected. An IPv6 literal may be bare (`::1`) or bracketed (`[::1]`), and both fold to `[::1]:8443`. A port embedded in the host wins over a differing `WithPort` (a warning is logged), a zero port means the default, and a trailing `/` on the host is ignored. An out-of-range port, a malformed or empty port in the host, or a non-default port with an empty host or a host that has a path, query, fragment or credentials, is rejected with `ErrInvalidKernelConfig`. When such a rejection involves a non-default `WithPort`, it also wraps `ErrNotSupportedByKernel`, as every non-default port did before, so a fallback to the default backend on that error still works. A host with a password (`user:pw@h`) is rejected at every port, except that the default port keeps a host with a path, query or fragment unchanged. Error messages show the host with its credentials replaced by ``. With OAuth and a non-default port, the kernel uses the same `host:port` for OAuth; Thrift keeps OAuth on the bare host (documented, not guarded). +- Honor `WithPort` / DSN port on the kernel backend, including the automatic Reyden recovery onto the kernel, instead of rejecting a non-default port. The kernel applies the port (`kernel_session_config_set_port`), and the driver passes the host through unchanged. Rules: a port of `0` or the scheme default `443` leaves the host unchanged and unvalidated; any other port becomes `host:port`, with a bare IPv6 literal bracketed (`[::1]:8443`); a port already in the host wins over a differing `WithPort`, and the kernel logs a warning. The kernel rejects credentials, an empty host, a path, query or fragment, and a bad embedded port with `InvalidArgument`, at connect. The driver checks only that `WithPort` is in `0..65535` (`ErrInvalidKernelConfig` and `ErrNotSupportedByKernel`). A kernel `InvalidArgument` for a non-default port wraps both sentinels, so a fallback to the default backend on `ErrNotSupportedByKernel` still works. For the default port it wraps only `ErrInvalidKernelConfig`. Errors never include credentials; the kernel redacts its messages. With OAuth and a non-default port, the kernel uses the same `host:port` for OAuth; Thrift keeps OAuth on the bare host (documented, not guarded). - Upgrade the SQL kernel bindings to v1.5.0. - Fix leaked HTTP connections after failed or retry-exhausted requests, which could exhaust a connector's connection pool. Remove the MPL-2.0 go-retryablehttp and go-cleanhttp dependencies while preserving first-send bodies, streaming trailers and retry behavior (databricks/databricks-sql-go#177). - Fix OAuth M2M token requests hanging indefinitely when the token endpoint stops responding. Each request now uses a copy of `http.DefaultClient` with a timeout of at most 60s; `WithRetries` repeats failed fetches (databricks/databricks-sql-go#475). diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 157944d7c..a79c5a95b 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -40,7 +40,7 @@ wire. They are listed under [Kernel client-result confs](#kernel-client-result-c |---|---|:---:|:---:|---|---| | *(host)* | `WithServerHostname` | ✅ | ✅ | *(required)* | Workspace hostname. | | *(path)* | `WithHTTPPath` | ✅ | ✅ | required on Thrift except localhost; required on kernel unless `warehouseId` is set | Warehouse/endpoint HTTP path. On the kernel path, a bare warehouse id can be used instead. | -| *(port)* | `WithPort` | ✅ | ✅ | `443` for connector options; required in a DSN | Kernel folds a non-default port into the host it connects to. A port embedded in the host wins over a differing `WithPort` (a warning is logged and the embedded port is used); an out-of-range port, a malformed port in the host, or a non-default port with a host that has a path, query, fragment or credentials, is rejected at connect. A host with a password (`user:pw@h`) is rejected at every port, except that the default port keeps a host with a path, query or fragment unchanged. Errors show the host with its credentials redacted. An IPv6 literal may be bare (`::1`) or bracketed (`[::1]`). With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | +| *(port)* | `WithPort` | ✅ | ✅ | `443` for connector options; required in a DSN | The kernel applies the port: a port of `0` or `443` leaves the host unchanged and unvalidated; any other port connects to `host:port`, with a bare IPv6 literal bracketed (`[::1]:8443`). A port already in the host wins over a differing `WithPort` (the kernel logs a warning). The kernel rejects credentials, an empty host, a path, query or fragment, and a bad embedded port with `InvalidArgument` at connect. The driver rejects only a `WithPort` outside `0..65535`. A non-default port's rejection wraps both `ErrInvalidKernelConfig` and `ErrNotSupportedByKernel`; a default-port rejection wraps only `ErrInvalidKernelConfig`. Errors never include credentials. With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | | *(scheme)* | *(via `WithServerHostname`)* | ✅ | ⚠️ | `https` | Kernel accepts `https` only and rejects `http`. A bare `localhost` passed to `WithServerHostname` selects `http`; a scheme-less DSN, including localhost, is prefixed with `https`. | | `warehouseId` | `WithWarehouseID` | ⚠️ | ✅ | | Bare warehouse id. The kernel normally prefers it over the HTTP path; a canonical path carrying `?o=` takes precedence so workspace-org routing is preserved. The Thrift backend **silently ignores** it. | | `catalog` | `WithInitialNamespace` | ✅ | ✅ | | Initial catalog. Kernel applies it post-connect via `USE CATALOG`. | diff --git a/KERNEL_REV b/KERNEL_REV index 2add322e2..6e083d73b 100644 --- a/KERNEL_REV +++ b/KERNEL_REV @@ -1 +1 @@ -5c3a909771f749174567af074bfe18c24a335f5c +b5aac45d54bb4842b7e04dd7fbf2368216b6de4e diff --git a/README.md b/README.md index f25ce67b6..7706478c6 100644 --- a/README.md +++ b/README.md @@ -240,7 +240,7 @@ session parameter on both backends. |---|---|---|---|---| | *(host)* | `WithServerHostname` | Both | *(required)* | Workspace hostname. | | *(path)* | `WithHTTPPath` | Both | *(required)* | Warehouse/endpoint HTTP path. | -| *(port)* | `WithPort` | Both | `443` | Kernel folds a non-default port into the host it connects to. A port embedded in the host wins over a differing `WithPort` (a warning is logged); an out-of-range port, a malformed port in the host, or a non-default port with a host that has a path, query, fragment or credentials, is rejected at connect. A host with a password (`user:pw@h`) is rejected at every port, except that the default port keeps a host with a path, query or fragment unchanged. Errors show the host with its credentials redacted. An IPv6 literal may be bare (`::1`) or bracketed (`[::1]`). With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | +| *(port)* | `WithPort` | Both | `443` | The kernel applies the port: a port of `0` or `443` leaves the host unchanged and unvalidated; any other port connects to `host:port`, with a bare IPv6 literal bracketed (`[::1]:8443`). A port already in the host wins over a differing `WithPort` (the kernel logs a warning). The kernel rejects credentials, an empty host, a path, query or fragment, and a bad embedded port with `InvalidArgument` at connect. The driver rejects only a `WithPort` outside `0..65535`. A non-default port's rejection wraps both `ErrInvalidKernelConfig` and `ErrNotSupportedByKernel`; a default-port rejection wraps only `ErrInvalidKernelConfig`. Errors never include credentials. With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | | `warehouseId` | `WithWarehouseID` | SEA only | | Bare warehouse id; the kernel routes by it (preferred over the HTTP path). **The Thrift backend ignores it.** | | `catalog` | `WithInitialNamespace` | Both | | Initial catalog. Kernel applies it post-connect via `USE CATALOG`. | | `schema` | `WithInitialNamespace` | Both | | Initial schema. Kernel applies it post-connect via `USE SCHEMA`. | diff --git a/connector_reyden_test.go b/connector_reyden_test.go index d789631c0..676c5d72a 100644 --- a/connector_reyden_test.go +++ b/connector_reyden_test.go @@ -221,15 +221,15 @@ func TestReydenReactiveRecovery(t *testing.T) { defer warehouse_cache.ClearCache() tt := NewTestReydenFallback() - var kernelHost string + var kernelCfg kernel.Config conn := tt.makeConnector( func(ctx context.Context, cfg *config.Config, client *http.Client) (backend.Backend, error) { return &fakeThriftBackend{openSessionErr: dbsqlerrint.NewReydenThriftUnsupportedError( "Lakehouse/RT is not supported for Thrift protocol")}, nil }, func(ctx context.Context, cfg *config.Config) (backend.Backend, error) { - require.NoError(t, validateKernelHostPort(cfg.Host, cfg.Port)) - kernelHost = buildKernelConfig(cfg, kernel.Auth{Mode: kernel.AuthPAT, Token: "test-token"}).Host + require.NoError(t, validateKernelPort(cfg.Port)) + kernelCfg = buildKernelConfig(cfg, kernel.Auth{Mode: kernel.AuthPAT, Token: "test-token"}) return &fakeKernelBackend{}, nil }, ) @@ -237,7 +237,9 @@ func TestReydenReactiveRecovery(t *testing.T) { _, _, err := conn.openSessionWithReydenFallback(context.Background()) require.NoError(t, err) - assert.Equal(t, "reyden.example.com:8443", kernelHost) + // The host is passed through; the port reaches the kernel, which folds it. + assert.Equal(t, "reyden.example.com", kernelCfg.Host) + assert.Equal(t, uint16(8443), kernelCfg.Port) }) } diff --git a/internal/backend/kernel/backend.go b/internal/backend/kernel/backend.go index d8e20d08e..69d2dafc4 100644 --- a/internal/backend/kernel/backend.go +++ b/internal/backend/kernel/backend.go @@ -198,7 +198,7 @@ func (k *KernelBackend) OpenSession(ctx context.Context) error { if err := call(func() C.KernelStatusCode { return C.kernel_session_config_set_warehouse(cfg, host.c, wh.c) }); err != nil { - return fmt.Errorf("kernel: set_warehouse: %w", toConnError(err)) + return fmt.Errorf("kernel: set_warehouse: %w", portRejection(k.cfg.Port, toConnError(err))) } } else { path := newCStr(k.cfg.HTTPPath) @@ -206,7 +206,18 @@ func (k *KernelBackend) OpenSession(ctx context.Context) error { if err := call(func() C.KernelStatusCode { return C.kernel_session_config_set_http_path(cfg, host.c, path.c) }); err != nil { - return fmt.Errorf("kernel: set_http_path: %w", toConnError(err)) + return fmt.Errorf("kernel: set_http_path: %w", portRejection(k.cfg.Port, toConnError(err))) + } + } + + // Connection port, after the host so the kernel validates the pair. The kernel folds + // a non-default port into the host it connects to; 0 means unset, so nothing is sent. + // A rejection here is the WithPort contract's InvalidArgument (see portRejection). + if k.cfg.Port != 0 { + if err := call(func() C.KernelStatusCode { + return C.kernel_session_config_set_port(cfg, C.uint16_t(k.cfg.Port)) + }); err != nil { + return fmt.Errorf("kernel: set_port: %w", portRejection(k.cfg.Port, toConnError(err))) } } diff --git a/internal/backend/kernel/config.go b/internal/backend/kernel/config.go index c3f97ed83..9f1e01356 100644 --- a/internal/backend/kernel/config.go +++ b/internal/backend/kernel/config.go @@ -15,7 +15,8 @@ import ( // fills it from the driver's config so the user-facing options are unchanged. // Zero-valued fields are simply not applied unless documented otherwise. type Config struct { - Host string // workspace hostname, no scheme + Host string // workspace hostname, no scheme; passed to the kernel unchanged + Port uint16 // connection port; 0 leaves the host as given. Applied with kernel_session_config_set_port, which folds it into the host HTTPPath string // e.g. /sql/1.0/warehouses/abc123 (carries ?o= org routing) WarehouseID string // bare warehouse id; preferred over HTTPPath when set Auth Auth // PAT / OAuth M2M / OAuth U2M diff --git a/internal/backend/kernel/errors_classify.go b/internal/backend/kernel/errors_classify.go index 73b7c39c9..c945a52fd 100644 --- a/internal/backend/kernel/errors_classify.go +++ b/internal/backend/kernel/errors_classify.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" + dbsqlerr "github.com/databricks/databricks-sql-go/errors" dbsqlerrint "github.com/databricks/databricks-sql-go/internal/errors" ) @@ -202,3 +203,28 @@ func toStatementError(err error) error { } return err } + +// kernelDefaultPort is the https default. The kernel accepts it and changes nothing. +const kernelDefaultPort uint16 = 443 + +// portRejection applies the WithPort error contract to a kernel rejection. The kernel +// validates the port against the host (kernel_session_config_set_port, and the host +// setters, which re-check it), so an InvalidArgument from any of those calls is the +// kernel's verdict on the pair. A non-default port wraps both ErrInvalidKernelConfig +// and ErrNotSupportedByKernel, so a caller can fall back to the default backend with +// errors.Is. The default port wraps only ErrInvalidKernelConfig. Port 0 (unset), other +// codes and non-kernel errors pass through unchanged. The kernel's message is already +// redacted, so the wrapper adds no host text. +func portRejection(port uint16, err error) error { + if err == nil || port == 0 { + return err + } + var ke *KernelError + if !errors.As(err, &ke) || ke.Code != statusInvalidArgument { + return err + } + if port == kernelDefaultPort { + return fmt.Errorf("%w: %w", err, dbsqlerr.ErrInvalidKernelConfig) + } + return fmt.Errorf("%w: %w: %w", err, dbsqlerr.ErrInvalidKernelConfig, dbsqlerr.ErrNotSupportedByKernel) +} diff --git a/internal/backend/kernel/errors_classify_test.go b/internal/backend/kernel/errors_classify_test.go index 32eeec097..ef7b65dd4 100644 --- a/internal/backend/kernel/errors_classify_test.go +++ b/internal/backend/kernel/errors_classify_test.go @@ -6,6 +6,7 @@ import ( "fmt" "testing" + dbsqlerr "github.com/databricks/databricks-sql-go/errors" dbsqlerrint "github.com/databricks/databricks-sql-go/internal/errors" ) @@ -217,6 +218,51 @@ func TestKernelErrorCategoryThroughWrap(t *testing.T) { } } +// portRejection is the WithPort error contract for a kernel rejection. A non-default port wraps +// both ErrInvalidKernelConfig and ErrNotSupportedByKernel, the default port only +// ErrInvalidKernelConfig, and port 0 or another code passes through untouched. The kernel's own +// message is kept as is and nothing is added to it, so no host text is introduced here. +func TestPortRejection(t *testing.T) { + const kernelMsg = "kernel: host is not valid for the port" + invalid := &KernelError{Code: statusInvalidArgument, Message: kernelMsg} + + t.Run("non-default port wraps both sentinels", func(t *testing.T) { + for _, port := range []uint16{1, 8443, 65535} { + err := portRejection(port, invalid) + if !errors.Is(err, dbsqlerr.ErrInvalidKernelConfig) || !errors.Is(err, dbsqlerr.ErrNotSupportedByKernel) { + t.Errorf("port %d: err = %v, want both sentinels", port, err) + } + var ke *KernelError + if !errors.As(err, &ke) || ke.Message != kernelMsg { + t.Errorf("port %d: kernel error not preserved: %v", port, err) + } + } + }) + + t.Run("default port wraps only ErrInvalidKernelConfig", func(t *testing.T) { + err := portRejection(kernelDefaultPort, invalid) + if !errors.Is(err, dbsqlerr.ErrInvalidKernelConfig) { + t.Errorf("err = %v, want ErrInvalidKernelConfig", err) + } + if errors.Is(err, dbsqlerr.ErrNotSupportedByKernel) { + t.Errorf("default-port rejection must not wrap ErrNotSupportedByKernel: %v", err) + } + }) + + t.Run("unset port and other codes pass through unchanged", func(t *testing.T) { + if err := portRejection(0, invalid); err != invalid { + t.Errorf("port 0: err = %v, want the input unchanged", err) + } + unavailable := &KernelError{Code: statusUnavailable, Message: "gone"} + if err := portRejection(8443, unavailable); err != unavailable { + t.Errorf("non-InvalidArgument: err = %v, want the input unchanged", err) + } + if err := portRejection(8443, nil); err != nil { + t.Errorf("nil: err = %v, want nil", err) + } + }) +} + func contains(s, sub string) bool { return len(s) >= len(sub) && (s == sub || indexOf(s, sub) >= 0) } func indexOf(s, sub string) int { diff --git a/internal/backend/kernel/include/databricks_kernel.h b/internal/backend/kernel/include/databricks_kernel.h index e167f1815..0e9af665b 100644 --- a/internal/backend/kernel/include/databricks_kernel.h +++ b/internal/backend/kernel/include/databricks_kernel.h @@ -245,6 +245,21 @@ KernelStatusCode kernel_session_config_set_http_path(KernelSessionConfig* config const char* host, const char* http_path); +/* Connection port — optional, may be set before or after the host; last call + * wins. `0` (the default) means unset. The scheme default (443 for https, 80 + * for http) is accepted and changes nothing. Any other port is folded into the + * host at kernel_session_open, so the kernel connects to host:port. + * + * The host must not carry userinfo (`user:pw@host`), a path, a query or a + * fragment, and must not be empty. A port already embedded in the host + * (`host:N` or `[v6]:N`) is kept and wins over this one; the kernel logs a + * warning when the two differ. Validation is eager: a bad combination returns + * KernelStatusCode_InvalidArgument from whichever of this call or the host + * setter came second, and leaves the config unchanged. Error text never + * includes credentials. */ +KernelStatusCode kernel_session_config_set_port(KernelSessionConfig* config, + uint16_t port); + /* Authentication — call exactly one; the last one wins. */ KernelStatusCode kernel_session_config_set_auth_pat(KernelSessionConfig* config, const char* token); diff --git a/internal/backend/kernel/port_test.go b/internal/backend/kernel/port_test.go new file mode 100644 index 000000000..d73c45c5f --- /dev/null +++ b/internal/backend/kernel/port_test.go @@ -0,0 +1,38 @@ +//go:build cgo && databricks_kernel + +package kernel + +import ( + "context" + "errors" + "strings" + "testing" + + dbsqlerr "github.com/databricks/databricks-sql-go/errors" +) + +const portTestSecret = "pSecretPw" + +// TestOpenSessionPortRejection checks the WithPort contract end to end through the real +// kernel. OpenSession sets the host before the port, so the host setter has no port to +// check yet. The kernel's kernel_session_config_set_port then rejects the credentialed +// host with InvalidArgument, before any connection is made. The error must wrap both +// sentinels and must not carry the credentials. +func TestOpenSessionPortRejection(t *testing.T) { + k := New(Config{ + Host: "user:" + portTestSecret + "@h.databricks.com", + Port: 8443, + WarehouseID: "wh", + Auth: Auth{Mode: AuthPAT, Token: "test-token"}, + }) + err := k.OpenSession(context.Background()) + if err == nil { + t.Fatal("OpenSession accepted credentials with a custom port; want the kernel to reject it") + } + if !errors.Is(err, dbsqlerr.ErrInvalidKernelConfig) || !errors.Is(err, dbsqlerr.ErrNotSupportedByKernel) { + t.Errorf("err = %v, want both ErrInvalidKernelConfig and ErrNotSupportedByKernel", err) + } + if msg := err.Error(); strings.Contains(msg, portTestSecret) || strings.Contains(msg, "user:") { + t.Errorf("error leaks credentials: %q", msg) + } +} diff --git a/kernel_config.go b/kernel_config.go index 451c12664..9def49834 100644 --- a/kernel_config.go +++ b/kernel_config.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "net" "net/url" "strconv" "strings" @@ -16,7 +15,6 @@ import ( "github.com/databricks/databricks-sql-go/internal/backend/kernel" "github.com/databricks/databricks-sql-go/internal/client" "github.com/databricks/databricks-sql-go/internal/config" - "github.com/databricks/databricks-sql-go/logger" "github.com/databricks/databricks-sql-go/telemetry" ) @@ -80,9 +78,10 @@ func validateKernelConfigContext(ctx context.Context, cfg *config.Config) (kerne return kernel.Auth{}, fmt.Errorf("databricks: a non-https protocol is %w "+ "(it connects over https); use the default (Thrift) backend", dbsqlerr.ErrNotSupportedByKernel) } - // Port: the kernel folds host:port (see kernelHostWithPort); reject a bad port or host here. An - // embedded host port wins over a differing WithPort, with a warning rather than an error. - if err := validateKernelHostPort(cfg.Host, cfg.Port); err != nil { + // Port: only the uint16 range is checked here. The kernel folds a non-default port into + // the host and validates the host/port pair itself (kernel_session_config_set_port), and + // its InvalidArgument reaches the caller with the same sentinels (see portRejection). + if err := validateKernelPort(cfg.Port); err != nil { return kernel.Auth{}, err } // Transport (WithTransport, a custom http.RoundTripper carrying a custom CA @@ -154,7 +153,9 @@ func validateKernelConfigContext(ctx context.Context, cfg *config.Config) (kerne // with newKernelBackend's kernel.Config assembly. func buildKernelConfig(cfg *config.Config, kauth kernel.Auth) kernel.Config { kc := kernel.Config{ - Host: kernelHostWithPort(cfg.Host, cfg.Port), + // The host goes through unchanged; the kernel applies Port (set_port). + Host: cfg.Host, + Port: uint16(cfg.Port), //nolint:gosec // G115: range-checked by validateKernelPort before this runs HTTPPath: cfg.HTTPPath, WarehouseID: cfg.WarehouseID, Auth: kauth, @@ -238,158 +239,19 @@ func buildKernelConfig(cfg *config.Config, kauth kernel.Auth) kernel.Config { return kc } -// kernelHost is cfg.Host split by net/url: the parts the kernel port logic needs. -type kernelHost struct { - raw string // cfg.Host with a trailing "/" trimmed and a bare IPv6 literal bracketed; the kernel gets it unchanged when no port is folded - redacted string // raw with any user[:password] replaced by ""; the only form of the host that goes into an error - name string // host name without IPv6 brackets (url.URL.Hostname) - port string // digits after the authority's ":"; "" when there is none - hasPort bool // the authority has a ":", even with no digits after it ("h:") - hasPath bool // a path, query or fragment follows the host, or a bare "#" (url.URL drops an empty fragment) - userinfo bool // a user@ prefix is present - password bool // the user@ prefix carries a password -} - -// splitAuthority splits a host string at its first "/", "?" or "#": the authority, and the rest. -func splitAuthority(raw string) (authority, rest string) { - if i := strings.IndexAny(raw, "/?#"); i >= 0 { - return raw[:i], raw[i:] - } - return raw, "" -} - -// bracketBareIPv6 wraps a bare IPv6 literal (after any user@ prefix) in brackets. net/url parses -// "https://[::1]" the same way on every Go version, but "https://::1" differs: a newer net/url rejects it, -// and an older one reads the last group as a port. So a DSN host (ParseDSN strips the brackets) and a -// bare WithServerHostname("::1") both reach the kernel path in the bracketed form. -func bracketBareIPv6(raw string) string { - authority, rest := splitAuthority(raw) - start := strings.LastIndex(authority, "@") + 1 - if host := authority[start:]; strings.Contains(host, ":") && net.ParseIP(host) != nil { - return authority[:start] + "[" + host + "]" + rest - } - return raw -} - -// redactUserinfo replaces everything up to the last "@" of a host with "". The whole string is -// searched, not only the authority: a password may contain "/", "?" or "#" (e.g. "user:p/w@h"), which would -// otherwise end the authority before the "@" and leave the password in the text. -func redactUserinfo(raw string) string { - at := strings.LastIndex(raw, "@") - if at < 0 { - return raw - } - return "@" + raw[at+1:] -} - -// parseKernelHost parses cfg.Host (trailing "/" trimmed, bare IPv6 bracketed) as the authority of an https -// URL, which is the form the kernel connects to. The fields are set only when the error is nil. The error -// never carries the host or url.Parse's text: url.Parse quotes the whole URL, and an invalid escape quotes -// the password itself, so a host with user info gets a generic reason. -func parseKernelHost(host string) (kernelHost, error) { - raw := bracketBareIPv6(strings.TrimRight(host, "/")) - h := kernelHost{raw: raw, redacted: redactUserinfo(raw)} - u, err := url.Parse("https://" + raw) - if err != nil { - // The parser's reason can quote part of the userinfo (e.g. `invalid port ":p"` for "user:p/w@h"), so it - // is withheld whenever an "@" appears anywhere in the host. - reason := "it does not parse as a host" - var ue *url.Error - if !strings.Contains(raw, "@") && errors.As(err, &ue) { - reason = ue.Err.Error() - } - return h, errors.New(reason) - } - h.name = u.Hostname() - h.port = u.Port() - h.hasPort = h.port != "" || strings.HasSuffix(u.Host, ":") - h.hasPath = u.Path != "" || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || strings.Contains(h.raw, "#") - h.userinfo = u.User != nil - _, h.password = u.User.Password() - return h, nil -} - -// validateKernelHostPort rejects an out-of-range WithPort, a host that net/url cannot parse, and a -// non-default WithPort with a host that has a path, query, fragment or credentials. A password is -// rejected at every port, except that the default port keeps a host with a path, query or fragment -// unchanged (checked before the password, as before). It also rejects unbalanced brackets and an empty, out-of-range or malformed -// port embedded in the host. An IPv6 literal may be bare or bracketed. WithDefaults fills 443 when no port -// is set. A port embedded in the host wins over a differing WithPort, with a warning rather than an error. -// Every error names the host with its credentials redacted, and wraps ErrInvalidKernelConfig. With a -// non-default WithPort it also wraps ErrNotSupportedByKernel: before WithPort was honored, any non-default -// port was that error on the kernel path, so a caller that falls back to the default backend on -// errors.Is(err, ErrNotSupportedByKernel) still does. -func validateKernelHostPort(host string, port int) error { - nonDefault := port != 0 && port != 443 - reject := func(err error) error { - if nonDefault { - return fmt.Errorf("%w: %w", err, dbsqlerr.ErrNotSupportedByKernel) - } - return err - } +// validateKernelPort checks the WithPort range the uint16 conversion needs. Everything +// else about the port (the host it is folded into, an embedded port, credentials, a +// path, an empty host) is the kernel's to validate when the session is opened. An +// out-of-range port is never the default, so the rejection wraps ErrNotSupportedByKernel +// as well as ErrInvalidKernelConfig. +func validateKernelPort(port int) error { if port < 0 || port > 65535 { - return reject(fmt.Errorf("databricks: WithPort %d is out of range (want 1..65535, or 0 for the default): %w", port, dbsqlerr.ErrInvalidKernelConfig)) - } - // An empty host cannot take a port: it would reach the kernel as ":". - if nonDefault && strings.TrimSpace(host) == "" { - return reject(fmt.Errorf("databricks: WithPort %d needs a host (WithServerHostname is empty): %w", port, dbsqlerr.ErrInvalidKernelConfig)) - } - h, err := parseKernelHost(host) - if err != nil { - return reject(fmt.Errorf("databricks: host %q is not a valid host (want a host name, an IPv4 address or an IPv6 literal): %v: %w", h.redacted, err, dbsqlerr.ErrInvalidKernelConfig)) - } - // A path, query or fragment is checked before the embedded-port parse. With the default port the - // host goes to the kernel unchanged, as before (the kernel appends its API paths after it). A - // non-default port cannot be folded into such a host, so reject it. - if h.hasPath { - if nonDefault { - return reject(fmt.Errorf("databricks: host %q has a path, query or fragment, so WithPort %d cannot be applied: %w", - h.redacted, port, dbsqlerr.ErrInvalidKernelConfig)) - } - return nil - } - // Credentials are kept only at the default port: a non-default port would have to be folded in without them. - if h.userinfo && nonDefault { - return reject(fmt.Errorf("databricks: host %q carries credentials, so WithPort %d cannot be applied: %w", - h.redacted, port, dbsqlerr.ErrInvalidKernelConfig)) - } - if h.password { - return reject(fmt.Errorf("databricks: host %q carries a password: %w", h.redacted, dbsqlerr.ErrInvalidKernelConfig)) - } - // url.Parse accepts a stray "]" in a plain name, so brackets are checked on the parsed host name - // (IPv6 brackets are already removed from it). - if strings.ContainsAny(h.name, "[]") { - return reject(fmt.Errorf("databricks: host %q has unbalanced IPv6 brackets: %w", h.redacted, dbsqlerr.ErrInvalidKernelConfig)) - } - if !h.hasPort { - return nil // no embedded port - } - embedded, err := strconv.Atoi(h.port) - if err != nil || embedded < 1 || embedded > 65535 { - return reject(fmt.Errorf("databricks: host %q carries an invalid port %q (want 1..65535): %w", h.redacted, h.port, dbsqlerr.ErrInvalidKernelConfig)) - } - // The embedded port is used, as on the kernel path before WithPort was honored. An explicit 443 is - // the default and is not warned about. - if nonDefault && embedded != port { - logger.Warn().Msgf("databricks: the host carries port %d, which differs from WithPort %d; connecting to port %d from the host", - embedded, port, embedded) + return fmt.Errorf("databricks: WithPort %d is out of range (want 1..65535, or 0 for the default): %w: %w", + port, dbsqlerr.ErrInvalidKernelConfig, dbsqlerr.ErrNotSupportedByKernel) } return nil } -// kernelHostWithPort returns the Host the kernel connects to. The kernel has no port setter but keeps a -// `host:port` authority, so a non-default port is folded in with net.JoinHostPort, which brackets an IPv6 -// literal. A trailing "/" is trimmed first, and a bare IPv6 literal is bracketed. 0 and 443 add nothing. A host that already carries a port, a -// path, query or fragment, or credentials is returned unchanged; validateKernelHostPort rejects the last -// two with a non-default port before the kernel is built. -func kernelHostWithPort(host string, port int) string { - h, err := parseKernelHost(host) - if err != nil || port == 0 || port == 443 || h.hasPort || h.hasPath || h.userinfo { - return h.raw - } - return net.JoinHostPort(h.name, strconv.Itoa(port)) -} - func kernelTelemetryConfig(cfg *config.Config) *kernel.TelemetryConfig { var enabled *bool if val, isSet := cfg.EnableTelemetry.Get(); isSet { diff --git a/kernel_config_test.go b/kernel_config_test.go index 2479678f3..621ee5e18 100644 --- a/kernel_config_test.go +++ b/kernel_config_test.go @@ -6,7 +6,6 @@ import ( "fmt" "net/http" "reflect" - "strings" "testing" "time" @@ -445,7 +444,7 @@ var kernelConfigFieldDisposition = map[string]string{ // Rejected loudly by validateKernelConfig. "QueryTimeout": "rejected", // when > 0 (WithTimeout) "Protocol": "rejected", // kernel is https-only; non-default rejected - "Port": "forwarded", // folded into the kernel Host by kernelHostWithPort; validated by validateKernelHostPort + "Port": "forwarded", // range-checked by validateKernelPort; passed to the kernel (set_port), which folds and validates it "Transport": "rejected", // custom RoundTripper; kernel uses its own HTTP stack, so reject rather than drop // Forwarded to the kernel's HTTP retry config via kernelRetryConfig → @@ -973,134 +972,49 @@ func TestKernelRetryConfig(t *testing.T) { }) } -// TestKernelCustomPort covers WithPort on the kernel backend: a non-default port is folded into the -// kernel Host, 0 and 443 add nothing, a port embedded in the host wins, a trailing "/" is trimmed, -// and a host with a path passes through unchanged unless a non-default port would be folded into it. -// Host parsing uses net/url. A bare IPv6 literal is bracketed before it is parsed, so it folds the same -// way as its bracketed form on every Go version. An out-of-range port or unbalanced IPv6 brackets are -// rejected with ErrInvalidKernelConfig. -func TestKernelCustomPort(t *testing.T) { - cases := []struct { - name string - host string - port int - wantHost string // kernelHostWithPort result for an accepted pair - wantErr bool - }{ - {"default 443 adds nothing", "h.databricks.com", 443, "h.databricks.com", false}, - {"unset port adds nothing", "h.databricks.com", 0, "h.databricks.com", false}, - {"custom port", "h.databricks.com", 8443, "h.databricks.com:8443", false}, - {"IPv4 literal", "127.0.0.1", 8443, "127.0.0.1:8443", false}, - {"bare IPv6 is bracketed and folded", "::1", 8443, "[::1]:8443", false}, - {"bare IPv6, full form", "2001:db8::1", 8443, "[2001:db8::1]:8443", false}, - {"bare IPv6, trailing slash", "::1/", 8443, "[::1]:8443", false}, - {"bare IPv6, default port: bracketed", "::1", 443, "[::1]", false}, - {"bare IPv6, unset port: bracketed", "::1", 0, "[::1]", false}, - {"bare IPv6, default port, trailing slash", "::1/", 443, "[::1]", false}, - {"bracketed IPv6", "[::1]", 8443, "[::1]:8443", false}, - {"bracketed IPv6, default port: unchanged", "[::1]", 443, "[::1]", false}, - {"port 1", "h.databricks.com", 1, "h.databricks.com:1", false}, - {"port 65535", "h.databricks.com", 65535, "h.databricks.com:65535", false}, - {"embedded port equal", "h.databricks.com:8443", 8443, "h.databricks.com:8443", false}, - {"embedded port equal, IPv6", "[::1]:8443", 8443, "[::1]:8443", false}, - {"443 with embedded 443", "h.databricks.com:443", 443, "h.databricks.com:443", false}, - {"443 with embedded port: embedded wins", "h.databricks.com:8443", 443, "h.databricks.com:8443", false}, - {"embedded port differs: embedded wins", "h.databricks.com:7000", 8443, "h.databricks.com:7000", false}, - {"embedded port differs, IPv6: embedded wins", "[::1]:7000", 8443, "[::1]:7000", false}, - {"trailing slash on bare host", "h.databricks.com/", 8443, "h.databricks.com:8443", false}, - {"trailing slash on bare host, default port", "h.databricks.com/", 443, "h.databricks.com", false}, - {"trailing slash with embedded port, default port", "h.databricks.com:8443/", 443, "h.databricks.com:8443", false}, - {"trailing slash with embedded port, equal port", "h.databricks.com:8443/", 8443, "h.databricks.com:8443", false}, - {"trailing slash, IPv6", "[::1]/", 8443, "[::1]:8443", false}, - {"path, default port: unchanged", "h.databricks.com/x", 443, "h.databricks.com/x", false}, - {"path, unset port: unchanged", "h.databricks.com/x", 0, "h.databricks.com/x", false}, - {"path with colon, default port: unchanged", "h.io/path:8443", 443, "h.io/path:8443", false}, - {"path with custom port", "h.databricks.com/x", 8443, "", true}, - {"path with colon and custom port", "h.io/path:8443", 8443, "", true}, - {"query with colon and custom port", "h.io?q=1:8443", 8443, "", true}, - {"query with custom port", "h.databricks.com?x", 8443, "", true}, - {"fragment with custom port", "h.databricks.com#x", 8443, "", true}, - {"negative port", "h.databricks.com", -1, "", true}, - {"port above range", "h.databricks.com", 65536, "", true}, - {"embedded port not a number", "h.databricks.com:notaport", 8443, "", true}, - {"embedded port out of range", "h.databricks.com:70000", 0, "", true}, - {"embedded port zero", "h.databricks.com:0", 0, "", true}, - {"unclosed IPv6 bracket", "[::1", 8443, "", true}, - {"text after IPv6 bracket", "[::1]x", 8443, "", true}, - {"stray closing bracket", "h.databricks.com]", 8443, "", true}, - {"stray closing bracket, default port", "h.databricks.com]", 443, "", true}, - {"text after IPv6 bracket, default port", "[::1]x", 443, "", true}, - {"unclosed IPv6 bracket, default port", "[::1", 443, "", true}, - // net/url rules: an empty port, credentials, an empty fragment and an IPv6 zone. - {"empty port after colon", "h:", 8443, "", true}, - {"empty port after colon, default port", "h:", 443, "", true}, - {"bare IPv6 with zone is rejected", "fe80::1%eth0", 8443, "", true}, - {"bare IPv6 with zone, default port: rejected", "fe80::1%eth0", 443, "", true}, - {"userinfo with bare IPv6, custom port: rejected", "user@::1", 8443, "", true}, - {"userinfo with bare IPv6, default port: bracketed", "user@::1", 443, "user@[::1]", false}, - {"userinfo, default port: unchanged", "user@h", 443, "user@h", false}, - {"userinfo, custom port: rejected", "user@h", 8443, "", true}, - {"userinfo with an embedded port, custom port: rejected", "user@h:8443", 9443, "", true}, - {"userinfo with an embedded port, default port: unchanged", "user@h:8443", 443, "user@h:8443", false}, - {"password, default port: rejected", "user:pw@h", 443, "", true}, - {"password, custom port: rejected", "user:pw@h", 8443, "", true}, - {"password with a path, default port: unchanged (path check runs first)", "user:pw@h/x", 443, "user:pw@h/x", false}, - {"password with a path, custom port: rejected", "user:pw@h/x", 8443, "", true}, - {"empty fragment, custom port: rejected (h#)", "h#", 8443, "", true}, - {"empty fragment, default port: unchanged (h#)", "h#", 443, "h#", false}, - {"embedded port out of range (h:70000)", "h:70000", 8443, "", true}, - {"embedded port not a number (h:abc)", "h:abc", 8443, "", true}, - {"mixed-case host is kept (custom port)", "H.Example.COM", 8443, "H.Example.COM:8443", false}, - {"mixed-case host is kept (default port)", "H.Example.COM", 443, "H.Example.COM", false}, - {"trailing slash after embedded port", "h:8443/", 8443, "h:8443", false}, - {"path with custom port (h/x)", "h/x", 8443, "", true}, - {"path, default port: unchanged (h/x)", "h/x", 443, "h/x", false}, - {"query with custom port (h?q)", "h?q", 8443, "", true}, - {"query, default port: unchanged (h?q)", "h?q", 443, "h?q", false}, - {"fragment with custom port (h#f)", "h#f", 8443, "", true}, - {"fragment, default port: unchanged (h#f)", "h#f", 443, "h#f", false}, - {"empty host, custom port: rejected", "", 8443, "", true}, - {"empty host, unset port: unchanged", "", 0, "", false}, - {"empty host, default port: unchanged", "", 443, "", false}, +// TestKernelPortPassThrough checks that the host reaches the kernel unchanged and the port +// reaches the kernel config. The kernel folds a non-default port into the host and validates +// the pair, so the driver adds no folding and no host validation. Credentials, paths and +// bad embedded ports are the kernel's to reject at session open (see TestOpenSessionPortRejection). +func TestKernelPortPassThrough(t *testing.T) { + hosts := []string{ + "h.databricks.com", + "h.databricks.com/", + "h.databricks.com:8443", + "127.0.0.1", + "::1", + "[::1]", + "h.databricks.com/x", + "user:pw@h", + "", } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - err := validateKernelHostPort(tc.host, tc.port) - if tc.wantErr { - if !errors.Is(err, dbsqlerr.ErrInvalidKernelConfig) { - t.Errorf("err = %v, want ErrInvalidKernelConfig", err) + ports := []int{0, 443, 8443, 65535} + for _, host := range hosts { + for _, port := range ports { + t.Run(fmt.Sprintf("host %q port %d", host, port), func(t *testing.T) { + c := baseKernelConfig() + c.Host = host + c.Port = port + kauth, err := validateKernelConfig(c) + if err != nil { + t.Fatalf("validateKernelConfig: %v", err) } - // Before WithPort was honored, a non-default port was ErrNotSupportedByKernel on the kernel - // path, so a rejection with one still wraps it; a default-port rejection does not. - nonDefault := tc.port != 0 && tc.port != 443 - if got := errors.Is(err, dbsqlerr.ErrNotSupportedByKernel); got != nonDefault { - t.Errorf("errors.Is(err, ErrNotSupportedByKernel) = %v, want %v (err %v)", got, nonDefault, err) + kc := buildKernelConfig(c, kauth) + if kc.Host != host { + t.Errorf("kernel Host = %q, want the host unchanged", kc.Host) } - return - } - if err != nil { - t.Errorf("unexpected err %v", err) - } - if got := kernelHostWithPort(tc.host, tc.port); got != tc.wantHost { - t.Errorf("kernelHostWithPort(%q, %d) = %q, want %q", tc.host, tc.port, got, tc.wantHost) - } - }) - } - - t.Run("explicit WithPort(443) differing from an embedded port connects to the embedded port", func(t *testing.T) { - c := baseKernelConfig() - c.Host = "h.databricks.com:8443" - WithPort(443)(c) - kauth, err := validateKernelConfig(c) - if err != nil { - t.Fatalf("unexpected err %v", err) - } - if got := buildKernelConfig(c, kauth).Host; got != "h.databricks.com:8443" { - t.Errorf("kernel Host = %q, want the embedded port h.databricks.com:8443", got) + if kc.Port != uint16(port) { + t.Errorf("kernel Port = %d, want %d", kc.Port, port) + } + }) } - }) + } +} - t.Run("WithServerHostname with a trailing slash plus WithPort folds to host:port", func(t *testing.T) { +// TestKernelPortFromOptions checks the connector options that set the host and port: WithServerHostname +// and WithPort reach the kernel config as given, and a port embedded in the host is left for the kernel. +func TestKernelPortFromOptions(t *testing.T) { + t.Run("WithServerHostname with a trailing slash plus WithPort", func(t *testing.T) { c := baseKernelConfig() WithServerHostname("https://h.databricks.com/")(c) WithPort(8443)(c) @@ -1108,50 +1022,63 @@ func TestKernelCustomPort(t *testing.T) { if err != nil { t.Fatalf("unexpected err %v", err) } - if got := buildKernelConfig(c, kauth).Host; got != "h.databricks.com:8443" { - t.Errorf("kernel Host = %q, want h.databricks.com:8443", got) + kc := buildKernelConfig(c, kauth) + if kc.Host != "h.databricks.com/" || kc.Port != 8443 { + t.Errorf("kernel Host=%q Port=%d, want h.databricks.com/ and 8443", kc.Host, kc.Port) } }) - t.Run("WithServerHostname with an embedded port and a trailing slash is still accepted", func(t *testing.T) { + t.Run("embedded port with WithPort(443) is passed through for the kernel to resolve", func(t *testing.T) { c := baseKernelConfig() - WithServerHostname("https://h.databricks.com:8443/")(c) + c.Host = "h.databricks.com:8443" + WithPort(443)(c) kauth, err := validateKernelConfig(c) if err != nil { t.Fatalf("unexpected err %v", err) } - if got := buildKernelConfig(c, kauth).Host; got != "h.databricks.com:8443" { - t.Errorf("kernel Host = %q, want h.databricks.com:8443", got) + kc := buildKernelConfig(c, kauth) + if kc.Host != "h.databricks.com:8443" || kc.Port != 443 { + t.Errorf("kernel Host=%q Port=%d, want h.databricks.com:8443 and 443", kc.Host, kc.Port) } }) +} - t.Run("kernel Host: unset port keeps the embedded port, custom port folds in", func(t *testing.T) { +// TestKernelPortRange checks the driver's only port check, the uint16 range. Both bounds of the +// rejection wrap ErrInvalidKernelConfig and ErrNotSupportedByKernel, since an out-of-range port is +// never the default. +func TestKernelPortRange(t *testing.T) { + for _, port := range []int{-1, 65536} { c := baseKernelConfig() - c.Host = "h.databricks.com:8443" - kauth, err := validateKernelConfig(c) - if err != nil || buildKernelConfig(c, kauth).Host != "h.databricks.com:8443" { - t.Errorf("embedded port: err=%v host=%q", err, buildKernelConfig(c, kauth).Host) + c.Port = port + _, err := validateKernelConfig(c) + if !errors.Is(err, dbsqlerr.ErrInvalidKernelConfig) { + t.Errorf("WithPort(%d): err = %v, want ErrInvalidKernelConfig", port, err) } - c = baseKernelConfig() - WithPort(8443)(c) - kauth, err = validateKernelConfig(c) - if err != nil || buildKernelConfig(c, kauth).Host != "h.databricks.com:8443" { - t.Errorf("WithPort(8443): err=%v host=%q", err, buildKernelConfig(c, kauth).Host) + if !errors.Is(err, dbsqlerr.ErrNotSupportedByKernel) { + t.Errorf("WithPort(%d): err = %v, want ErrNotSupportedByKernel", port, err) } - }) + } + for _, port := range []int{0, 1, 443, 65535} { + c := baseKernelConfig() + c.Port = port + if _, err := validateKernelConfig(c); err != nil { + t.Errorf("WithPort(%d): unexpected err %v", port, err) + } + } } -// TestKernelIPv6FromDSN checks that a DSN IPv6 host reaches the kernel the same way as its bracketed form. -// ParseDSN strips the brackets (url.Hostname), so the kernel path gets a bare "::1" and the port separately. -func TestKernelIPv6FromDSN(t *testing.T) { +// TestKernelDSNHostAndPort checks that a DSN IPv6 host reaches the kernel as the bare address with +// the port alongside it. ParseDSN strips the brackets (url.Hostname); the kernel folds the port. +func TestKernelDSNHostAndPort(t *testing.T) { cases := []struct { name string dsn string wantHost string + wantPort uint16 }{ - {"bracketed IPv6 with custom port", "token:x@[::1]:8443/sql/1.0/warehouses/abc", "[::1]:8443"}, - {"bracketed IPv6 with default port", "token:x@[::1]:443/sql/1.0/warehouses/abc", "[::1]"}, - {"IPv4 with custom port", "token:x@10.0.0.1:8443/sql/1.0/warehouses/abc", "10.0.0.1:8443"}, + {"bracketed IPv6 with custom port", "token:x@[::1]:8443/sql/1.0/warehouses/abc", "::1", 8443}, + {"bracketed IPv6 with default port", "token:x@[::1]:443/sql/1.0/warehouses/abc", "::1", 443}, + {"IPv4 with custom port", "token:x@10.0.0.1:8443/sql/1.0/warehouses/abc", "10.0.0.1", 8443}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -1171,69 +1098,10 @@ func TestKernelIPv6FromDSN(t *testing.T) { if err != nil { t.Fatalf("validateKernelConfig: %v", err) } - if got := buildKernelConfig(coni.cfg, kauth).Host; got != tc.wantHost { - t.Errorf("kernel Host = %q, want %q", got, tc.wantHost) - } - }) - } -} - -// TestKernelHostErrorsRedactCredentials checks that no host error carries the password or the user part. -// The password includes a bad escape, so url.Parse's own text would quote it; that text is withheld when -// the host has user info. Every error still names the host with the credentials replaced by . -func TestKernelHostErrorsRedactCredentials(t *testing.T) { - const secret = "pSecret" - cases := []struct { - name string - host string - port int - }{ - {"password with a bad escape, default port (url.Parse fails)", "user:" + secret + "%zz@h", 443}, - {"password with a bad escape, custom port (url.Parse fails)", "user:" + secret + "%zz@h", 8443}, - {"password, custom port", "user:" + secret + "@h", 8443}, - {"password, default port", "user:" + secret + "@h", 443}, - {"password with an embedded port", "user:" + secret + "@h:8443", 443}, - {"password with an invalid embedded port", "user:" + secret + "@h:bad", 443}, - {"password with unbalanced bracket", "user:" + secret + "@h]", 443}, - {"password with a path, custom port", "user:" + secret + "@h/x", 8443}, - {"password with a query, custom port", "user:" + secret + "@h?x", 8443}, - {"password with an IPv6 literal", "user:" + secret + "@[::1]", 443}, - {"password with a bad IPv6 bracket", "user:" + secret + "@[::1", 443}, - {"password with a bare IPv6 literal", "user:" + secret + "@::1", 443}, - // A "/", "?" or "#" inside the password ends the authority before the "@", so redaction must not rely - // on the authority split. - {"password containing a slash, default port", "user:" + secret + "/part@h", 443}, - {"password containing a slash, custom port", "user:" + secret + "/part@h", 8443}, - {"password containing a question mark", "user:" + secret + "?part@h", 443}, - {"password containing a hash", "user:" + secret + "#part@h", 8443}, - } - check := func(t *testing.T, err error) { - t.Helper() - if err == nil { - t.Fatal("expected an error") - } - if !errors.Is(err, dbsqlerr.ErrInvalidKernelConfig) { - t.Errorf("err = %v, want ErrInvalidKernelConfig", err) - } - msg := err.Error() - for _, leak := range []string{"Secret", "%zz", "user:", "user@"} { - if strings.Contains(msg, leak) { - t.Errorf("error %q leaks %q", msg, leak) + kc := buildKernelConfig(coni.cfg, kauth) + if kc.Host != tc.wantHost || kc.Port != tc.wantPort { + t.Errorf("kernel Host=%q Port=%d, want %q and %d", kc.Host, kc.Port, tc.wantHost, tc.wantPort) } - } - if !strings.Contains(msg, "@") { - t.Errorf("error %q does not name the redacted host", msg) - } - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - check(t, validateKernelHostPort(tc.host, tc.port)) }) } - t.Run("through validateKernelConfig", func(t *testing.T) { - c := baseKernelConfig() - c.Host = "user:" + secret + "@h" - _, err := validateKernelConfig(c) - check(t, err) - }) } diff --git a/kernel_proxy.go b/kernel_proxy.go index 1c37b4450..a00dc162f 100644 --- a/kernel_proxy.go +++ b/kernel_proxy.go @@ -2,8 +2,11 @@ package dbsql import ( "fmt" + "net" "net/http" "net/url" + "strconv" + "strings" "github.com/databricks/databricks-sql-go/internal/config" ) @@ -24,6 +27,25 @@ func proxyForEndpoint(cfg *config.Config) string { return proxyForEndpointFunc(cfg, http.ProxyFromEnvironment) } +// kernelEndpointHost is the host:port the kernel dials, used only to pick the proxy +// (HTTPS_PROXY / NO_PROXY). It applies the kernel's simple port rule without the +// kernel's validation: a port of 0 or 443 leaves the host as given; a host that already +// carries a port keeps it (an embedded port wins over WithPort, as in the kernel); any +// other port is appended, bracketing an IPv6 literal. A trailing "/" is trimmed. A +// malformed host is passed through, since the kernel rejects it at session open. It +// returns no error and never echoes the host, so it cannot leak credentials. +func kernelEndpointHost(host string, port int) string { + host = strings.TrimRight(host, "/") + if port == 0 || port == 443 { + return host + } + if _, _, err := net.SplitHostPort(host); err == nil { + return host + } + bare := strings.TrimSuffix(strings.TrimPrefix(host, "["), "]") + return net.JoinHostPort(bare, strconv.Itoa(port)) +} + // proxyForEndpointFunc is the testable core: it builds the endpoint request and // asks resolve for the proxy, returning "" (direct) on any error, no proxy, or an // unbuildable endpoint. resolve is http.ProxyFromEnvironment in production; tests @@ -43,9 +65,7 @@ func proxyForEndpointFunc(cfg *config.Config, resolve func(*http.Request) (*url. if scheme == "" { scheme = "https" } - // Same authority the kernel connects to: an embedded port is not appended twice - // and an IPv6 literal is bracketed (kernelHostWithPort). - endpoint := fmt.Sprintf("%s://%s", scheme, kernelHostWithPort(cfg.Host, cfg.Port)) + endpoint := fmt.Sprintf("%s://%s", scheme, kernelEndpointHost(cfg.Host, cfg.Port)) req, err := http.NewRequest(http.MethodPost, endpoint, nil) if err != nil { return "" From 1a2a075fdfe3e77f1c9f0cd137b15a7d569e662e Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:49:33 +0000 Subject: [PATCH 12/17] chore(kernel): pin KERNEL_REV to the kernel port PR head Move KERNEL_REV to 22ae6ec250837b38d0e3dc720310d4dcfb81fa98 (databricks/databricks-sql-kernel#505 head) and copy its header. The only header change is the set_port doc comment: a default port never warns about a port already in the host. Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac --- KERNEL_REV | 2 +- internal/backend/kernel/include/databricks_kernel.h | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/KERNEL_REV b/KERNEL_REV index 6e083d73b..bb1a004ed 100644 --- a/KERNEL_REV +++ b/KERNEL_REV @@ -1 +1 @@ -b5aac45d54bb4842b7e04dd7fbf2368216b6de4e +22ae6ec250837b38d0e3dc720310d4dcfb81fa98 diff --git a/internal/backend/kernel/include/databricks_kernel.h b/internal/backend/kernel/include/databricks_kernel.h index 0e9af665b..a9d9bd001 100644 --- a/internal/backend/kernel/include/databricks_kernel.h +++ b/internal/backend/kernel/include/databricks_kernel.h @@ -253,7 +253,8 @@ KernelStatusCode kernel_session_config_set_http_path(KernelSessionConfig* config * The host must not carry userinfo (`user:pw@host`), a path, a query or a * fragment, and must not be empty. A port already embedded in the host * (`host:N` or `[v6]:N`) is kept and wins over this one; the kernel logs a - * warning when the two differ. Validation is eager: a bad combination returns + * warning when a non-default port differs from it (the scheme default never + * warns). Validation is eager: a bad combination returns * KernelStatusCode_InvalidArgument from whichever of this call or the host * setter came second, and leaves the config unchanged. Error text never * includes credentials. */ From 922e73a7e238c7067ec6c09846c3e8f14e7f1841 Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:33:47 +0000 Subject: [PATCH 13/17] fix(kernel): apply the port error contract only to set_port OpenSession sets the host before the port, so an InvalidArgument from set_warehouse or set_http_path can't be a port rejection. Tagging those errors with ErrNotSupportedByKernel for a custom port could trigger a needless fallback to Thrift. They now keep main's classification. Also drop the docs' default-port rejection clause: the kernel accepts 443 without validation. And compare the port as int in TestKernelPortPassThrough, which gosec flagged as a narrowing conversion (G115). Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac --- CHANGELOG.md | 2 +- CONNECTION_PARAMETERS.md | 2 +- README.md | 2 +- internal/backend/kernel/backend.go | 4 ++-- internal/backend/kernel/errors_classify.go | 17 +++++++++-------- kernel_config_test.go | 2 +- 6 files changed, 15 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c29156537..1cf5d97e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ ### Driver changes -- Honor `WithPort` / DSN port on the kernel backend, including the automatic Reyden recovery onto the kernel, instead of rejecting a non-default port. The kernel applies the port (`kernel_session_config_set_port`), and the driver passes the host through unchanged. Rules: a port of `0` or the scheme default `443` leaves the host unchanged and unvalidated; any other port becomes `host:port`, with a bare IPv6 literal bracketed (`[::1]:8443`); a port already in the host wins over a differing `WithPort`, and the kernel logs a warning. The kernel rejects credentials, an empty host, a path, query or fragment, and a bad embedded port with `InvalidArgument`, at connect. The driver checks only that `WithPort` is in `0..65535` (`ErrInvalidKernelConfig` and `ErrNotSupportedByKernel`). A kernel `InvalidArgument` for a non-default port wraps both sentinels, so a fallback to the default backend on `ErrNotSupportedByKernel` still works. For the default port it wraps only `ErrInvalidKernelConfig`. Errors never include credentials; the kernel redacts its messages. With OAuth and a non-default port, the kernel uses the same `host:port` for OAuth; Thrift keeps OAuth on the bare host (documented, not guarded). +- Honor `WithPort` / DSN port on the kernel backend, including the automatic Reyden recovery onto the kernel, instead of rejecting a non-default port. The kernel applies the port (`kernel_session_config_set_port`), and the driver passes the host through unchanged. Rules: a port of `0` or the scheme default `443` leaves the host unchanged and unvalidated; any other port becomes `host:port`, with a bare IPv6 literal bracketed (`[::1]:8443`); a port already in the host wins over a differing `WithPort`, and the kernel logs a warning. The kernel rejects credentials, an empty host, a path, query or fragment, and a bad embedded port with `InvalidArgument`, at connect. The driver checks only that `WithPort` is in `0..65535` (`ErrInvalidKernelConfig` and `ErrNotSupportedByKernel`). A kernel `InvalidArgument` from setting a non-default port wraps both sentinels, so a fallback to the default backend on `ErrNotSupportedByKernel` still works. Host errors keep their existing classification. Errors never include credentials; the kernel redacts its messages. With OAuth and a non-default port, the kernel uses the same `host:port` for OAuth; Thrift keeps OAuth on the bare host (documented, not guarded). - **Behavior change:** Bound each whole-transfer Thrift CloudFetch download attempt, including `WithTransport`, by the existing 900s `ClientTimeout`, and omit the link's presigned query string from download errors (databricks/databricks-sql-go#475). ## v2.0.0 (2026-11-23) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index a79c5a95b..04a91523b 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -40,7 +40,7 @@ wire. They are listed under [Kernel client-result confs](#kernel-client-result-c |---|---|:---:|:---:|---|---| | *(host)* | `WithServerHostname` | ✅ | ✅ | *(required)* | Workspace hostname. | | *(path)* | `WithHTTPPath` | ✅ | ✅ | required on Thrift except localhost; required on kernel unless `warehouseId` is set | Warehouse/endpoint HTTP path. On the kernel path, a bare warehouse id can be used instead. | -| *(port)* | `WithPort` | ✅ | ✅ | `443` for connector options; required in a DSN | The kernel applies the port: a port of `0` or `443` leaves the host unchanged and unvalidated; any other port connects to `host:port`, with a bare IPv6 literal bracketed (`[::1]:8443`). A port already in the host wins over a differing `WithPort` (the kernel logs a warning). The kernel rejects credentials, an empty host, a path, query or fragment, and a bad embedded port with `InvalidArgument` at connect. The driver rejects only a `WithPort` outside `0..65535`. A non-default port's rejection wraps both `ErrInvalidKernelConfig` and `ErrNotSupportedByKernel`; a default-port rejection wraps only `ErrInvalidKernelConfig`. Errors never include credentials. With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | +| *(port)* | `WithPort` | ✅ | ✅ | `443` for connector options; required in a DSN | The kernel applies the port: a port of `0` or `443` leaves the host unchanged and unvalidated; any other port connects to `host:port`, with a bare IPv6 literal bracketed (`[::1]:8443`). A port already in the host wins over a differing `WithPort` (the kernel logs a warning). The kernel rejects credentials, an empty host, a path, query or fragment, and a bad embedded port with `InvalidArgument` at connect. The driver rejects only a `WithPort` outside `0..65535`. A non-default port's rejection wraps both `ErrInvalidKernelConfig` and `ErrNotSupportedByKernel`. Errors never include credentials. With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | | *(scheme)* | *(via `WithServerHostname`)* | ✅ | ⚠️ | `https` | Kernel accepts `https` only and rejects `http`. A bare `localhost` passed to `WithServerHostname` selects `http`; a scheme-less DSN, including localhost, is prefixed with `https`. | | `warehouseId` | `WithWarehouseID` | ⚠️ | ✅ | | Bare warehouse id. The kernel normally prefers it over the HTTP path; a canonical path carrying `?o=` takes precedence so workspace-org routing is preserved. The Thrift backend **silently ignores** it. | | `catalog` | `WithInitialNamespace` | ✅ | ✅ | | Initial catalog. Kernel applies it post-connect via `USE CATALOG`. | diff --git a/README.md b/README.md index 3ceb6002b..dc28f9208 100644 --- a/README.md +++ b/README.md @@ -252,7 +252,7 @@ session parameter on both backends. |---|---|---|---|---| | *(host)* | `WithServerHostname` | Both | *(required)* | Workspace hostname. | | *(path)* | `WithHTTPPath` | Both | *(required)* | Warehouse/endpoint HTTP path. | -| *(port)* | `WithPort` | Both | `443` | The kernel applies the port: a port of `0` or `443` leaves the host unchanged and unvalidated; any other port connects to `host:port`, with a bare IPv6 literal bracketed (`[::1]:8443`). A port already in the host wins over a differing `WithPort` (the kernel logs a warning). The kernel rejects credentials, an empty host, a path, query or fragment, and a bad embedded port with `InvalidArgument` at connect. The driver rejects only a `WithPort` outside `0..65535`. A non-default port's rejection wraps both `ErrInvalidKernelConfig` and `ErrNotSupportedByKernel`; a default-port rejection wraps only `ErrInvalidKernelConfig`. Errors never include credentials. With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | +| *(port)* | `WithPort` | Both | `443` | The kernel applies the port: a port of `0` or `443` leaves the host unchanged and unvalidated; any other port connects to `host:port`, with a bare IPv6 literal bracketed (`[::1]:8443`). A port already in the host wins over a differing `WithPort` (the kernel logs a warning). The kernel rejects credentials, an empty host, a path, query or fragment, and a bad embedded port with `InvalidArgument` at connect. The driver rejects only a `WithPort` outside `0..65535`. A non-default port's rejection wraps both `ErrInvalidKernelConfig` and `ErrNotSupportedByKernel`. Errors never include credentials. With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | | `warehouseId` | `WithWarehouseID` | SEA only | | Bare warehouse id; the kernel routes by it (preferred over the HTTP path). **The Thrift backend ignores it.** | | `catalog` | `WithInitialNamespace` | Both | | Initial catalog. Kernel applies it post-connect via `USE CATALOG`. | | `schema` | `WithInitialNamespace` | Both | | Initial schema. Kernel applies it post-connect via `USE SCHEMA`. | diff --git a/internal/backend/kernel/backend.go b/internal/backend/kernel/backend.go index a356f7eee..0eaa77b44 100644 --- a/internal/backend/kernel/backend.go +++ b/internal/backend/kernel/backend.go @@ -198,7 +198,7 @@ func (k *KernelBackend) OpenSession(ctx context.Context) error { if err := call(func() C.KernelStatusCode { return C.kernel_session_config_set_warehouse(cfg, host.c, wh.c) }); err != nil { - return fmt.Errorf("kernel: set_warehouse: %w", portRejection(k.cfg.Port, toConnError(err))) + return fmt.Errorf("kernel: set_warehouse: %w", toConnError(err)) } } else { path := newCStr(k.cfg.HTTPPath) @@ -206,7 +206,7 @@ func (k *KernelBackend) OpenSession(ctx context.Context) error { if err := call(func() C.KernelStatusCode { return C.kernel_session_config_set_http_path(cfg, host.c, path.c) }); err != nil { - return fmt.Errorf("kernel: set_http_path: %w", portRejection(k.cfg.Port, toConnError(err))) + return fmt.Errorf("kernel: set_http_path: %w", toConnError(err)) } } diff --git a/internal/backend/kernel/errors_classify.go b/internal/backend/kernel/errors_classify.go index fa854f855..e43db1447 100644 --- a/internal/backend/kernel/errors_classify.go +++ b/internal/backend/kernel/errors_classify.go @@ -207,14 +207,15 @@ func toStatementError(err error) error { // kernelDefaultPort is the https default. The kernel accepts it and changes nothing. const kernelDefaultPort uint16 = 443 -// portRejection applies the WithPort error contract to a kernel rejection. The kernel -// validates the port against the host (kernel_session_config_set_port, and the host -// setters, which re-check it), so an InvalidArgument from any of those calls is the -// kernel's verdict on the pair. A non-default port wraps both ErrInvalidKernelConfig -// and ErrNotSupportedByKernel, so a caller can fall back to the default backend with -// errors.Is. The default port wraps only ErrInvalidKernelConfig. Port 0 (unset), other -// codes and non-kernel errors pass through unchanged. The kernel's message is already -// redacted, so the wrapper adds no host text. +// portRejection applies the WithPort error contract to a kernel_session_config_set_port +// rejection. The kernel validates the port against the host already set, so an +// InvalidArgument there is the kernel's verdict on the pair. A non-default port wraps both +// ErrInvalidKernelConfig and ErrNotSupportedByKernel, so a caller can fall back to the +// default backend with errors.Is. The kernel accepts the default port without validation; +// were it rejected, only ErrInvalidKernelConfig is wrapped. Port 0 (unset), other codes and +// non-kernel errors pass through unchanged. Host setter errors are not passed here: they +// run before the port is set. The kernel's message is already redacted, so the wrapper +// adds no host text. func portRejection(port uint16, err error) error { if err == nil || port == 0 { return err diff --git a/kernel_config_test.go b/kernel_config_test.go index 879a738b9..7ab962811 100644 --- a/kernel_config_test.go +++ b/kernel_config_test.go @@ -1003,7 +1003,7 @@ func TestKernelPortPassThrough(t *testing.T) { if kc.Host != host { t.Errorf("kernel Host = %q, want the host unchanged", kc.Host) } - if kc.Port != uint16(port) { + if int(kc.Port) != port { t.Errorf("kernel Port = %d, want %d", kc.Port, port) } }) From 1c3bcc590d8ee473d3915699033a87d652b63db0 Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:32:12 +0000 Subject: [PATCH 14/17] docs(changelog): shorten the port entry Keep the user-facing change and its requirement; the detailed rules stay in the connection parameter docs and the PR description. Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1cf5d97e7..3a4ab9aa9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ ### Driver changes -- Honor `WithPort` / DSN port on the kernel backend, including the automatic Reyden recovery onto the kernel, instead of rejecting a non-default port. The kernel applies the port (`kernel_session_config_set_port`), and the driver passes the host through unchanged. Rules: a port of `0` or the scheme default `443` leaves the host unchanged and unvalidated; any other port becomes `host:port`, with a bare IPv6 literal bracketed (`[::1]:8443`); a port already in the host wins over a differing `WithPort`, and the kernel logs a warning. The kernel rejects credentials, an empty host, a path, query or fragment, and a bad embedded port with `InvalidArgument`, at connect. The driver checks only that `WithPort` is in `0..65535` (`ErrInvalidKernelConfig` and `ErrNotSupportedByKernel`). A kernel `InvalidArgument` from setting a non-default port wraps both sentinels, so a fallback to the default backend on `ErrNotSupportedByKernel` still works. Host errors keep their existing classification. Errors never include credentials; the kernel redacts its messages. With OAuth and a non-default port, the kernel uses the same `host:port` for OAuth; Thrift keeps OAuth on the bare host (documented, not guarded). +- Honor `WithPort` and the DSN port on the kernel backend, including after automatic Reyden recovery, instead of rejecting a non-default port. A host the kernel can't combine with that port returns an error wrapping both `ErrInvalidKernelConfig` and `ErrNotSupportedByKernel`. - **Behavior change:** Bound each whole-transfer Thrift CloudFetch download attempt, including `WithTransport`, by the existing 900s `ClientTimeout`, and omit the link's presigned query string from download errors (databricks/databricks-sql-go#475). ## v2.0.0 (2026-11-23) From 0d7098016e7c4e81bed6fbc2ea25693f6e6ab1ac Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:04:38 +0000 Subject: [PATCH 15/17] refactor(kernel): pass WithPort to the kernel as is The driver no longer validates or folds the port. WithPort and the DSN port go to the kernel unchanged, and the kernel range-checks the port and validates the host/port pair at connect. The driver keeps no port logic of its own. - kernel.Config.Port is an int, passed to kernel_session_config_set_port as int64 when non-zero. - Drop the driver-side port range check, the uint16 narrowing, and the kernelEndpointHost helper. The proxy endpoint is built from Host and Port as on main. - Bump KERNEL_REV to 7e76a603fd4e3ce74e90e6c578e86bc75ac025eb and copy its header. The kernel's rules: an IPv6 host needs brackets, a non-default port already in the host wins, a default port in the host counts as none, and errors never include the host. - An out-of-range or otherwise invalid non-default port now fails at connect, not in config validation. It wraps both ErrInvalidKernelConfig and ErrNotSupportedByKernel. - Update CONNECTION_PARAMETERS.md, README.md and CHANGELOG.md to match. Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac --- CHANGELOG.md | 2 +- CONNECTION_PARAMETERS.md | 2 +- KERNEL_REV | 2 +- README.md | 2 +- connector_reyden_test.go | 5 +- internal/backend/kernel/backend.go | 6 +- internal/backend/kernel/config.go | 2 +- internal/backend/kernel/errors_classify.go | 12 +-- .../backend/kernel/errors_classify_test.go | 2 +- .../kernel/include/databricks_kernel.h | 22 ++--- internal/backend/kernel/port_test.go | 25 +++++- kernel_config.go | 23 +---- kernel_config_test.go | 90 ++++++------------- kernel_proxy.go | 27 +----- kernel_proxy_test.go | 68 -------------- 15 files changed, 85 insertions(+), 205 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a4ab9aa9..adc74ad05 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ ### Driver changes -- Honor `WithPort` and the DSN port on the kernel backend, including after automatic Reyden recovery, instead of rejecting a non-default port. A host the kernel can't combine with that port returns an error wrapping both `ErrInvalidKernelConfig` and `ErrNotSupportedByKernel`. +- Pass `WithPort` and the DSN port to the kernel backend unchanged, including after automatic Reyden recovery, instead of rejecting a non-default port; IPv6 hosts need brackets. The kernel validates the port and host at connect, and a non-default port it rejects returns an error wrapping both `ErrInvalidKernelConfig` and `ErrNotSupportedByKernel` that never includes the host. - **Behavior change:** Bound each whole-transfer Thrift CloudFetch download attempt, including `WithTransport`, by the existing 900s `ClientTimeout`, and omit the link's presigned query string from download errors (databricks/databricks-sql-go#475). ## v2.0.0 (2026-11-23) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 04a91523b..d60cea0ac 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -40,7 +40,7 @@ wire. They are listed under [Kernel client-result confs](#kernel-client-result-c |---|---|:---:|:---:|---|---| | *(host)* | `WithServerHostname` | ✅ | ✅ | *(required)* | Workspace hostname. | | *(path)* | `WithHTTPPath` | ✅ | ✅ | required on Thrift except localhost; required on kernel unless `warehouseId` is set | Warehouse/endpoint HTTP path. On the kernel path, a bare warehouse id can be used instead. | -| *(port)* | `WithPort` | ✅ | ✅ | `443` for connector options; required in a DSN | The kernel applies the port: a port of `0` or `443` leaves the host unchanged and unvalidated; any other port connects to `host:port`, with a bare IPv6 literal bracketed (`[::1]:8443`). A port already in the host wins over a differing `WithPort` (the kernel logs a warning). The kernel rejects credentials, an empty host, a path, query or fragment, and a bad embedded port with `InvalidArgument` at connect. The driver rejects only a `WithPort` outside `0..65535`. A non-default port's rejection wraps both `ErrInvalidKernelConfig` and `ErrNotSupportedByKernel`. Errors never include credentials. With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | +| *(port)* | `WithPort` | ✅ | ✅ | `443` for connector options; required in a DSN | The port is passed to the kernel as is, and the kernel validates it at connect. `0` leaves the host unchanged, and any other port connects to `host:port`. An IPv6 host needs brackets (`[::1]`, not `::1`), so the port becomes `[::1]:8443`. A non-default port already in the host (`host:8443`) wins over `WithPort` and the kernel logs a warning; a default port in the host (`host:443`) counts as no port, so `WithPort` applies. An invalid port (outside `0..65535`) or host (credentials, a path, query or fragment, an empty host, or an unbracketed IPv6 address) is rejected at connect with `InvalidArgument`. A non-default port's rejection wraps both `ErrInvalidKernelConfig` and `ErrNotSupportedByKernel`. Errors never include the host. With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | | *(scheme)* | *(via `WithServerHostname`)* | ✅ | ⚠️ | `https` | Kernel accepts `https` only and rejects `http`. A bare `localhost` passed to `WithServerHostname` selects `http`; a scheme-less DSN, including localhost, is prefixed with `https`. | | `warehouseId` | `WithWarehouseID` | ⚠️ | ✅ | | Bare warehouse id. The kernel normally prefers it over the HTTP path; a canonical path carrying `?o=` takes precedence so workspace-org routing is preserved. The Thrift backend **silently ignores** it. | | `catalog` | `WithInitialNamespace` | ✅ | ✅ | | Initial catalog. Kernel applies it post-connect via `USE CATALOG`. | diff --git a/KERNEL_REV b/KERNEL_REV index bb1a004ed..4e5ff54b6 100644 --- a/KERNEL_REV +++ b/KERNEL_REV @@ -1 +1 @@ -22ae6ec250837b38d0e3dc720310d4dcfb81fa98 +7e76a603fd4e3ce74e90e6c578e86bc75ac025eb diff --git a/README.md b/README.md index dc28f9208..0de0c28fb 100644 --- a/README.md +++ b/README.md @@ -252,7 +252,7 @@ session parameter on both backends. |---|---|---|---|---| | *(host)* | `WithServerHostname` | Both | *(required)* | Workspace hostname. | | *(path)* | `WithHTTPPath` | Both | *(required)* | Warehouse/endpoint HTTP path. | -| *(port)* | `WithPort` | Both | `443` | The kernel applies the port: a port of `0` or `443` leaves the host unchanged and unvalidated; any other port connects to `host:port`, with a bare IPv6 literal bracketed (`[::1]:8443`). A port already in the host wins over a differing `WithPort` (the kernel logs a warning). The kernel rejects credentials, an empty host, a path, query or fragment, and a bad embedded port with `InvalidArgument` at connect. The driver rejects only a `WithPort` outside `0..65535`. A non-default port's rejection wraps both `ErrInvalidKernelConfig` and `ErrNotSupportedByKernel`. Errors never include credentials. With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | +| *(port)* | `WithPort` | Both | `443` | The port is passed to the kernel as is, and the kernel validates it at connect. `0` leaves the host unchanged, and any other port connects to `host:port`. An IPv6 host needs brackets (`[::1]`, not `::1`), so the port becomes `[::1]:8443`. A non-default port already in the host (`host:8443`) wins over `WithPort` and the kernel logs a warning; a default port in the host (`host:443`) counts as no port, so `WithPort` applies. An invalid port (outside `0..65535`) or host (credentials, a path, query or fragment, an empty host, or an unbracketed IPv6 address) is rejected at connect with `InvalidArgument`. A non-default port's rejection wraps both `ErrInvalidKernelConfig` and `ErrNotSupportedByKernel`. Errors never include the host. With OAuth the kernel uses the same `host:port` for its OAuth endpoints; Thrift keeps OAuth on the bare host. | | `warehouseId` | `WithWarehouseID` | SEA only | | Bare warehouse id; the kernel routes by it (preferred over the HTTP path). **The Thrift backend ignores it.** | | `catalog` | `WithInitialNamespace` | Both | | Initial catalog. Kernel applies it post-connect via `USE CATALOG`. | | `schema` | `WithInitialNamespace` | Both | | Initial schema. Kernel applies it post-connect via `USE SCHEMA`. | diff --git a/connector_reyden_test.go b/connector_reyden_test.go index a775304dc..151dcb26d 100644 --- a/connector_reyden_test.go +++ b/connector_reyden_test.go @@ -228,7 +228,6 @@ func TestReydenReactiveRecovery(t *testing.T) { "Lakehouse/RT is not supported for Thrift protocol")}, nil }, func(ctx context.Context, cfg *config.Config) (backend.Backend, error) { - require.NoError(t, validateKernelPort(cfg.Port)) kernelCfg = buildKernelConfig(cfg, kernel.Auth{Mode: kernel.AuthPAT, Token: "test-token"}) return &fakeKernelBackend{}, nil }, @@ -237,9 +236,9 @@ func TestReydenReactiveRecovery(t *testing.T) { _, _, err := conn.openSessionWithReydenFallback(context.Background()) require.NoError(t, err) - // The host is passed through; the port reaches the kernel, which folds it. + // The host and port are passed through; the kernel validates the pair at connect. assert.Equal(t, "reyden.example.com", kernelCfg.Host) - assert.Equal(t, uint16(8443), kernelCfg.Port) + assert.Equal(t, 8443, kernelCfg.Port) }) } diff --git a/internal/backend/kernel/backend.go b/internal/backend/kernel/backend.go index 0eaa77b44..77e983cdf 100644 --- a/internal/backend/kernel/backend.go +++ b/internal/backend/kernel/backend.go @@ -210,12 +210,12 @@ func (k *KernelBackend) OpenSession(ctx context.Context) error { } } - // Connection port, after the host so the kernel validates the pair. The kernel folds - // a non-default port into the host it connects to; 0 means unset, so nothing is sent. + // Connection port, after the host. The driver passes it through as is; the kernel + // range-checks it and validates the host/port pair. 0 means unset, so nothing is sent. // A rejection here is the WithPort contract's InvalidArgument (see portRejection). if k.cfg.Port != 0 { if err := call(func() C.KernelStatusCode { - return C.kernel_session_config_set_port(cfg, C.uint16_t(k.cfg.Port)) + return C.kernel_session_config_set_port(cfg, C.int64_t(k.cfg.Port)) }); err != nil { return fmt.Errorf("kernel: set_port: %w", portRejection(k.cfg.Port, toConnError(err))) } diff --git a/internal/backend/kernel/config.go b/internal/backend/kernel/config.go index 9f1e01356..c7b2cb100 100644 --- a/internal/backend/kernel/config.go +++ b/internal/backend/kernel/config.go @@ -16,7 +16,7 @@ import ( // Zero-valued fields are simply not applied unless documented otherwise. type Config struct { Host string // workspace hostname, no scheme; passed to the kernel unchanged - Port uint16 // connection port; 0 leaves the host as given. Applied with kernel_session_config_set_port, which folds it into the host + Port int // connection port, passed to the kernel unchanged; 0 means unset. The kernel validates it (kernel_session_config_set_port) HTTPPath string // e.g. /sql/1.0/warehouses/abc123 (carries ?o= org routing) WarehouseID string // bare warehouse id; preferred over HTTPPath when set Auth Auth // PAT / OAuth M2M / OAuth U2M diff --git a/internal/backend/kernel/errors_classify.go b/internal/backend/kernel/errors_classify.go index e43db1447..33b4a76e1 100644 --- a/internal/backend/kernel/errors_classify.go +++ b/internal/backend/kernel/errors_classify.go @@ -205,18 +205,18 @@ func toStatementError(err error) error { } // kernelDefaultPort is the https default. The kernel accepts it and changes nothing. -const kernelDefaultPort uint16 = 443 +const kernelDefaultPort = 443 // portRejection applies the WithPort error contract to a kernel_session_config_set_port -// rejection. The kernel validates the port against the host already set, so an -// InvalidArgument there is the kernel's verdict on the pair. A non-default port wraps both -// ErrInvalidKernelConfig and ErrNotSupportedByKernel, so a caller can fall back to the -// default backend with errors.Is. The kernel accepts the default port without validation; +// rejection. The kernel validates the port (range and host pair) and returns InvalidArgument +// for anything it rejects, so that is the kernel's verdict on the port. A non-default port +// wraps both ErrInvalidKernelConfig and ErrNotSupportedByKernel, so a caller can fall back to +// the default backend with errors.Is. The kernel accepts the default port without validation; // were it rejected, only ErrInvalidKernelConfig is wrapped. Port 0 (unset), other codes and // non-kernel errors pass through unchanged. Host setter errors are not passed here: they // run before the port is set. The kernel's message is already redacted, so the wrapper // adds no host text. -func portRejection(port uint16, err error) error { +func portRejection(port int, err error) error { if err == nil || port == 0 { return err } diff --git a/internal/backend/kernel/errors_classify_test.go b/internal/backend/kernel/errors_classify_test.go index 50c06beed..d33b7505b 100644 --- a/internal/backend/kernel/errors_classify_test.go +++ b/internal/backend/kernel/errors_classify_test.go @@ -227,7 +227,7 @@ func TestPortRejection(t *testing.T) { invalid := &KernelError{Code: statusInvalidArgument, Message: kernelMsg} t.Run("non-default port wraps both sentinels", func(t *testing.T) { - for _, port := range []uint16{1, 8443, 65535} { + for _, port := range []int{1, 8443, 65535, 70000} { err := portRejection(port, invalid) if !errors.Is(err, dbsqlerr.ErrInvalidKernelConfig) || !errors.Is(err, dbsqlerr.ErrNotSupportedByKernel) { t.Errorf("port %d: err = %v, want both sentinels", port, err) diff --git a/internal/backend/kernel/include/databricks_kernel.h b/internal/backend/kernel/include/databricks_kernel.h index a9d9bd001..32d740333 100644 --- a/internal/backend/kernel/include/databricks_kernel.h +++ b/internal/backend/kernel/include/databricks_kernel.h @@ -246,20 +246,22 @@ KernelStatusCode kernel_session_config_set_http_path(KernelSessionConfig* config const char* http_path); /* Connection port — optional, may be set before or after the host; last call - * wins. `0` (the default) means unset. The scheme default (443 for https, 80 - * for http) is accepted and changes nothing. Any other port is folded into the + * wins. `port` is a signed 64-bit integer so callers pass their own integer + * type as is; a value outside 0..65535 returns KernelStatusCode_InvalidArgument. + * `0` (the default) means unset. The scheme default (443 for https, 80 for + * http) is accepted and changes nothing. Any other port is folded into the * host at kernel_session_open, so the kernel connects to host:port. * * The host must not carry userinfo (`user:pw@host`), a path, a query or a - * fragment, and must not be empty. A port already embedded in the host - * (`host:N` or `[v6]:N`) is kept and wins over this one; the kernel logs a - * warning when a non-default port differs from it (the scheme default never - * warns). Validation is eager: a bad combination returns - * KernelStatusCode_InvalidArgument from whichever of this call or the host - * setter came second, and leaves the config unchanged. Error text never - * includes credentials. */ + * fragment, and must be a valid host (an IPv6 address needs brackets). A + * non-default port already in the host (`host:N` or `[v6]:N`) is kept and wins + * over this one, and the kernel logs a warning when they differ; a default + * port written in the host (`host:443`) counts as none. Validation is eager: a + * bad combination returns KernelStatusCode_InvalidArgument from whichever of + * this call or the host setter came second, and leaves the config unchanged. + * Error text never repeats the host. */ KernelStatusCode kernel_session_config_set_port(KernelSessionConfig* config, - uint16_t port); + int64_t port); /* Authentication — call exactly one; the last one wins. */ KernelStatusCode kernel_session_config_set_auth_pat(KernelSessionConfig* config, diff --git a/internal/backend/kernel/port_test.go b/internal/backend/kernel/port_test.go index 219869033..c693734de 100644 --- a/internal/backend/kernel/port_test.go +++ b/internal/backend/kernel/port_test.go @@ -14,10 +14,9 @@ import ( const portTestSecret = "pSecretPw" // TestOpenSessionPortRejection checks the WithPort contract end to end through the real -// kernel. OpenSession sets the host before the port, so the host setter has no port to -// check yet. The kernel's kernel_session_config_set_port then rejects the credentialed -// host with InvalidArgument, before any connection is made. The error must wrap both -// sentinels and must not carry the credentials. +// kernel. OpenSession sets the host before the port. The kernel's kernel_session_config_set_port +// then rejects the credentialed host with InvalidArgument, before any connection is made. The +// error must wrap both sentinels and must not carry the credentials. func TestOpenSessionPortRejection(t *testing.T) { k := New(Config{ Host: "user:" + portTestSecret + "@h.databricks.com", @@ -36,3 +35,21 @@ func TestOpenSessionPortRejection(t *testing.T) { t.Errorf("error leaks credentials: %q", msg) } } + +// TestOpenSessionOutOfRangePort checks that a port the kernel's range check rejects (70000 is +// above 65535) fails at session open with both sentinels, since it is never the default port. +func TestOpenSessionOutOfRangePort(t *testing.T) { + k := New(Config{ + Host: "h.databricks.com", + Port: 70000, + WarehouseID: "wh", + Auth: Auth{Mode: AuthPAT, Token: "test-token"}, + }) + err := k.OpenSession(context.Background()) + if err == nil { + t.Fatal("OpenSession accepted port 70000; want the kernel to reject it") + } + if !errors.Is(err, dbsqlerr.ErrInvalidKernelConfig) || !errors.Is(err, dbsqlerr.ErrNotSupportedByKernel) { + t.Errorf("err = %v, want both ErrInvalidKernelConfig and ErrNotSupportedByKernel", err) + } +} diff --git a/kernel_config.go b/kernel_config.go index eaa45a5d2..a7c9eabfb 100644 --- a/kernel_config.go +++ b/kernel_config.go @@ -78,12 +78,6 @@ func validateKernelConfigContext(ctx context.Context, cfg *config.Config) (kerne return kernel.Auth{}, fmt.Errorf("databricks: a non-https protocol is %w "+ "(it connects over https); use the default (Thrift) backend", dbsqlerr.ErrNotSupportedByKernel) } - // Port: only the uint16 range is checked here. The kernel folds a non-default port into - // the host and validates the host/port pair itself (kernel_session_config_set_port), and - // its InvalidArgument reaches the caller with the same sentinels (see portRejection). - if err := validateKernelPort(cfg.Port); err != nil { - return kernel.Auth{}, err - } // Transport (WithTransport, a custom http.RoundTripper carrying a custom CA // bundle / mTLS / proxy): the kernel uses its own Rust HTTP stack below the C // ABI and never sees a Go RoundTripper, so a custom Transport would be silently @@ -153,9 +147,9 @@ func validateKernelConfigContext(ctx context.Context, cfg *config.Config) (kerne // with newKernelBackend's kernel.Config assembly. func buildKernelConfig(cfg *config.Config, kauth kernel.Auth) kernel.Config { kc := kernel.Config{ - // The host goes through unchanged; the kernel applies Port (set_port). + // Host and Port go through unchanged; the kernel validates the pair (set_port). Host: cfg.Host, - Port: uint16(cfg.Port), //nolint:gosec // G115: range-checked by validateKernelPort before this runs + Port: cfg.Port, HTTPPath: cfg.HTTPPath, WarehouseID: cfg.WarehouseID, Auth: kauth, @@ -239,19 +233,6 @@ func buildKernelConfig(cfg *config.Config, kauth kernel.Auth) kernel.Config { return kc } -// validateKernelPort checks the WithPort range the uint16 conversion needs. Everything -// else about the port (the host it is folded into, an embedded port, credentials, a -// path, an empty host) is the kernel's to validate when the session is opened. An -// out-of-range port is never the default, so the rejection wraps ErrNotSupportedByKernel -// as well as ErrInvalidKernelConfig. -func validateKernelPort(port int) error { - if port < 0 || port > 65535 { - return fmt.Errorf("databricks: WithPort %d is out of range (want 1..65535, or 0 for the default): %w: %w", - port, dbsqlerr.ErrInvalidKernelConfig, dbsqlerr.ErrNotSupportedByKernel) - } - return nil -} - func kernelTelemetryConfig(cfg *config.Config) *kernel.TelemetryConfig { var enabled *bool if val, isSet := cfg.EnableTelemetry.Get(); isSet { diff --git a/kernel_config_test.go b/kernel_config_test.go index 7ab962811..0fcaeeec7 100644 --- a/kernel_config_test.go +++ b/kernel_config_test.go @@ -444,7 +444,7 @@ var kernelConfigFieldDisposition = map[string]string{ // Rejected loudly by validateKernelConfig. "QueryTimeout": "rejected", // when > 0 (WithTimeout) "Protocol": "rejected", // kernel is https-only; non-default rejected - "Port": "forwarded", // range-checked by validateKernelPort; passed to the kernel (set_port), which folds and validates it + "Port": "forwarded", // passed to the kernel (set_port), which range-checks and validates it "Transport": "rejected", // custom RoundTripper; kernel uses its own HTTP stack, so reject rather than drop // Forwarded to the kernel's HTTP retry config via kernelRetryConfig → @@ -972,42 +972,34 @@ func TestKernelRetryConfig(t *testing.T) { }) } -// TestKernelPortPassThrough checks that the host reaches the kernel unchanged and the port -// reaches the kernel config. The kernel folds a non-default port into the host and validates -// the pair, so the driver adds no folding and no host validation. Credentials, paths and -// bad embedded ports are the kernel's to reject at session open (see TestOpenSessionPortRejection). +// TestKernelPortPassThrough checks that the host and port reach kernel.Config unchanged. The +// driver neither folds the port nor validates the pair or the range; the kernel does that at +// session open (see TestOpenSessionPortRejection and the tagged port_test.go). func TestKernelPortPassThrough(t *testing.T) { - hosts := []string{ - "h.databricks.com", - "h.databricks.com/", - "h.databricks.com:8443", - "127.0.0.1", - "::1", - "[::1]", - "h.databricks.com/x", - "user:pw@h", - "", + cases := []struct { + host string + port int + }{ + {"h.databricks.com", 0}, + {"h.databricks.com", 443}, + {"h.databricks.com:8443", 8443}, + {"::1", 8443}, + {"h.databricks.com", 70000}, } - ports := []int{0, 443, 8443, 65535} - for _, host := range hosts { - for _, port := range ports { - t.Run(fmt.Sprintf("host %q port %d", host, port), func(t *testing.T) { - c := baseKernelConfig() - c.Host = host - c.Port = port - kauth, err := validateKernelConfig(c) - if err != nil { - t.Fatalf("validateKernelConfig: %v", err) - } - kc := buildKernelConfig(c, kauth) - if kc.Host != host { - t.Errorf("kernel Host = %q, want the host unchanged", kc.Host) - } - if int(kc.Port) != port { - t.Errorf("kernel Port = %d, want %d", kc.Port, port) - } - }) - } + for _, tc := range cases { + t.Run(fmt.Sprintf("host %q port %d", tc.host, tc.port), func(t *testing.T) { + c := baseKernelConfig() + c.Host = tc.host + c.Port = tc.port + kauth, err := validateKernelConfig(c) + if err != nil { + t.Fatalf("validateKernelConfig: %v", err) + } + kc := buildKernelConfig(c, kauth) + if kc.Host != tc.host || kc.Port != tc.port { + t.Errorf("kernel Host=%q Port=%d, want %q and %d", kc.Host, kc.Port, tc.host, tc.port) + } + }) } } @@ -1043,38 +1035,14 @@ func TestKernelPortFromOptions(t *testing.T) { }) } -// TestKernelPortRange checks the driver's only port check, the uint16 range. Both bounds of the -// rejection wrap ErrInvalidKernelConfig and ErrNotSupportedByKernel, since an out-of-range port is -// never the default. -func TestKernelPortRange(t *testing.T) { - for _, port := range []int{-1, 65536} { - c := baseKernelConfig() - c.Port = port - _, err := validateKernelConfig(c) - if !errors.Is(err, dbsqlerr.ErrInvalidKernelConfig) { - t.Errorf("WithPort(%d): err = %v, want ErrInvalidKernelConfig", port, err) - } - if !errors.Is(err, dbsqlerr.ErrNotSupportedByKernel) { - t.Errorf("WithPort(%d): err = %v, want ErrNotSupportedByKernel", port, err) - } - } - for _, port := range []int{0, 1, 443, 65535} { - c := baseKernelConfig() - c.Port = port - if _, err := validateKernelConfig(c); err != nil { - t.Errorf("WithPort(%d): unexpected err %v", port, err) - } - } -} - // TestKernelDSNHostAndPort checks that a DSN IPv6 host reaches the kernel as the bare address with -// the port alongside it. ParseDSN strips the brackets (url.Hostname); the kernel folds the port. +// the port alongside it. ParseDSN strips the brackets (url.Hostname); the kernel validates the pair. func TestKernelDSNHostAndPort(t *testing.T) { cases := []struct { name string dsn string wantHost string - wantPort uint16 + wantPort int }{ {"bracketed IPv6 with custom port", "token:x@[::1]:8443/sql/1.0/warehouses/abc", "::1", 8443}, {"bracketed IPv6 with default port", "token:x@[::1]:443/sql/1.0/warehouses/abc", "::1", 443}, diff --git a/kernel_proxy.go b/kernel_proxy.go index 0d0d1b229..4f3df18f0 100644 --- a/kernel_proxy.go +++ b/kernel_proxy.go @@ -2,11 +2,8 @@ package dbsql import ( "fmt" - "net" "net/http" "net/url" - "strconv" - "strings" "github.com/databricks/databricks-sql-go/v2/internal/config" ) @@ -27,25 +24,6 @@ func proxyForEndpoint(cfg *config.Config) string { return proxyForEndpointFunc(cfg, http.ProxyFromEnvironment) } -// kernelEndpointHost is the host:port the kernel dials, used only to pick the proxy -// (HTTPS_PROXY / NO_PROXY). It applies the kernel's simple port rule without the -// kernel's validation: a port of 0 or 443 leaves the host as given; a host that already -// carries a port keeps it (an embedded port wins over WithPort, as in the kernel); any -// other port is appended, bracketing an IPv6 literal. A trailing "/" is trimmed. A -// malformed host is passed through, since the kernel rejects it at session open. It -// returns no error and never echoes the host, so it cannot leak credentials. -func kernelEndpointHost(host string, port int) string { - host = strings.TrimRight(host, "/") - if port == 0 || port == 443 { - return host - } - if _, _, err := net.SplitHostPort(host); err == nil { - return host - } - bare := strings.TrimSuffix(strings.TrimPrefix(host, "["), "]") - return net.JoinHostPort(bare, strconv.Itoa(port)) -} - // proxyForEndpointFunc is the testable core: it builds the endpoint request and // asks resolve for the proxy, returning "" (direct) on any error, no proxy, or an // unbuildable endpoint. resolve is http.ProxyFromEnvironment in production; tests @@ -65,7 +43,10 @@ func proxyForEndpointFunc(cfg *config.Config, resolve func(*http.Request) (*url. if scheme == "" { scheme = "https" } - endpoint := fmt.Sprintf("%s://%s", scheme, kernelEndpointHost(cfg.Host, cfg.Port)) + endpoint := fmt.Sprintf("%s://%s", scheme, cfg.Host) + if cfg.Port != 0 { + endpoint = fmt.Sprintf("%s://%s:%d", scheme, cfg.Host, cfg.Port) + } req, err := http.NewRequest(http.MethodPost, endpoint, nil) if err != nil { return "" diff --git a/kernel_proxy_test.go b/kernel_proxy_test.go index 0536cfb95..f857ebad6 100644 --- a/kernel_proxy_test.go +++ b/kernel_proxy_test.go @@ -55,37 +55,6 @@ func TestProxyForEndpoint(t *testing.T) { resolve: func(*http.Request) (*url.URL, error) { return proxyURL, nil }, want: "http://corp-proxy:3128", }, - { - name: "embedded port equal to Port is not doubled", - cfg: func() *config.Config { - c := config.WithDefaults() - c.Host = "my-workspace.databricks.com:8443" - c.Port = 8443 - c.HTTPPath = "/sql/1.0/warehouses/abc" - return c - }(), - resolve: func(*http.Request) (*url.URL, error) { return proxyURL, nil }, - want: "http://corp-proxy:3128", - }, - { - // A bracketed IPv6 literal with a port is folded into the endpoint as [addr]:port, - // the same way the kernel Host is built. - name: "bracketed IPv6 literal with Port is folded", - cfg: func() *config.Config { - c := config.WithDefaults() - c.Host = "[::1]" - c.Port = 8443 - c.HTTPPath = "/sql/1.0/warehouses/abc" - return c - }(), - resolve: func(req *http.Request) (*url.URL, error) { - if req.URL.Host != "[::1]:8443" { - t.Errorf("endpoint host = %q, want %q", req.URL.Host, "[::1]:8443") - } - return proxyURL, nil - }, - want: "http://corp-proxy:3128", - }, { name: "host excluded by NO_PROXY -> direct", cfg: validCfg(), @@ -111,43 +80,6 @@ func TestProxyForEndpoint(t *testing.T) { }, want: "", }, - { - // A bare IPv6 literal is bracketed before the port is folded, so the endpoint is [::1]:8443. - name: "bare IPv6 host with Port folds to a bracketed endpoint", - cfg: func() *config.Config { - c := config.WithDefaults() - c.Host = "::1" - c.Port = 8443 - c.HTTPPath = "/sql/1.0/warehouses/abc" - return c - }(), - resolve: func(req *http.Request) (*url.URL, error) { - if req.URL.Host != "[::1]:8443" { - t.Errorf("endpoint host = %q, want %q", req.URL.Host, "[::1]:8443") - } - return proxyURL, nil - }, - want: "http://corp-proxy:3128", - }, - { - // A trailing "/" (WithServerHostname("https://h/")) is trimmed before the port is - // folded, so the endpoint is h:8443, not h/:8443. - name: "trailing slash host with Port folds to host:port", - cfg: func() *config.Config { - c := config.WithDefaults() - c.Host = "my-workspace.databricks.com/" - c.Port = 8443 - c.HTTPPath = "/sql/1.0/warehouses/abc" - return c - }(), - resolve: func(req *http.Request) (*url.URL, error) { - if req.URL.Host != "my-workspace.databricks.com:8443" { - t.Errorf("endpoint host = %q, want %q", req.URL.Host, "my-workspace.databricks.com:8443") - } - return proxyURL, nil - }, - want: "http://corp-proxy:3128", - }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { From 9a6305005bef02e0bf30e3af19e75a4b85107048 Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:26:39 +0000 Subject: [PATCH 16/17] chore(kernel): pin KERNEL_REV to the merged kernel port change databricks-sql-kernel#505 merged as 3b691d2; pin that commit instead of the PR head, and copy its C header (it adds kernel main's kernel_statement_add_parameter_set declaration and comment updates). Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac --- KERNEL_REV | 2 +- .../kernel/include/databricks_kernel.h | 31 +++++++++++++------ 2 files changed, 23 insertions(+), 10 deletions(-) diff --git a/KERNEL_REV b/KERNEL_REV index 4e5ff54b6..101d21c5a 100644 --- a/KERNEL_REV +++ b/KERNEL_REV @@ -1 +1 @@ -7e76a603fd4e3ce74e90e6c578e86bc75ac025eb +3b691d2a2c235ef847d61b308c31604979830994 diff --git a/internal/backend/kernel/include/databricks_kernel.h b/internal/backend/kernel/include/databricks_kernel.h index 32d740333..c73dbfbd2 100644 --- a/internal/backend/kernel/include/databricks_kernel.h +++ b/internal/backend/kernel/include/databricks_kernel.h @@ -422,7 +422,8 @@ KernelStatusCode kernel_init_logging(const char* level, const char* file_path); * that kernel operation. Hosts that need asynchronous logging can copy the * record into their own bounded queue and return. Strings are valid only during * the callback. Calls may be concurrent; copy retained strings and synchronize - * the destination. `user_data` is the pointer supplied at initialization. */ + * the destination. `user_data` is the pointer supplied at initialization. + * Kernel threads run with SIGPIPE blocked; callbacks must not unblock it. */ typedef void (*KernelLogCallback)(const char* level, const char* target, const char* message, void* user_data); @@ -702,13 +703,25 @@ KernelStatusCode kernel_session_rollback(kernel_session_t* session); /* ─── Statement ───────────────────────────────────────────────────────*/ /* Set the statement's SQL text, replacing any previously set SQL. Also clears - * every previously-bound parameter (raw and the typed positional binders below), + * every previously-bound parameter (raw, typed, and native parameter sets), * so a reused statement handle starts each query with a fresh parameter set. */ KernelStatusCode kernel_statement_set_sql(kernel_statement_t* stmt, const char* sql); +/* Snapshot current scalar bindings as the next ordered native parameter set, + * then clear the scalar bindings. Repeat bind + add_parameter_set for each set, + * then use kernel_statement_execute to submit the entire batch in one request. + * The caller selects eligible SQL; the server validates the parameter sets. + * Scalar bindings and batch sets cannot be submitted together. + * kernel_statement_set_sql clears all snapshots. Execute retains them. + * num_modified_rows reports the aggregate affected count, or -1 if unavailable. + * + * Errors reading the batch's affected-row count are non-retryable because + * the rows may already be committed. */ +KernelStatusCode kernel_statement_add_parameter_set(kernel_statement_t* stmt); + /* Typed positional parameter binding (1-based ordinal); the kernel infers the * SEA wire type from the C type. These are the "typed params" the - * kernel_statement_bind_parameter contract refers to: within one statement they + * kernel_statement_bind_parameter contract refers to: within one parameter set they * cannot be combined with kernel_statement_bind_parameter (raw binds) — pick one * binding style. The conflict is reported at kernel_statement_execute, not here. */ KernelStatusCode kernel_statement_bind_null(kernel_statement_t* stmt, size_t ordinal); @@ -728,14 +741,14 @@ KernelStatusCode kernel_statement_bind_string(kernel_statement_t* stmt, size_t o * non-empty (an empty type is rejected here with InvalidArgument). * * Lifecycle: raw binds ACCUMULATE (each call appends a marker in push order); - * they carry no ordinal to overwrite by. kernel_statement_set_sql is the sole - * reset point — it clears ALL prior binds (raw AND the typed positional binders - * below) so each set_sql begins a fresh parameter set. kernel_statement_execute - * does NOT clear them, so a host reusing one statement handle across queries must - * call set_sql before re-binding, or the prior query's markers persist and the + * they carry no ordinal to overwrite by. kernel_statement_add_parameter_set + * snapshots and clears current binds. kernel_statement_set_sql clears ALL + * scalar binds and parameter sets. kernel_statement_execute does NOT clear + * them, so a host reusing one statement handle across queries must call + * set_sql before re-binding, or the prior query's markers persist and the * server sees the wrong parameter count. * - * Two mutual-exclusion rules hold within one statement, both enforced at + * Two mutual-exclusion rules hold within each scalar parameter set, enforced at * kernel_statement_execute (this call always returns Success on a valid * arg — the conflict surfaces later as InvalidArgument from execute): * - positional and named raw params cannot be mixed; From 1e46843220026dc92962ae0c82f9a9ada405043c Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:53:53 +0000 Subject: [PATCH 17/17] fix(kernel): resolve the proxy for a host that has its own port proxyForEndpointFunc appended cfg.Port to a host that already had a port, building an unparsable `h:8443:443` URL, so HTTPS_PROXY and NO_PROXY were silently skipped. Keep the host's own port, as the kernel does. Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac --- kernel_proxy.go | 15 +++++++++++---- kernel_proxy_test.go | 16 ++++++++++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/kernel_proxy.go b/kernel_proxy.go index 4f3df18f0..8ce0e0703 100644 --- a/kernel_proxy.go +++ b/kernel_proxy.go @@ -2,8 +2,10 @@ package dbsql import ( "fmt" + "net" "net/http" "net/url" + "strconv" "github.com/databricks/databricks-sql-go/v2/internal/config" ) @@ -43,11 +45,16 @@ func proxyForEndpointFunc(cfg *config.Config, resolve func(*http.Request) (*url. if scheme == "" { scheme = "https" } - endpoint := fmt.Sprintf("%s://%s", scheme, cfg.Host) - if cfg.Port != 0 { - endpoint = fmt.Sprintf("%s://%s:%d", scheme, cfg.Host, cfg.Port) + endpoint, err := url.Parse(fmt.Sprintf("%s://%s", scheme, cfg.Host)) + if err != nil { + return "" + } + // A port already in the host wins, as in the kernel; appending cfg.Port too + // would build an unparsable `h:8443:443` and silently skip the proxy. + if endpoint.Port() == "" && cfg.Port != 0 { + endpoint.Host = net.JoinHostPort(endpoint.Hostname(), strconv.Itoa(cfg.Port)) } - req, err := http.NewRequest(http.MethodPost, endpoint, nil) + req, err := http.NewRequest(http.MethodPost, endpoint.String(), nil) if err != nil { return "" } diff --git a/kernel_proxy_test.go b/kernel_proxy_test.go index f857ebad6..8b7eceb32 100644 --- a/kernel_proxy_test.go +++ b/kernel_proxy_test.go @@ -55,6 +55,22 @@ func TestProxyForEndpoint(t *testing.T) { resolve: func(*http.Request) (*url.URL, error) { return proxyURL, nil }, want: "http://corp-proxy:3128", }, + { + // A port in the host wins over cfg.Port, so the endpoint stays parsable. + name: "host with its own port still resolves proxy", + cfg: func() *config.Config { + c := validCfg() + c.Host = "my-workspace.databricks.com:8443" + return c + }(), + resolve: func(r *http.Request) (*url.URL, error) { + if r.URL.Host != "my-workspace.databricks.com:8443" { + t.Errorf("endpoint host = %q, want the host's own port", r.URL.Host) + } + return proxyURL, nil + }, + want: "http://corp-proxy:3128", + }, { name: "host excluded by NO_PROXY -> direct", cfg: validCfg(),