diff --git a/CHANGELOG.md b/CHANGELOG.md index cf77ad1e..a3697c56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +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. IPv6 hosts need brackets, and a port the kernel rejects returns an error wrapping both `ErrInvalidKernelConfig` and `ErrNotSupportedByKernel`. - Render Thrift ARRAY, MAP and STRUCT values in linear time (databricks/databricks-sql-go#596). - **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). - **Behavior change:** Without direct results, `ArrowIPCStreamIterator.SchemaBytes()` and `ArrowBatchIterator.Schema()` now retrieve result metadata without fetching data and return the result schema, including for empty results, and can return request or schema-conversion errors. Schemas inferred from Thrift metadata may differ from CloudFetch file schemas when server ArrowSchema is absent (databricks/databricks-sql-go#312). diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 6aa25e15..d60cea0a 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 | 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 445092d2..101d21c5 100644 --- a/KERNEL_REV +++ b/KERNEL_REV @@ -1 +1 @@ -c8113e4f1e55dabb9125d4272721fa11b2d6f32d +3b691d2a2c235ef847d61b308c31604979830994 diff --git a/README.md b/README.md index 525b597d..0de0c28f 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` | Thrift only | `443` | Kernel connects on **443 only** and rejects any other port. | +| *(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 0c6fd8ca..151dcb26 100644 --- a/connector_reyden_test.go +++ b/connector_reyden_test.go @@ -216,6 +216,30 @@ 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 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) { + kernelCfg = buildKernelConfig(cfg, kernel.Auth{Mode: kernel.AuthPAT, Token: "test-token"}) + return &fakeKernelBackend{}, nil + }, + ) + WithPort(8443)(conn.cfg) + + _, _, err := conn.openSessionWithReydenFallback(context.Background()) + require.NoError(t, err) + // 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, 8443, kernelCfg.Port) + }) } func TestReydenPreCheck(t *testing.T) { diff --git a/internal/backend/kernel/backend.go b/internal/backend/kernel/backend.go index de8fe0b7..47bb2800 100644 --- a/internal/backend/kernel/backend.go +++ b/internal/backend/kernel/backend.go @@ -211,6 +211,17 @@ func (k *KernelBackend) OpenSession(ctx context.Context) error { } } + // 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.int64_t(k.cfg.Port)) + }); err != nil { + return fmt.Errorf("kernel: set_port: %w", portRejection(k.cfg.Port, toConnError(err))) + } + } + if err := k.setAuth(cfg); err != nil { return err } diff --git a/internal/backend/kernel/config.go b/internal/backend/kernel/config.go index c3f97ed8..c7b2cb10 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 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 54399043..8eb605ba 100644 --- a/internal/backend/kernel/errors_classify.go +++ b/internal/backend/kernel/errors_classify.go @@ -5,6 +5,7 @@ import ( "fmt" "strings" + dbsqlerr "github.com/databricks/databricks-sql-go/v2/errors" dbsqlerrint "github.com/databricks/databricks-sql-go/v2/internal/errors" ) @@ -203,3 +204,29 @@ func toStatementError(err error) error { } return err } + +// kernelDefaultPort is the https default. The kernel accepts it and changes nothing. +const kernelDefaultPort = 443 + +// portRejection applies the WithPort error contract to a kernel_session_config_set_port +// 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 int, 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 358a619d..3c132dff 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/v2/errors" dbsqlerrint "github.com/databricks/databricks-sql-go/v2/internal/errors" ) @@ -297,6 +298,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 []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) + } + 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 e167f181..c73dbfbd 100644 --- a/internal/backend/kernel/include/databricks_kernel.h +++ b/internal/backend/kernel/include/databricks_kernel.h @@ -245,6 +245,24 @@ 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. `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 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, + int64_t port); + /* Authentication — call exactly one; the last one wins. */ KernelStatusCode kernel_session_config_set_auth_pat(KernelSessionConfig* config, const char* token); @@ -404,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); @@ -684,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); @@ -710,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; diff --git a/internal/backend/kernel/port_test.go b/internal/backend/kernel/port_test.go new file mode 100644 index 00000000..c693734d --- /dev/null +++ b/internal/backend/kernel/port_test.go @@ -0,0 +1,55 @@ +//go:build cgo && databricks_kernel + +package kernel + +import ( + "context" + "errors" + "strings" + "testing" + + dbsqlerr "github.com/databricks/databricks-sql-go/v2/errors" +) + +const portTestSecret = "pSecretPw" + +// TestOpenSessionPortRejection checks the WithPort contract end to end through the real +// 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", + 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) + } +} + +// 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/internal/config/thrift_endpoint_test.go b/internal/config/thrift_endpoint_test.go new file mode 100644 index 00000000..efdcf13b --- /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 fcd99cdf..a7c9eabf 100644 --- a/kernel_config.go +++ b/kernel_config.go @@ -73,19 +73,11 @@ 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) - } // 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 @@ -155,7 +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{ + // Host and Port go through unchanged; the kernel validates the pair (set_port). Host: cfg.Host, + Port: cfg.Port, HTTPPath: cfg.HTTPPath, WarehouseID: cfg.WarehouseID, Auth: kauth, diff --git a/kernel_config_test.go b/kernel_config_test.go index d9092926..0fcaeeec 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,10 @@ 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", // 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 → // set_retry_config (WithRetries: backoff bounds + max attempts, incl. disable). @@ -972,3 +971,105 @@ func TestKernelRetryConfig(t *testing.T) { } }) } + +// 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) { + 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}, + } + 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) + } + }) + } +} + +// 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) + kauth, err := validateKernelConfig(c) + if err != nil { + t.Fatalf("unexpected err %v", err) + } + 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("embedded port with WithPort(443) is passed through for the kernel to resolve", 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) + } + 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) + } + }) +} + +// 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 validates the pair. +func TestKernelDSNHostAndPort(t *testing.T) { + cases := []struct { + name string + dsn string + wantHost string + 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}, + {"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) + } + 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) + } + }) + } +} diff --git a/kernel_proxy.go b/kernel_proxy.go index 4f3df18f..8ce0e070 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 f857ebad..8b7eceb3 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(),