diff --git a/CHANGELOG.md b/CHANGELOG.md index 41c5e722..e53adf99 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,8 @@ - Evict kernel connections when SEA reports a missing or invalid session, and reject later requests locally without replaying the failed statement. - Reduce Thrift row-scan CPU by binding scalar readers and null/type handling once per Arrow record (databricks/databricks-sql-go#602). - **Behavior change:** Closed Thrift Arrow row scanners return an explicit error without logging an ERROR instead of stale values; a destination whose column count differs from the Arrow holders now errors instead of filling leading columns or NULL-padding missing columns. Column-value setup failures now stop scanning and are retained for subsequent scans instead of only being logged and ignored (databricks/databricks-sql-go#602). +- Support SOCKS proxies on the kernel backend; see [Proxy](CONNECTION_PARAMETERS.md#proxy). +- **Behavior change:** On the kernel backend, `NO_PROXY` now also applies to CloudFetch storage and OAuth hosts, with the differences from the Thrift path listed in [Proxy](CONNECTION_PARAMETERS.md#proxy). ## v2.0.0 (2026-11-23) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 1dd9bb15..8b31a592 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -214,14 +214,40 @@ used for: ## Proxy Both backends honor the standard `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY` environment -variables. Note the kernel path accepts **http(s) proxies only**: a `socks*` proxy URL -(honored on the Thrift path) is rejected at connect on the kernel path. Kernel SOCKS -support is tracked in PECOBLR-4152. +variables, including `socks5://` and `socks5h://` proxy URLs. Credentials go in the URL userinfo +(`socks5h://user:pass@proxy:1080`, RFC 1929 for SOCKS5). + +For a SOCKS `HTTPS_PROXY`, the kernel path keeps the Thrift path's behavior: + +- `socks5://` is sent to the kernel as `socks5h://`, so the proxy resolves the + warehouse and CloudFetch host names, as on the Thrift path. +- `socks5h://` resolves at the proxy on both paths. +- `socks4://` and `socks4a://` fail at connect with `ErrInvalidKernelConfig` when the + warehouse uses the proxy. The Thrift path cannot use them either. When `NO_PROXY` + bypasses the warehouse, the URL is passed to the kernel as is, so the connection works + if no host needs the proxy; hosts that do, such as CloudFetch storage, go through the + SOCKS4 proxy, where the Thrift path would fail. + +On the kernel path, the driver passes one proxy for every host (warehouse, CloudFetch +storage and OAuth) together with `NO_PROXY` as the kernel's bypass list. It is the +warehouse's proxy, or `HTTPS_PROXY` when the warehouse connects directly (for example +through `NO_PROXY`). As on the Thrift path, these variables are read once per process. The +warehouse always follows Go's `NO_PROXY` rules exactly. For other hosts, two things +differ from the Thrift path: + +- A `host:port` entry applies only with port 443 (CloudFetch storage and OAuth use 443); + entries for other ports are dropped, so those hosts stay proxied. +- `.example.com` and `*.example.com` also bypass `example.com` itself. + +`ALL_PROXY` differs between the paths. Thrift ignores it. On the kernel path, when the +warehouse connects directly and no `HTTPS_PROXY` is set, the driver passes no proxy and the +kernel reads `HTTPS_PROXY` / `ALL_PROXY` / `NO_PROXY` itself. A `socks5://` `ALL_PROXY` +therefore resolves host names locally, and `socks4://` / `socks4a://` are accepted. | Connector option | Thrift | Kernel | Notes | |---|:---:|:---:|---| -| *(environment)* | ✅ | ✅ | `HTTP(S)_PROXY` / `NO_PROXY`. | -| `WithKernelProxy(KernelProxy{URL, Username, Password, BypassHosts})` | ❌ | ✅ | Explicit proxy with out-of-band basic-auth credentials and a structured bypass list — the "advanced" fields the env-var path can't express. Overrides the environment proxy; a malformed URL is rejected at connect. | +| *(environment)* | ✅ | ✅ | `HTTP(S)_PROXY` / `NO_PROXY`; `ALL_PROXY` on the kernel path only. | +| `WithKernelProxy(KernelProxy{URL, Username, Password, BypassHosts})` | ❌ | ✅ | Explicit proxy with out-of-band credentials (basic auth, or RFC 1929 for SOCKS5) and a structured bypass list — the "advanced" fields the env-var path can't express. Overrides the environment proxy; a malformed URL is rejected at connect. The URL is passed to the kernel verbatim: `http`, `https`, `socks4`, `socks4a`, `socks5` and `socks5h` are accepted, and `socks4` / `socks5` resolve host names locally while `socks4a` / `socks5h` resolve them at the proxy. | ## Telemetry diff --git a/KERNEL_REV b/KERNEL_REV index 101d21c5..418c81d3 100644 --- a/KERNEL_REV +++ b/KERNEL_REV @@ -1 +1 @@ -3b691d2a2c235ef847d61b308c31604979830994 +a29235cbea9532efa5572ebff010045583a19cbe diff --git a/connector.go b/connector.go index 6828d9f5..3a4a50a8 100644 --- a/connector.go +++ b/connector.go @@ -779,28 +779,33 @@ func WithKernelSkipHostnameVerify() ConnOption { // misplaced BypassHosts) compile cleanly and fail only at runtime with wrong proxy // credentials. type KernelProxy struct { - // URL is the proxy URL (e.g. "http://proxy.internal:3128"). Required; empty is a - // no-op, leaving the environment-derived proxy (if any) in effect. + // URL is the proxy URL (e.g. "http://proxy.internal:3128" or + // "socks5h://proxy.internal:1080"). Required; empty is a no-op, leaving the + // environment-derived proxy (if any) in effect. It is passed to the kernel + // verbatim: http, https, socks4, socks4a, socks5 and socks5h are accepted; + // socks4/socks5 resolve the target host locally and socks4a/socks5h at the proxy. URL string - // Username / Password are optional out-of-band basic-auth credentials, supplied - // here rather than embedded in the URL userinfo. Empty means unset. + // Username / Password are optional out-of-band proxy credentials (basic auth for + // an HTTP proxy, RFC 1929 for SOCKS5), supplied here rather than embedded in the + // URL userinfo. Empty means unset. Username string Password string - // BypassHosts is an optional comma-separated no-proxy host list. NO_PROXY is - // consumed during environment resolution and not forwarded to the kernel, so this - // is the only way to give the kernel a structured bypass list. Empty means unset. + // BypassHosts is an optional comma-separated no-proxy host list, passed to the + // kernel verbatim. It replaces the environment path's bypass list, which the driver + // translates from NO_PROXY. Empty means unset. BypassHosts string } -// WithKernelProxy configures an explicit HTTP proxy for the kernel backend, with -// optional out-of-band basic-auth credentials and a comma-separated bypass -// (no-proxy) host list. It overrides the HTTP(S)_PROXY / NO_PROXY environment the -// kernel path otherwise mirrors from the Thrift path. +// WithKernelProxy configures an explicit HTTP or SOCKS proxy for the kernel backend, with +// optional out-of-band credentials (basic auth for an HTTP proxy, RFC 1929 for SOCKS5) +// and a comma-separated bypass (no-proxy) host list. It overrides the HTTP(S)_PROXY / +// NO_PROXY environment the kernel path otherwise mirrors from the Thrift path. // -// Use this instead of the proxy environment when you need the "advanced" fields -// the env-var path can't express: a structured bypass list (NO_PROXY is consumed -// during environment resolution, not forwarded to the kernel) or basic-auth -// credentials supplied out of band rather than embedded in the URL userinfo. +// Use this instead of the proxy environment when you need what the env-var path +// can't express: a bypass list in the kernel's own matching rules, passed verbatim +// (the env path translates NO_PROXY into that list, approximating Go's rules for +// hosts other than the warehouse), or credentials supplied out of band rather than +// embedded in the URL userinfo. // KernelProxy.Username / Password / BypassHosts may be empty (passed to the kernel // as NULL, i.e. unset). An empty KernelProxy.URL is a no-op — the environment-derived // proxy, if any, stays in effect. A malformed URL is rejected at connect diff --git a/internal/backend/kernel/backend.go b/internal/backend/kernel/backend.go index 47bb2800..13b6c4f1 100644 --- a/internal/backend/kernel/backend.go +++ b/internal/backend/kernel/backend.go @@ -418,14 +418,14 @@ func (k *KernelBackend) applyKernelTLS(cfg *C.KernelSessionConfig) error { return nil } -// applyProxy forwards the HTTP proxy config to the session config. The URL is set -// when either the environment configured one for this endpoint or the caller -// supplied one via WithKernelProxy (resolveKernelProxy decides which). The -// optional basic-auth credentials and bypass list ride along; each is NULL when -// empty (the env path folds credentials into the URL and consumes NO_PROXY during -// resolution, so it leaves them empty — Go's proxy-env convention). A no-op when -// ProxyURL is empty (direct connection). The kernel applies the URL as an explicit -// override of its own env-var behavior. +// applyProxy forwards the HTTP or SOCKS proxy config to the session config. The URL +// is set when either the environment configured one or the caller supplied one via +// WithKernelProxy (resolveKernelProxy decides which). The optional credentials and +// bypass list ride along; each is NULL when empty. The env path keeps credentials +// in the URL userinfo and sets the bypass list from NO_PROXY, translated to the +// kernel's matching rules. A no-op when ProxyURL is empty, which leaves proxy +// selection to the kernel's own env-var handling. The kernel applies the URL as an +// explicit override of that env-var behavior. func (k *KernelBackend) applyProxy(cfg *C.KernelSessionConfig) error { if k.cfg.ProxyURL == "" { return nil diff --git a/internal/backend/kernel/config.go b/internal/backend/kernel/config.go index c7b2cb10..a84779c3 100644 --- a/internal/backend/kernel/config.go +++ b/internal/backend/kernel/config.go @@ -65,17 +65,18 @@ type Config struct { TLSClientKeyPEM []byte TLSSkipHostnameVerify bool - // ProxyURL configures an HTTP proxy. It is either resolved for this endpoint - // from the same HTTP(S)_PROXY / NO_PROXY environment the Thrift path uses - // (NO_PROXY applied during resolution), or set explicitly via WithKernelProxy. - // Empty leaves the kernel on a direct connection. + // ProxyURL configures an HTTP or SOCKS proxy for every kernel destination. It + // is either resolved from the same HTTP(S)_PROXY / NO_PROXY environment the + // Thrift path uses, or set explicitly via WithKernelProxy. Empty leaves proxy + // selection to the kernel's own environment handling. // - // ProxyUsername / ProxyPassword are out-of-band basic-auth credentials (an - // alternative to embedding them in ProxyURL's userinfo). ProxyBypassHosts is - // a comma-separated no-proxy list honored kernel-side. All three are only - // meaningful with an explicit WithKernelProxy — the env-var path folds - // credentials into the URL and consumes NO_PROXY during resolution, so it - // leaves these empty. Empty fields are passed as NULL (kernel default). + // ProxyUsername / ProxyPassword are out-of-band proxy credentials (an + // alternative to embedding them in ProxyURL's userinfo); only WithKernelProxy + // sets them, since the env-var path keeps credentials in the URL. + // ProxyBypassHosts is a comma-separated no-proxy list honored kernel-side: + // WithKernelProxy's list, or on the env-var path NO_PROXY translated to the + // kernel's matching rules (plus loopback, and the warehouse when NO_PROXY + // bypasses it). Empty fields are passed as NULL (kernel default). ProxyURL string ProxyUsername string ProxyPassword string diff --git a/internal/backend/kernel/include/databricks_kernel.h b/internal/backend/kernel/include/databricks_kernel.h index c73dbfbd..effd6057 100644 --- a/internal/backend/kernel/include/databricks_kernel.h +++ b/internal/backend/kernel/include/databricks_kernel.h @@ -453,9 +453,10 @@ KernelStatusCode kernel_init_logging_callback(const char* level, * override. */ -/* Route traffic through an HTTP/HTTPS proxy. `url` is required (e.g. - * "http://proxy.corp:8080"); `username` / `password` / `bypass_hosts` - * (comma-separated) are optional — pass NULL to omit. */ +/* Route traffic through an HTTP/HTTPS or SOCKS proxy. `url` is required + * (e.g. "http://proxy.corp:8080" or "socks5h://proxy.corp:1080"; schemes + * http, https, socks4, socks4a, socks5, socks5h); `username` / `password` / + * `bypass_hosts` (comma-separated) are optional — pass NULL to omit. */ KernelStatusCode kernel_session_config_set_proxy(KernelSessionConfig* config, const char* url, const char* username, const char* password, const char* bypass_hosts); @@ -487,6 +488,32 @@ KernelStatusCode kernel_session_config_set_tls_client_certificate( KernelSessionConfig* config, const uint8_t* cert_pem, size_t cert_len, const uint8_t* key_pem, size_t key_len); +/* Enable or disable TLS certificate-revocation checking (default: off). + * + * Supported only on Windows with the tls-rustls backend, where Windows CryptoAPI + * checks the revocation of the chain it builds for the server certificate, after + * webpki has verified the chain. A revoked certificate is always rejected. + * `accept_undetermined` governs a status that cannot be determined (a fetch + * failure or timeout, an offline status, a partial chain): false rejects it + * (strict), true accepts it. `check_revocation` false disables the check whatever + * `accept_undetermined` says. Revocation is also skipped when the self-signed + * setter is set. + * + * CRL and OCSP retrieval uses Windows networking and proxy settings, not the + * kernel's proxy configuration, and Windows caches the results. The check is + * synchronous: it blocks the calling thread's TLS handshake until CryptoAPI + * returns, so a connect or operation timeout can be exceeded by up to the + * revocation budget (about 10 s for CRL and OCSP retrieval in total, shared by a + * handshake's one or two chain builds; AIA and other chain-building fetches are + * bounded per URL, not in total). Session + * resumption is disabled while checking is on. + * + * Requesting it on any other platform, or on tls-native, makes opening a session + * fail with InvalidArgument, and the error names the unsupported platform or + * backend. So does requesting it for a host that is not https. */ +KernelStatusCode kernel_session_config_set_tls_certificate_revocation( + KernelSessionConfig* config, bool check_revocation, bool accept_undetermined); + /* Configure the HTTP retry / backoff policy. `min_wait_ms` / `max_wait_ms` * are the backoff-wait bounds between attempts (the wait is exponential * with jitter, clamped to this range); `max_retries` is the number of diff --git a/kernel_backend.go b/kernel_backend.go index c6ccc43f..0108acf8 100644 --- a/kernel_backend.go +++ b/kernel_backend.go @@ -37,7 +37,9 @@ func newKernelBackend(ctx context.Context, cfg *config.Config) (backend.Backend, // HTTP(S)_PROXY / NO_PROXY environment for the kernel. resolveKernelProxy is // pure Go (untagged, in kernel_config.go) with its own unit coverage, so it // (and proxyForEndpoint) resolve here rather than in buildKernelConfig. - resolveKernelProxy(cfg, &kc) + if err := resolveKernelProxy(cfg, &kc); err != nil { + return nil, err + } return kernel.New(kc), nil } diff --git a/kernel_config.go b/kernel_config.go index a7c9eabf..2e2b08d7 100644 --- a/kernel_config.go +++ b/kernel_config.go @@ -371,21 +371,29 @@ func kernelRetryConfig(cfg *config.Config) *kernel.RetryConfig { // resolveKernelProxy fills the kernel Config's proxy fields. An explicit // WithKernelProxy (KernelExperimental.ProxyURL non-empty) wins verbatim, // including its out-of-band credentials and bypass list; otherwise the -// endpoint's environment-derived proxy URL is used (with no credentials or -// bypass list — the env path folds credentials into the URL userinfo and -// consumes NO_PROXY during resolution, per Go's proxy-env convention). Kept -// untagged here (like buildKernelConfig) so the explicit-over-env precedence is -// asserted under CGO_ENABLED=0 (see TestResolveKernelProxy); newKernelBackend +// environment proxy is used for every kernel destination, with NO_PROXY +// translated into the kernel's bypass list (see proxyForEndpointFunc). The env +// path carries no separate credentials: they stay in the URL userinfo. An env +// socks4/socks4a proxy that the warehouse selects returns ErrInvalidKernelConfig +// (see kernelEnvProxyURL). +// Kept untagged here (like buildKernelConfig) so the explicit-over-env precedence +// is asserted under CGO_ENABLED=0 (see TestResolveKernelProxy); newKernelBackend // calls it after buildKernelConfig so it stays a thin assembler. -func resolveKernelProxy(cfg *config.Config, kc *kernel.Config) { +func resolveKernelProxy(cfg *config.Config, kc *kernel.Config) error { if ke := cfg.KernelExperimental; ke != nil && ke.ProxyURL != "" { kc.ProxyURL = ke.ProxyURL kc.ProxyUsername = ke.ProxyUsername kc.ProxyPassword = ke.ProxyPassword kc.ProxyBypassHosts = ke.ProxyBypassHosts - return + return nil + } + proxyURL, bypassHosts, err := proxyForEndpoint(cfg) + if err != nil { + return err } - kc.ProxyURL = proxyForEndpoint(cfg) + kc.ProxyURL = proxyURL + kc.ProxyBypassHosts = bypassHosts + return nil } // resolveKernelAuth picks the kernel auth form from the config. The kernel backend diff --git a/kernel_proxy.go b/kernel_proxy.go index 8ce0e070..211d69cd 100644 --- a/kernel_proxy.go +++ b/kernel_proxy.go @@ -5,8 +5,12 @@ import ( "net" "net/http" "net/url" + "os" "strconv" + "strings" + "sync" + dbsqlerr "github.com/databricks/databricks-sql-go/v2/errors" "github.com/databricks/databricks-sql-go/v2/internal/config" ) @@ -15,23 +19,109 @@ import ( // build lets its test run under CGO_ENABLED=0 rather than being dead behind the // tag. newKernelBackend (tagged) calls proxyForEndpoint. -// proxyForEndpoint resolves the proxy the Thrift path would use for this -// connection, via the same http.ProxyFromEnvironment (HTTP(S)_PROXY / NO_PROXY) -// the Thrift transport applies at request time. Building the endpoint request -// lets ProxyFromEnvironment apply the NO_PROXY rules for this exact host, so the -// kernel sees the same effective proxy decision — returning "" (direct) when -// NO_PROXY excludes the host or no proxy is set. No extra dependency: this is the -// stdlib function the driver already relies on. -func proxyForEndpoint(cfg *config.Config) string { - return proxyForEndpointFunc(cfg, http.ProxyFromEnvironment) +// proxyForEndpoint resolves the environment proxy for the kernel: one proxy URL +// that the kernel uses for every destination (warehouse, CloudFetch storage, +// OAuth), plus a bypass list the kernel matches per destination. It reads the +// same HTTP(S)_PROXY / NO_PROXY variables as the Thrift transport's +// http.ProxyFromEnvironment, and decides the warehouse itself with that function. +// It returns "" (no proxy) when no proxy applies, which leaves the environment to +// the kernel as before. +func proxyForEndpoint(cfg *config.Config) (proxyURL, bypassHosts string, err error) { + return proxyForEndpointFunc(cfg, http.ProxyFromEnvironment, proxyEnvSnapshot()) } -// 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 -// inject a deterministic resolver to exercise proxy-set / NO_PROXY / direct -// without depending on http.ProxyFromEnvironment's process-wide env caching. -func proxyForEndpointFunc(cfg *config.Config, resolve func(*http.Request) (*url.URL, error)) string { +var ( + proxyEnvOnce sync.Once + proxyEnvOS proxyEnv +) + +// proxyEnvSnapshot reads the proxy environment once per process, like +// http.ProxyFromEnvironment, so the warehouse decision and the other destinations +// come from the same values: later changes to the environment don't apply, as on +// the Thrift path. It triggers ProxyFromEnvironment's own one-time read first, so +// both snapshots are taken together unless net/http already read the environment +// earlier in the process. +func proxyEnvSnapshot() proxyEnv { + proxyEnvOnce.Do(func() { + _, _ = http.ProxyFromEnvironment(&http.Request{URL: &url.URL{Scheme: "https", Host: "proxy-env.invalid"}}) + proxyEnvOS = proxyEnvFromOS() + }) + return proxyEnvOS +} + +// proxyEnv is the proxy environment as golang.org/x/net/http/httpproxy (behind +// http.ProxyFromEnvironment) reads it. The stdlib copy of that package is not +// importable, so the few rules the kernel path needs are mirrored here. +type proxyEnv struct { + HTTPProxy, HTTPSProxy, NoProxy string + CGI bool +} + +func proxyEnvFromOS() proxyEnv { + return proxyEnv{ + HTTPProxy: getEnvAny("HTTP_PROXY", "http_proxy"), + HTTPSProxy: getEnvAny("HTTPS_PROXY", "https_proxy"), + NoProxy: getEnvAny("NO_PROXY", "no_proxy"), + CGI: os.Getenv("REQUEST_METHOD") != "", + } +} + +func getEnvAny(names ...string) string { + for _, n := range names { + if v := os.Getenv(n); v != "" { + return v + } + } + return "" +} + +// proxyFor returns the proxy Go uses for a request with this scheme, ignoring +// NO_PROXY, or nil when there is none. Like httpproxy, an unparsable value counts +// as unset and HTTP_PROXY is ignored in a CGI process. +func (e proxyEnv) proxyFor(scheme string) *url.URL { + var raw string + switch scheme { + case "https": + raw = e.HTTPSProxy + case "http": + if e.CGI { + return nil + } + raw = e.HTTPProxy + } + if raw == "" { + return nil + } + u, err := url.Parse(raw) + if err != nil || u.Scheme == "" || u.Host == "" { + if u, err := url.Parse("http://" + raw); err == nil { + return u + } + return nil + } + return u +} + +// proxyForEndpointFunc is the testable core. resolve decides the warehouse +// (http.ProxyFromEnvironment in production; tests inject a deterministic +// resolver because that function snapshots the environment once per process), and +// env supplies the proxy and NO_PROXY for the other destinations. +// +// - Warehouse proxied: its proxy URL goes to the kernel with the NO_PROXY bypass +// list, so storage and OAuth hosts in NO_PROXY connect directly. The kernel +// path is https-only (validateKernelConfigContext), so that proxy is the +// HTTPS_PROXY that storage and OAuth hosts would use on Thrift too. +// - Warehouse not proxied (NO_PROXY, loopback, or no proxy for its scheme) while +// HTTPS_PROXY is set: HTTPS_PROXY goes to the kernel, since storage and OAuth +// use https, with the warehouse host added to the bypass list. Otherwise the +// kernel would read the raw environment, and a socks5:// value would resolve +// other hosts locally instead of at the proxy. A socks4 or socks4a proxy is +// passed as is here, since no request may select it. +// - Warehouse not proxied and no HTTPS_PROXY, NO_PROXY=*, a resolver error or an +// unbuildable endpoint: "" (the kernel applies its own environment handling). +// +// A SOCKS proxy is mapped to the Thrift path's behavior (see kernelEnvProxyURL). +func proxyForEndpointFunc(cfg *config.Config, resolve func(*http.Request) (*url.URL, error), env proxyEnv) (proxyURL, bypassHosts string, err error) { // Build the endpoint from scheme/host/port directly rather than via // cfg.ToEndpointURL(): that requires a non-empty HTTPPath and errors in the // warehouse-id addressing mode the kernel prefers (HTTPPath == ""), which would @@ -39,7 +129,7 @@ func proxyForEndpointFunc(cfg *config.Config, resolve func(*http.Request) (*url. // Only scheme+host matter for the proxy/NO_PROXY decision; the path is // irrelevant, so omitting it is correct here. if cfg.Host == "" { - return "" + return "", "", nil } scheme := cfg.Protocol if scheme == "" { @@ -47,7 +137,7 @@ func proxyForEndpointFunc(cfg *config.Config, resolve func(*http.Request) (*url. } endpoint, err := url.Parse(fmt.Sprintf("%s://%s", scheme, cfg.Host)) if err != nil { - return "" + return "", "", nil } // 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. @@ -56,11 +146,164 @@ func proxyForEndpointFunc(cfg *config.Config, resolve func(*http.Request) (*url. } req, err := http.NewRequest(http.MethodPost, endpoint.String(), nil) if err != nil { - return "" + return "", "", nil + } + warehouseProxy, err := resolve(req) + if err != nil { + return "", "", nil + } + proxy := warehouseProxy + if proxy == nil { + // Only storage and OAuth hosts can use the proxy now, and they are https. + proxy = env.proxyFor("https") + if proxy == nil || noProxyAll(env.NoProxy) { + return "", "", nil + } + } + proxyURL, err = kernelEnvProxyURL(proxy, warehouseProxy != nil) + if err != nil { + return "", "", err + } + return proxyURL, kernelBypassHosts(env.NoProxy, strings.ToLower(endpoint.Hostname()), warehouseProxy == nil), nil +} + +// kernelEnvProxyURL keeps the Thrift path's SOCKS behavior for an +// environment-derived proxy. net/http dials socks5:// by sending the target host +// name to the proxy, so the proxy resolves DNS; the kernel resolves socks5:// +// targets locally and socks5h:// at the proxy, so socks5 is rewritten to socks5h. +// net/http cannot use a socks4/socks4a proxy, so when the warehouse selects one +// (warehouseSelects) the connection fails closed here rather than connect on the +// kernel path only. When the warehouse bypasses it, a request may never select +// it, so the URL is passed as is: hosts the kernel does route through it use the +// configured socks4 proxy (never a direct connection), where the Thrift path +// would fail. The error names the scheme and never the URL, which may carry +// credentials. Explicit WithKernelProxy URLs skip this. +func kernelEnvProxyURL(u *url.URL, warehouseSelects bool) (string, error) { + switch u.Scheme { + case "socks5": + rewritten := *u + rewritten.Scheme = "socks5h" + return rewritten.String(), nil + case "socks4", "socks4a": + if !warehouseSelects { + return u.String(), nil + } + return "", fmt.Errorf("databricks: a %s:// proxy from the HTTP(S)_PROXY environment variable is %w: "+ + "the default backend cannot use it either; use socks5:// or socks5h://, or set it with WithKernelProxy", + u.Scheme, dbsqlerr.ErrInvalidKernelConfig) + } + return u.String(), nil +} + +// kernelLoopbackBypass mirrors Go never proxying localhost or a loopback address. +// Go exempts only the exact name localhost, while the kernel's entry also matches +// its subdomains, so these entries go through the same warehouse filter as +// NO_PROXY entries. +var kernelLoopbackBypass = []string{"localhost", "127.0.0.0/8", "::1"} + +// kernelBypassHosts translates NO_PROXY into the kernel's bypass list. The kernel +// (reqwest/hyper-util) matches hosts only: `*`, IP and CIDR entries, and domain +// entries that match the domain and its subdomains, with or without a leading dot. +// Go's rules (httpproxy) differ in two ways, handled like this: +// +// - Port-specific entries (`host:port`): kept as the bare host when the port is +// 443, the port the kernel uses for CloudFetch storage and OAuth hosts, and +// dropped otherwise. A dropped entry stays proxied on the kernel path. +// - `.example.com` (and `*.example.com`) match only subdomains in Go, but also +// example.com itself in the kernel. +// +// The warehouse always gets Go's exact decision: when Go bypasses it, its host is +// added; when Go proxies it, entries that would bypass it in the kernel +// (including the loopback entries) are dropped. Non-ASCII entries are dropped: Go +// converts them with IDNA, which needs golang.org/x/net, and the kernel only sees +// ASCII host names, so they could not match. +func kernelBypassHosts(noProxy, warehouseHost string, warehouseBypassed bool) string { + candidates := append([]string(nil), kernelLoopbackBypass...) + for _, p := range strings.Split(noProxy, ",") { + if entry, ok := kernelBypassEntry(p); ok { + candidates = append(candidates, entry) + } + } + entries := make([]string, 0, len(candidates)+1) + for _, entry := range candidates { + if !warehouseBypassed && kernelBypassMatches(entry, warehouseHost) { + continue + } + entries = append(entries, entry) + } + if warehouseBypassed { + entries = append(entries, warehouseHost) + } + seen := make(map[string]bool, len(entries)) + out := entries[:0] + for _, e := range entries { + if !seen[e] { + seen[e] = true + out = append(out, e) + } + } + return strings.Join(out, ",") +} + +// kernelBypassEntry converts one NO_PROXY entry, parsed as httpproxy does. +func kernelBypassEntry(p string) (string, bool) { + p = strings.ToLower(strings.TrimSpace(p)) + if p == "" { + return "", false + } + for i := 0; i < len(p); i++ { + if p[i] >= 0x80 { + return "", false + } + } + if p == "*" { + return "*", true + } + if _, cidr, err := net.ParseCIDR(p); err == nil { + return cidr.String(), true + } + host, port, err := net.SplitHostPort(p) + if err != nil { + host, port = p, "" + } + host = strings.TrimSuffix(strings.TrimPrefix(host, "["), "]") + if host == "" || (port != "" && port != "443") { + return "", false + } + if ip := net.ParseIP(host); ip != nil { + return ip.String(), true + } + if strings.HasPrefix(host, "*.") { + host = host[1:] + } + if host == "." { + return "", false } - proxyURL, err := resolve(req) - if err != nil || proxyURL == nil { - return "" + return host, true +} + +// kernelBypassMatches reports whether the kernel's matcher bypasses host for entry. +func kernelBypassMatches(entry, host string) bool { + if entry == "*" { + return true + } + if ip := net.ParseIP(host); ip != nil { + if _, cidr, err := net.ParseCIDR(entry); err == nil { + return cidr.Contains(ip) + } + eip := net.ParseIP(entry) + return eip != nil && eip.Equal(ip) + } + d := strings.TrimPrefix(entry, ".") + return host == d || strings.HasSuffix(host, "."+d) +} + +// noProxyAll reports whether NO_PROXY contains `*`, which bypasses every host. +func noProxyAll(noProxy string) bool { + for _, p := range strings.Split(noProxy, ",") { + if strings.TrimSpace(p) == "*" { + return true + } } - return proxyURL.String() + return false } diff --git a/kernel_proxy_test.go b/kernel_proxy_test.go index 8b7eceb3..22111818 100644 --- a/kernel_proxy_test.go +++ b/kernel_proxy_test.go @@ -1,23 +1,36 @@ package dbsql import ( + "encoding/json" "errors" "net/http" "net/url" + "os" + "os/exec" + "strings" "testing" + dbsqlerr "github.com/databricks/databricks-sql-go/v2/errors" "github.com/databricks/databricks-sql-go/v2/internal/backend/kernel" "github.com/databricks/databricks-sql-go/v2/internal/config" ) -// proxyForEndpointFunc maps the injected resolver's decision to a proxy URL -// string (or "" for direct), and returns "" for an unbuildable endpoint. The -// production path uses http.ProxyFromEnvironment, whose env is snapshotted once -// per process (sync.Once) and so can't be re-driven mid-test; the resolver seam -// lets us assert every branch deterministically. Each case mirrors an -// httpproxy-style outcome: proxy set for this host, host excluded by NO_PROXY, -// no proxy configured, and an unbuildable endpoint. Pure Go, so it runs in the -// default CGO_ENABLED=0 build (no kernel lib required). +// loopbackBypass is the bypass-list prefix the env path always sends: Go never +// proxies localhost or a loopback address. +const loopbackBypass = "localhost,127.0.0.0/8,::1" + +// proxyForEndpointFunc maps the injected resolver's warehouse decision and the +// injected proxy environment to the kernel's proxy URL and bypass list ("" for no +// proxy). The production path uses http.ProxyFromEnvironment, whose env is +// snapshotted once per process (sync.Once) and so can't be re-driven mid-test; +// the resolver seam lets us assert every branch deterministically. Each case +// mirrors an httpproxy-style outcome: proxy set for this host, host excluded by +// NO_PROXY (the proxy still goes to the kernel for other hosts), no proxy +// configured, and an unbuildable endpoint. SOCKS schemes keep the Thrift path's +// behavior: socks5 becomes socks5h (net/http resolves socks5 targets at the +// proxy), and socks4/socks4a fail closed when the warehouse selects them because +// net/http cannot use them; with the warehouse bypassed they pass through as is. +// Pure Go, so it runs in the default CGO_ENABLED=0 build (no kernel lib required). func TestProxyForEndpoint(t *testing.T) { validCfg := func() *config.Config { c := config.WithDefaults() @@ -27,18 +40,31 @@ func TestProxyForEndpoint(t *testing.T) { return c } proxyURL, _ := url.Parse("http://corp-proxy:3128") + resolveTo := func(raw string) func(*http.Request) (*url.URL, error) { + u, err := url.Parse(raw) + if err != nil { + t.Fatalf("url.Parse(%q): %v", raw, err) + } + return func(*http.Request) (*url.URL, error) { return u, nil } + } + + bypassed := func(*http.Request) (*url.URL, error) { return nil, nil } cases := []struct { - name string - cfg *config.Config - resolve func(*http.Request) (*url.URL, error) - want string + name string + cfg *config.Config + resolve func(*http.Request) (*url.URL, error) + env proxyEnv + want string + wantBypass string + wantErr bool }{ { - name: "proxy set for host", - cfg: validCfg(), - resolve: func(*http.Request) (*url.URL, error) { return proxyURL, nil }, - want: "http://corp-proxy:3128", + name: "proxy set for host", + cfg: validCfg(), + resolve: func(*http.Request) (*url.URL, error) { return proxyURL, nil }, + want: "http://corp-proxy:3128", + wantBypass: loopbackBypass, }, { // Warehouse-id addressing mode (HTTPPath == "") is what the kernel @@ -52,8 +78,9 @@ func TestProxyForEndpoint(t *testing.T) { c.WarehouseID = "abc" // no HTTPPath return c }(), - resolve: func(*http.Request) (*url.URL, error) { return proxyURL, nil }, - want: "http://corp-proxy:3128", + resolve: func(*http.Request) (*url.URL, error) { return proxyURL, nil }, + want: "http://corp-proxy:3128", + wantBypass: loopbackBypass, }, { // A port in the host wins over cfg.Port, so the endpoint stays parsable. @@ -69,12 +96,79 @@ func TestProxyForEndpoint(t *testing.T) { } return proxyURL, nil }, - want: "http://corp-proxy:3128", + want: "http://corp-proxy:3128", + wantBypass: loopbackBypass, + }, + { + name: "host excluded by NO_PROXY and no env proxy -> direct", + cfg: validCfg(), + resolve: bypassed, + want: "", + }, + { + // The warehouse connects directly, but the proxy still goes to the kernel + // for storage/OAuth hosts, with proxy-side DNS kept by socks5 -> socks5h. + name: "warehouse bypassed still passes the proxy", + cfg: validCfg(), + resolve: bypassed, + env: proxyEnv{HTTPSProxy: "socks5://127.0.0.1:1080", NoProxy: "my-workspace.databricks.com"}, + want: "socks5h://127.0.0.1:1080", + wantBypass: loopbackBypass + ",my-workspace.databricks.com", }, { - name: "host excluded by NO_PROXY -> direct", + name: "NO_PROXY=* -> direct", cfg: validCfg(), - resolve: func(*http.Request) (*url.URL, error) { return nil, nil }, + resolve: bypassed, + env: proxyEnv{HTTPSProxy: "socks5://127.0.0.1:1080", NoProxy: "*"}, + want: "", + }, + { + // No request may select the proxy, so it isn't rejected up front. + name: "warehouse bypassed passes a socks4 env proxy as is", + cfg: validCfg(), + resolve: bypassed, + env: proxyEnv{HTTPSProxy: "socks4://proxy.internal:1080", NoProxy: "my-workspace.databricks.com"}, + want: "socks4://proxy.internal:1080", + wantBypass: loopbackBypass + ",my-workspace.databricks.com", + }, + { + name: "warehouse bypassed passes a socks4a env proxy as is", + cfg: validCfg(), + resolve: bypassed, + env: proxyEnv{HTTPSProxy: "socks4a://proxy.internal:1080", NoProxy: "my-workspace.databricks.com"}, + want: "socks4a://proxy.internal:1080", + wantBypass: loopbackBypass + ",my-workspace.databricks.com", + }, + { + name: "storage and OAuth NO_PROXY entries reach the kernel", + cfg: validCfg(), + resolve: resolveTo("socks5h://127.0.0.1:1080"), + env: proxyEnv{HTTPSProxy: "socks5h://127.0.0.1:1080", NoProxy: "storage.example.net, login.example.com:443"}, + want: "socks5h://127.0.0.1:1080", + wantBypass: loopbackBypass + ",storage.example.net,login.example.com", + }, + { + // Storage and OAuth are https, so they get HTTPS_PROXY, as on Thrift. + name: "http endpoint with the warehouse bypassed passes HTTPS_PROXY", + cfg: func() *config.Config { + c := validCfg() + c.Protocol = "http" + return c + }(), + resolve: bypassed, + env: proxyEnv{HTTPProxy: "corp-proxy:3128", HTTPSProxy: "socks5://127.0.0.1:1080"}, + want: "socks5h://127.0.0.1:1080", + wantBypass: loopbackBypass + ",my-workspace.databricks.com", + }, + { + name: "http endpoint with the warehouse bypassed and no HTTPS_PROXY -> direct", + cfg: func() *config.Config { + c := validCfg() + c.Protocol = "http" + return c + }(), + resolve: bypassed, + env: proxyEnv{HTTPProxy: "corp-proxy:3128"}, want: "", }, { @@ -96,23 +190,73 @@ func TestProxyForEndpoint(t *testing.T) { }, want: "", }, + {name: "socks5 -> socks5h", cfg: validCfg(), resolve: resolveTo("socks5://127.0.0.1:1080"), want: "socks5h://127.0.0.1:1080", wantBypass: loopbackBypass}, + {name: "socks5 userinfo kept", cfg: validCfg(), resolve: resolveTo("socks5://user:secret@proxy.internal:1080"), want: "socks5h://user:secret@proxy.internal:1080", wantBypass: loopbackBypass}, + {name: "socks5h verbatim", cfg: validCfg(), resolve: resolveTo("socks5h://user:secret@proxy.internal:1080"), want: "socks5h://user:secret@proxy.internal:1080", wantBypass: loopbackBypass}, + {name: "https verbatim", cfg: validCfg(), resolve: resolveTo("https://user:secret@proxy.internal:3128"), want: "https://user:secret@proxy.internal:3128", wantBypass: loopbackBypass}, //nolint:gosec // G101: test literals, not real credentials + {name: "socks4 rejected", cfg: validCfg(), resolve: resolveTo("socks4://user:secret@proxy.internal:1080"), wantErr: true}, + {name: "socks4a rejected", cfg: validCfg(), resolve: resolveTo("socks4a://user:secret@proxy.internal:1080"), wantErr: true}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - if got := proxyForEndpointFunc(tc.cfg, tc.resolve); got != tc.want { - t.Errorf("proxyForEndpointFunc = %q, want %q", got, tc.want) + got, gotBypass, err := proxyForEndpointFunc(tc.cfg, tc.resolve, tc.env) + if got != tc.want || gotBypass != tc.wantBypass { + t.Errorf("proxyForEndpointFunc = (%q, %q), want (%q, %q)", got, gotBypass, tc.want, tc.wantBypass) + } + if !tc.wantErr { + if err != nil { + t.Errorf("unexpected error: %v", err) + } + return + } + if !errors.Is(err, dbsqlerr.ErrInvalidKernelConfig) { + t.Fatalf("err = %v, want ErrInvalidKernelConfig", err) + } + if strings.Contains(err.Error(), "secret") || strings.Contains(err.Error(), "user") || + strings.Contains(err.Error(), "proxy.internal") { + t.Errorf("error must not include the proxy URL: %v", err) } }) } // The production wrapper wires http.ProxyFromEnvironment and must not panic. - _ = proxyForEndpoint(validCfg()) + if _, _, err := proxyForEndpoint(validCfg()); err != nil { + t.Logf("proxyForEndpoint with this process's environment: %v", err) + } +} + +// kernelBypassHosts translates NO_PROXY into the kernel's host-only matcher and +// keeps the warehouse on Go's exact decision. +func TestKernelBypassHosts(t *testing.T) { + cases := []struct { + name string + noProxy string + warehouse string + bypassed bool + want string + }{ + {name: "empty", warehouse: "w.example.com", want: loopbackBypass}, + {name: "port 443 kept as bare host, other ports dropped", noProxy: "storage.example.net:443, other.example.net:8443", warehouse: "w.example.com", want: loopbackBypass + ",storage.example.net"}, + {name: "leading dot and wildcard stay subdomain entries", noProxy: ".blob.core.windows.net,*.dfs.core.windows.net", warehouse: "w.example.com", want: loopbackBypass + ",.blob.core.windows.net,.dfs.core.windows.net"}, + {name: "IP, IPv6 and CIDR entries", noProxy: "10.1.2.3, fd00::1, 10.1.2.3/8, [fd00::2]:443, 192.0.2.1:8443", warehouse: "w.example.com", want: loopbackBypass + ",10.1.2.3,fd00::1,10.0.0.0/8,fd00::2"}, + {name: "entries that would bypass a proxied warehouse are dropped", noProxy: ".w.example.com,example.com:443,storage.example.net", warehouse: "w.example.com", want: loopbackBypass + ",storage.example.net"}, + {name: "bypassed warehouse added once, lowercased", noProxy: "W.Example.com", warehouse: "w.example.com", bypassed: true, want: loopbackBypass + ",w.example.com"}, + {name: "localhost entry dropped for a proxied warehouse under localhost", noProxy: "storage.example.net", warehouse: "warehouse.localhost", want: "127.0.0.0/8,::1,storage.example.net"}, + {name: "non-ASCII and malformed entries dropped", noProxy: "bücher.example, :443, *., ,", warehouse: "w.example.com", want: loopbackBypass}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := kernelBypassHosts(tc.noProxy, tc.warehouse, tc.bypassed); got != tc.want { + t.Errorf("kernelBypassHosts(%q) = %q, want %q", tc.noProxy, got, tc.want) + } + }) + } } // resolveKernelProxy: an explicit WithKernelProxy (KernelExperimental.ProxyURL // set) wins verbatim — url + credentials + bypass list — over the environment; -// with no explicit proxy it falls back to the endpoint's env-derived URL and -// leaves credentials / bypass empty. Pure Go, default CGO_ENABLED=0 build. +// with no explicit proxy it falls back to the env-derived URL and bypass list and +// leaves credentials empty. Pure Go, default CGO_ENABLED=0 build. func TestResolveKernelProxy(t *testing.T) { t.Run("explicit WithKernelProxy wins verbatim over env", func(t *testing.T) { c := config.WithDefaults() @@ -126,7 +270,9 @@ func TestResolveKernelProxy(t *testing.T) { ProxyBypassHosts: "localhost,*.internal", } var kc kernel.Config - resolveKernelProxy(c, &kc) + if err := resolveKernelProxy(c, &kc); err != nil { + t.Fatal(err) + } if kc.ProxyURL != "http://explicit-proxy:8080" { t.Errorf("ProxyURL = %q, want the explicit WithKernelProxy URL", kc.ProxyURL) } @@ -135,18 +281,131 @@ func TestResolveKernelProxy(t *testing.T) { } }) - t.Run("no explicit proxy falls back to env (no creds/bypass)", func(t *testing.T) { + t.Run("no explicit proxy falls back to env (no separate creds)", func(t *testing.T) { c := config.WithDefaults() c.Host = "my-workspace.databricks.com" c.Port = 443 c.WarehouseID = "abc" - // No KernelExperimental proxy → env resolution. With no proxy env set in - // the test process this resolves to direct (""), and the credential / - // bypass fields must stay empty (the env path can't carry them). + // No KernelExperimental proxy → env resolution (exact env cases run in + // TestResolveKernelProxyEnvironment). The env path keeps credentials in the + // URL userinfo, and a bypass list only accompanies a proxy URL. var kc kernel.Config - resolveKernelProxy(c, &kc) - if kc.ProxyUsername != "" || kc.ProxyPassword != "" || kc.ProxyBypassHosts != "" { - t.Errorf("env path must not populate credentials/bypass: %+v", kc) + if err := resolveKernelProxy(c, &kc); err != nil { + t.Fatal(err) + } + if kc.ProxyUsername != "" || kc.ProxyPassword != "" { + t.Errorf("env path must not populate credentials: %+v", kc) + } + if kc.ProxyURL == "" && kc.ProxyBypassHosts != "" { + t.Errorf("bypass list without a proxy URL: %+v", kc) } }) } + +// kernelProxyEnvChild is set in the child processes TestResolveKernelProxyEnvironment +// starts, each with one case's proxy environment. +const kernelProxyEnvChild = "DBSQL_TEST_KERNEL_PROXY_ENV_CHILD" + +type kernelProxyEnvResult struct { + URL string `json:"url"` + Bypass string `json:"bypass"` + Err string `json:"err"` + InvalidCfg bool `json:"invalid_cfg"` + ExplicitUser string `json:"explicit_user"` +} + +// TestResolveKernelProxyEnvironment drives resolveKernelProxy through the real +// http.ProxyFromEnvironment. That function reads the environment once per process, +// so each case runs in a child test process with its own HTTPS_PROXY / ALL_PROXY / +// NO_PROXY. ALL_PROXY is not read here (as on the Thrift path); with no +// HTTPS_PROXY the driver passes no proxy and the kernel reads ALL_PROXY itself. +// A bypassed warehouse still sends the proxy, so other hosts keep it. +func TestResolveKernelProxyEnvironment(t *testing.T) { + if explicit, ok := os.LookupEnv(kernelProxyEnvChild); ok { + c := config.WithDefaults() + c.Host = "my-workspace.cloud.databricks.com" + c.WarehouseID = "abc" + if explicit != "" { + WithKernelProxy(KernelProxy{URL: explicit, Username: "explicit-user"})(c) + } + var kc kernel.Config + err := resolveKernelProxy(c, &kc) + res := kernelProxyEnvResult{URL: kc.ProxyURL, Bypass: kc.ProxyBypassHosts, ExplicitUser: kc.ProxyUsername} + if err != nil { + res.Err = err.Error() + res.InvalidCfg = errors.Is(err, dbsqlerr.ErrInvalidKernelConfig) + } + out, _ := json.Marshal(res) + _, _ = os.Stdout.WriteString("KERNEL_PROXY_RESULT " + string(out) + "\n") + return + } + + const warehouse = "my-workspace.cloud.databricks.com" + cases := []struct { + name string + env map[string]string + explicit string + want string + wantBypass string + wantErr bool + }{ + {name: "no proxy env is direct", want: ""}, + {name: "http proxy unchanged", env: map[string]string{"HTTPS_PROXY": "http://user:secret@127.0.0.1:3128"}, want: "http://user:secret@127.0.0.1:3128", wantBypass: loopbackBypass}, //nolint:gosec // G101: test literals, not real credentials + {name: "socks5 rewritten to socks5h", env: map[string]string{"HTTPS_PROXY": "socks5://user:secret@127.0.0.1:1080"}, want: "socks5h://user:secret@127.0.0.1:1080", wantBypass: loopbackBypass}, + {name: "lowercase https_proxy socks5", env: map[string]string{"https_proxy": "socks5://127.0.0.1:1080"}, want: "socks5h://127.0.0.1:1080", wantBypass: loopbackBypass}, + {name: "socks5h verbatim", env: map[string]string{"HTTPS_PROXY": "socks5h://127.0.0.1:1080"}, want: "socks5h://127.0.0.1:1080", wantBypass: loopbackBypass}, + {name: "socks4 rejected", env: map[string]string{"HTTPS_PROXY": "socks4://user:secret@127.0.0.1:1080"}, wantErr: true}, + {name: "socks4a rejected", env: map[string]string{"HTTPS_PROXY": "socks4a://user:secret@127.0.0.1:1080"}, wantErr: true}, + {name: "NO_PROXY warehouse keeps the proxy for other hosts", env: map[string]string{"HTTPS_PROXY": "socks5://127.0.0.1:1080", "NO_PROXY": warehouse}, want: "socks5h://127.0.0.1:1080", wantBypass: loopbackBypass + "," + warehouse}, + {name: "NO_PROXY suffix bypasses the warehouse", env: map[string]string{"HTTPS_PROXY": "socks5://127.0.0.1:1080", "NO_PROXY": ".databricks.com"}, want: "socks5h://127.0.0.1:1080", wantBypass: loopbackBypass + ",.databricks.com," + warehouse}, + {name: "NO_PROXY warehouse passes a socks4 proxy as is", env: map[string]string{"HTTPS_PROXY": "socks4://127.0.0.1:1080", "NO_PROXY": warehouse}, want: "socks4://127.0.0.1:1080", wantBypass: loopbackBypass + "," + warehouse}, + {name: "NO_PROXY storage and OAuth hosts reach the kernel", env: map[string]string{"HTTPS_PROXY": "socks5h://127.0.0.1:1080", "NO_PROXY": "storage.example.net, login.example.com:443, other.example.net:8443"}, want: "socks5h://127.0.0.1:1080", wantBypass: loopbackBypass + ",storage.example.net,login.example.com"}, + {name: "port-specific warehouse entry for another port keeps it proxied", env: map[string]string{"HTTPS_PROXY": "socks5h://127.0.0.1:1080", "NO_PROXY": warehouse + ":8443"}, want: "socks5h://127.0.0.1:1080", wantBypass: loopbackBypass}, + {name: "leading-dot entry for the warehouse apex keeps it proxied", env: map[string]string{"HTTPS_PROXY": "socks5h://127.0.0.1:1080", "NO_PROXY": "." + warehouse}, want: "socks5h://127.0.0.1:1080", wantBypass: loopbackBypass}, + {name: "NO_PROXY=* is direct", env: map[string]string{"HTTPS_PROXY": "socks5://127.0.0.1:1080", "NO_PROXY": "*"}, want: ""}, + {name: "ALL_PROXY alone is left to the kernel", env: map[string]string{"ALL_PROXY": "socks5://127.0.0.1:1080"}, want: ""}, + {name: "explicit socks5 beats env and stays verbatim", env: map[string]string{"HTTPS_PROXY": "socks5h://127.0.0.1:1080", "NO_PROXY": "storage.example.net"}, explicit: "socks5://127.0.0.1:2080", want: "socks5://127.0.0.1:2080"}, + {name: "explicit socks4 is not rejected", env: map[string]string{"HTTPS_PROXY": "socks4://127.0.0.1:1080"}, explicit: "socks4://127.0.0.1:2080", want: "socks4://127.0.0.1:2080"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + cmd := exec.Command(os.Args[0], "-test.run=^TestResolveKernelProxyEnvironment$", "-test.count=1") //nolint:gosec // G204: re-runs this test binary + for _, kv := range os.Environ() { + key := strings.ToUpper(strings.SplitN(kv, "=", 2)[0]) + if key != "HTTPS_PROXY" && key != "HTTP_PROXY" && key != "ALL_PROXY" && key != "NO_PROXY" && key != "REQUEST_METHOD" { + cmd.Env = append(cmd.Env, kv) + } + } + for k, v := range tc.env { + cmd.Env = append(cmd.Env, k+"="+v) + } + cmd.Env = append(cmd.Env, kernelProxyEnvChild+"="+tc.explicit) + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("child failed: %v\n%s", err, out) + } + var res kernelProxyEnvResult + found := false + for _, line := range strings.Split(string(out), "\n") { + if rest, ok := strings.CutPrefix(line, "KERNEL_PROXY_RESULT "); ok { + found = json.Unmarshal([]byte(rest), &res) == nil + } + } + if !found { + t.Fatalf("no child result in output:\n%s", out) + } + if res.URL != tc.want || res.Bypass != tc.wantBypass { + t.Errorf("ProxyURL, ProxyBypassHosts = %q, %q, want %q, %q", res.URL, res.Bypass, tc.want, tc.wantBypass) + } + if tc.wantErr != res.InvalidCfg || (!tc.wantErr && res.Err != "") { + t.Errorf("err = %q (ErrInvalidKernelConfig=%v), wantErr %v", res.Err, res.InvalidCfg, tc.wantErr) + } + if strings.Contains(res.Err, "secret") || strings.Contains(res.Err, "127.0.0.1") { + t.Errorf("error must not include the proxy URL: %q", res.Err) + } + if tc.explicit != "" && res.ExplicitUser != "explicit-user" { + t.Errorf("explicit credentials not forwarded: %+v", res) + } + }) + } +}