From 4406b2d89da54e207f05f19e67bee315053ad360 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:58:16 +0000 Subject: [PATCH 01/18] feat(proxy): Kerberos/Negotiate proxy authentication Authenticate to HTTP proxies with `Proxy-Authorization: Negotiate` (Kerberos/SPNEGO) on the CONNECT, for parity with the Python connector's `_proxy_auth_method="negotiate"` and Simba ODBC `ProxyAuthType=2`. - `ProxyConfig::auth`: `ProxyAuth::Default` (unchanged Basic/none), `ProxyAuth::Negotiate { service, host, realm }` (cross-krb5 0.5 behind the non-default `proxy-negotiate` feature: system GSSAPI on Unix, SSPI on Windows; ambient credentials, no delegation; target defaults to `HTTP/`) and `ProxyAuth::NegotiateCallback` (caller tokens, used by the Python binding, which links no GSSAPI library). - A token is created at client build (session open) and once more when the proxy answers a CONNECT with 407; only that hop is resent once on the rebuilt client, which then serves new requests. A second 407 on the same hop fails the request. It never falls back to Basic, a direct connection or an env proxy. Every token (session open, the Azure tenant redirect probe, 407 rebuilds) is created on the blocking pool, never on an async worker. - A Negotiate client loads its TLS setup once (native-tls: the connector; rustls: the OS trust store) and every 407 rebuild reuses it, so a rebuild only creates a client with the new token. - With Negotiate the kernel follows redirects itself with reqwest's default rules, so a 407 on a later hop never resends a request the server already received. As in reqwest, one request timeout covers every hop, the fresh-token rebuild and the final body. The retry ladder, U2M OAuth token requests and the feature-flag GET all send through `send_once`. - A token failure fails session open with the GSS major/minor message and no network I/O (`Unauthenticated`). Basic credentials, non-http(s) proxy URLs or a missing URL with Negotiate are `InvalidArgument`; `Negotiate` without the feature is rejected as unsupported. - C ABI `kernel_session_config_set_proxy_negotiate`; pyo3 `proxy_url`, `proxy_bypass_hosts` and `proxy_negotiate_token` kwargs. - Tests: a stub CONNECT proxy with replay-cache semantics (default PR tests, both TLS backends; tunnels, redirects, deadlines, U2M token requests, TLS parity of rebuilt clients, slow tokens off the async workers), a real MIT KDC + squid `negotiate_kerberos_auth` fixture (`ci/proxy/negotiate`, new PR job for both TLS backends), C smoke and pyo3 pytest cases. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- .github/workflows/pr-checks.yml | 51 ++ CONNECTION_PARAMETERS.md | 1 + Cargo.lock | 181 ++++- Cargo.toml | 17 +- NEXT_CHANGELOG.md | 1 + NOTICE | 3 + ci/proxy/negotiate/start.sh | 140 ++++ ci/proxy/negotiate/stop.sh | 21 + include/databricks_kernel.h | 11 + pyo3/NEXT_CHANGELOG.md | 1 + pyo3/src/session.rs | 62 ++ pyo3/tests/test_proxy_negotiate.py | 135 ++++ src/auth/oauth/u2m.rs | 48 +- src/c_abi/session.rs | 44 +- src/client/http.rs | 357 ++++++++- src/client/http_negotiate_tests.rs | 1164 ++++++++++++++++++++++++++++ src/client/mod.rs | 1 + src/client/proxy_negotiate.rs | 442 +++++++++++ src/config.rs | 79 ++ src/feature_flags/mod.rs | 27 +- src/lib.rs | 4 +- src/session.rs | 27 +- tests/c/session_smoke.c | 30 + 23 files changed, 2808 insertions(+), 39 deletions(-) create mode 100755 ci/proxy/negotiate/start.sh create mode 100755 ci/proxy/negotiate/stop.sh create mode 100644 pyo3/tests/test_proxy_negotiate.py create mode 100644 src/client/http_negotiate_tests.rs create mode 100644 src/client/proxy_negotiate.rs diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 2e6848a6..ad422031 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -160,6 +160,57 @@ jobs: # link and call the kernel. `cc` is preinstalled on the runner. run: make c-abi-test + proxy-negotiate: + name: Proxy Negotiate (${{ matrix.tls }}) + runs-on: + group: databricks-protected-runner-group + labels: linux-ubuntu-latest + strategy: + fail-fast: false + matrix: + tls: [tls-native, tls-rustls] + env: + RUSTC_WRAPPER: sccache + SCCACHE_GHA_ENABLED: "true" + FIXTURE: ${{ github.workspace }}/target/negotiate-fixture + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - uses: ./.github/actions/setup-public-package-proxies + with: + cargo: "true" + + - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 + with: + toolchain: stable + components: clippy + + - name: Setup sccache + uses: Mozilla-Actions/sccache-action@7d986dd989559c6ecdb630a3fd2557667be217ad # v0.0.9 + + - name: Install Kerberos and squid + # GSSAPI headers and libclang build `libgssapi-sys`. The KDC and + # squid run unprivileged from ci/proxy/negotiate/start.sh. + run: | + sudo apt-get update + sudo DEBIAN_FRONTEND=noninteractive apt-get install -y \ + krb5-kdc krb5-admin-server krb5-user squid libkrb5-dev libclang-dev + + - name: cargo clippy (proxy-negotiate) + run: cargo clippy --no-default-features --features ${{ matrix.tls }},proxy-negotiate --all-targets -- -D warnings + + - name: Start the KDC and Negotiate proxy + run: | + ci/proxy/negotiate/start.sh "$FIXTURE" + cat "$FIXTURE/env" >> "$GITHUB_ENV" + + - name: Negotiate tests (stub proxy and real KDC + squid) + run: cargo test --no-default-features --features ${{ matrix.tls }},proxy-negotiate --lib negotiate -- --include-ignored + + - name: Stop the fixture + if: always() + run: ci/proxy/negotiate/stop.sh "$FIXTURE" + adbc: name: ADBC native + C ABI runs-on: diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 6e29dc0c..b6f21019 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -187,6 +187,7 @@ behaviour applies. Setting `url` **overrides** those env vars. | `username` | Proxy basic-auth username. Overrides credentials embedded in `url`. | `None` | | `password` | Proxy basic-auth password. Ignored unless `username` is set. Redacted in `Debug`. | `None` | | `bypass_hosts` | Comma-separated hosts/domains to bypass the proxy, e.g. `localhost,*.internal.corp,.example.com`. | `None` | +| `auth` | `ProxyAuth::Default` (Basic from `username` or the URL, or none), `ProxyAuth::Negotiate { service, host, realm }` (Kerberos with the ambient credential cache / Windows logon; target `service/host[@realm]`, defaults `HTTP`, the proxy host, the default realm) or `ProxyAuth::NegotiateCallback` (tokens from a caller callback). Negotiate sends `Proxy-Authorization: Negotiate` on the proxy `CONNECT` only, creates a token at session open and once more on a proxy 407, and never falls back to Basic, a direct connection or an env proxy. It requires an `http(s)://` `url` and no Basic credentials (`InvalidArgument`); a failed token fails session open before any network I/O (`Unauthenticated`). `Negotiate` needs the non-default cargo feature `proxy-negotiate`, which links the system GSSAPI (`libgssapi_krb5`; building needs its headers and libclang) or uses SSPI on Windows; without it, it is rejected as unsupported. C ABI: `kernel_session_config_set_proxy_negotiate`. Python: `proxy_negotiate_token` (a callable returning `bytes`). | `Default` | ## `TlsConfig` — TLS / SSL (optional) diff --git a/Cargo.lock b/Cargo.lock index f1aee8c8..f38e390e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -63,6 +63,12 @@ dependencies = [ "libc", ] +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + [[package]] name = "approx" version = "0.5.1" @@ -302,6 +308,26 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "bindgen" +version = "0.71.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f58bf3d7db68cfbac37cfc485a8d711e87e064c3d0fe0435b92f7a407f9d6b3" +dependencies = [ + "bitflags", + "cexpr", + "clang-sys", + "itertools", + "log", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex 1.3.0", + "syn 2.0.118", +] + [[package]] name = "bit-vec" version = "0.9.1" @@ -397,7 +423,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f5d6cac793997bd970000024b2934968efe83b382de4fdcf4fcb46b6ee4ad996" dependencies = [ "find-msvc-tools", - "shlex", + "shlex 2.0.1", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom", ] [[package]] @@ -459,6 +494,17 @@ dependencies = [ "zeroize", ] +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + [[package]] name = "cmov" version = "0.5.4" @@ -563,6 +609,19 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "cross-krb5" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d426da4c3f9df62d4dac801df95d980a8ba8c4b4f95d02b9b607dab079d6768" +dependencies = [ + "anyhow", + "bitflags", + "bytes", + "libgssapi", + "windows", +] + [[package]] name = "crossbeam-channel" version = "0.5.17" @@ -657,6 +716,7 @@ dependencies = [ "base64", "cbc 0.2.1", "chrono", + "cross-krb5", "dashmap", "dirs", "futures", @@ -804,6 +864,12 @@ dependencies = [ "syn 2.0.118", ] +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + [[package]] name = "equivalent" version = "1.0.2" @@ -1060,6 +1126,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + [[package]] name = "h2" version = "0.4.15" @@ -1448,6 +1520,15 @@ dependencies = [ "once_cell", ] +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.18" @@ -1552,6 +1633,37 @@ version = "0.2.186" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" +[[package]] +name = "libgssapi" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e440a6151f5ef06571612e4121709aed90cfc0c40f8161f9090c71656758086d" +dependencies = [ + "bitflags", + "bytes", + "libgssapi-sys", +] + +[[package]] +name = "libgssapi-sys" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5103ac4557eacd36ff678b654b943f8966d3db9688fbd180a0b4c5464759ce17" +dependencies = [ + "bindgen", + "pkg-config", +] + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + [[package]] name = "libm" version = "0.2.16" @@ -2067,6 +2179,16 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.118", +] + [[package]] name = "proc-macro-crate" version = "3.5.0" @@ -2617,6 +2739,12 @@ dependencies = [ "lazy_static", ] +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + [[package]] name = "shlex" version = "2.0.1" @@ -3288,6 +3416,27 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + [[package]] name = "windows-core" version = "0.62.2" @@ -3301,6 +3450,17 @@ dependencies = [ "windows-strings", ] +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + [[package]] name = "windows-implement" version = "0.60.2" @@ -3329,6 +3489,16 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + [[package]] name = "windows-result" version = "0.4.1" @@ -3381,6 +3551,15 @@ dependencies = [ "windows_x86_64_msvc", ] +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" diff --git a/Cargo.toml b/Cargo.toml index 1b7f8c0b..5ec8241d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -79,6 +79,10 @@ rustls = { version = "0.23.41", optional = true, default-features = false, featu # Enforce TLS dependency minimums for consumers with their own lockfiles. rustls-webpki = { version = "0.103.16", optional = true, default-features = false } webpki-roots = { version = "1.0.11", optional = true, default-features = false } +# `tls-rustls`: loads the OS trust store, the same store reqwest's +# `rustls-tls-native-roots` loads, for the Windows revocation verifier (see +# `src/client/tls_revocation.rs`) and once per Negotiate client. +rustls-native-certs = { version = "0.8", optional = true } tokio = { version = "1", features = ["full", "sync"] } # Serialization @@ -159,13 +163,16 @@ zeroize = "1.9" jsonwebtoken = { version = "9", default-features = false, features = ["use_pem"] } # JWT signing (RS256/384/512, PS256/384/512, ES256/384); use_pem = PEM key loading (adds pem + simple_asn1, no TLS) pkcs8 = { version = "0.10", features = ["encryption", "pem", "std"] } # PKCS#8 PEM parsing + PBES2 passphrase decryption +# Kerberos/SPNEGO (`Proxy-Authorization: Negotiate`) proxy auth, behind the +# non-default `proxy-negotiate` feature. MIT GSSAPI or Heimdal via +# `libgssapi` on Unix (dynamically links `libgssapi_krb5`; building needs +# the GSSAPI headers and libclang), SSPI on Windows. MIT. +cross-krb5 = { version = "0.5", optional = true, default-features = false } + # Windows CryptoAPI for TLS certificate revocation (`src/client/tls_revocation.rs`). # `windows-sys` is already in the lock file; no new packages. [target.'cfg(windows)'.dependencies] windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security_Cryptography"] } -# `tls-rustls` on Windows only. Loads the OS trust store for the revocation verifier (see -# `src/client/tls_revocation.rs`), the same store reqwest's `rustls-tls-native-roots` loads. -rustls-native-certs = { version = "0.8", optional = true } # `pthread_sigmask` for kernel-owned runtime threads (`src/util/runtime.rs`). # Already in the graph through tokio, so no new crate is added. @@ -241,6 +248,10 @@ tls-rustls = [ "dep:webpki-roots", "dep:rustls-native-certs", ] +# Kerberos token generation for `ProxyAuth::Negotiate`. Off by default so +# default builds link no GSSAPI library; without it `Negotiate` is rejected +# as unsupported. `ProxyAuth::NegotiateCallback` works either way. +proxy-negotiate = ["dep:cross-krb5"] [lib] name = "databricks_sql_kernel" diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index ec9ccb7d..fec0060f 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -20,6 +20,7 @@ changes go in their respective binding's NEXT_CHANGELOG. `kernel_session_config_set_port` connect to `host:port`, so bindings no longer build it into the host. A non-default port is rejected with `InvalidArgument` if the host has credentials, a path, query or fragment. +- Kerberos (`Proxy-Authorization: Negotiate`) authentication to HTTP proxies via `ProxyConfig::auth` / `ProxyAuth::Negotiate` and the C ABI setter `kernel_session_config_set_proxy_negotiate`. Requires the non-default cargo feature `proxy-negotiate`, which links the system GSSAPI library (SSPI on Windows). ### Changed diff --git a/NOTICE b/NOTICE index cdc63bbf..0a01b892 100644 --- a/NOTICE +++ b/NOTICE @@ -35,6 +35,9 @@ Copyright: Copyright (c) 2014--2026, Kang Seonghoon and contributors; Copyright Package: chrono-tz Project URL: https://github.com/chronotope/chrono-tz Copyright: Copyright (c) 2016-2024 Benjamin Sago & the chronotope maintainers +Package: cross-krb5 (optional, `proxy-negotiate` feature; links the system GSSAPI library, e.g. MIT `libgssapi_krb5`) +Project URL: https://github.com/estokes/cross-krb5 +Copyright: Copyright cross-krb5 Authors. Package: dashmap diff --git a/ci/proxy/negotiate/start.sh b/ci/proxy/negotiate/start.sh new file mode 100755 index 00000000..736c4fa1 --- /dev/null +++ b/ci/proxy/negotiate/start.sh @@ -0,0 +1,140 @@ +#!/usr/bin/env bash +# Copyright (c) 2026 Databricks, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Throwaway Kerberos realm + squid Negotiate proxy for the `proxy-negotiate` +# tests. Runs unprivileged with everything under DIR; principals get random +# keys and nothing is committed. Needs krb5-kdc, krb5-admin-server, krb5-user +# and squid (with negotiate_kerberos_auth). Writes DIR/env (KEY=VALUE lines +# for $GITHUB_ENV); stop with ci/proxy/negotiate/stop.sh DIR. +# +# ci/proxy/negotiate/start.sh DIR +# +# Ports and realm: NEGOTIATE_KDC_PORT (48088), NEGOTIATE_PROXY_PORT (48128, +# Negotiate required), NEGOTIATE_OPEN_PROXY_PORT (48129, no auth), +# NEGOTIATE_REALM (KERNEL.TEST). NEGOTIATE_ALLOW_DOMAINS (squid dstdomain +# list) adds CONNECT targets beyond 127.0.0.1, e.g. ".databricks.com". +set -euo pipefail + +dir=$(mkdir -p "$1" && cd "$1" && pwd) +realm=${NEGOTIATE_REALM:-KERNEL.TEST} +kdc_port=${NEGOTIATE_KDC_PORT:-48088} +neg_port=${NEGOTIATE_PROXY_PORT:-48128} +open_port=${NEGOTIATE_OPEN_PROXY_PORT:-48129} +allow=${NEGOTIATE_ALLOW_DOMAINS:-localhost} +helper=${NEGOTIATE_SQUID_HELPER:-/usr/lib/squid/negotiate_kerberos_auth} +mkdir -p "$dir/kdc" "$dir/ccache" "$dir/rcache" "$dir/squid" +chmod 700 "$dir/kdc" "$dir/ccache" "$dir/rcache" + +cat > "$dir/krb5.conf" < "$dir/kdc/kdc.conf" < "$dir/kdc/kadm5.acl" + +export KRB5_CONFIG=$dir/krb5.conf KRB5_KDC_PROFILE=$dir/kdc/kdc.conf +if [ ! -f "$dir/kdc/principal" ]; then + kdb5_util create -s -r "$realm" -P "$(head -c 32 /dev/urandom | base64)" > "$dir/kdc/create.log" + for p in "alice@$realm" "HTTP/localhost@$realm"; do + kadmin.local -r "$realm" -q "addprinc -randkey $p" > /dev/null + done + kadmin.local -r "$realm" -q "ktadd -k $dir/kdc/alice.keytab alice@$realm" > /dev/null + kadmin.local -r "$realm" -q "ktadd -k $dir/kdc/http.keytab HTTP/localhost@$realm" > /dev/null + chmod 600 "$dir/kdc/"*.keytab +fi +nohup krb5kdc -n -P "$dir/kdc/krb5kdc.pid" > "$dir/kdc/krb5kdc.out" 2>&1 & +echo $! > "$dir/kdc/pid" + +# The acceptor's replay cache stays on (the default), as in production. +cat > "$dir/squid/squid.conf" <Hs %rm %ru user=%un ua="%{User-Agent}>h" +access_log stdio:$dir/squid/access.log negotiate +cache deny all +cache_mem 8 MB +coredump_dir $dir/squid +netdb_filename none +pinger_enable off +shutdown_lifetime 1 seconds +auth_param negotiate program $helper -s HTTP/localhost@$realm -k $dir/kdc/http.keytab -c $dir/rcache +auth_param negotiate children 5 startup=1 idle=1 +auth_param negotiate keep_alive on +acl negport myportname negport +acl openport myportname openport +acl local_dst dst 127.0.0.1 +acl allowed_dst dstdomain $allow +acl authed proxy_auth REQUIRED +http_access deny !local_dst !allowed_dst +http_access allow openport +http_access allow negport authed +http_access deny all +EOF +squid -k parse -f "$dir/squid/squid.conf" > "$dir/squid/parse.log" 2>&1 +nohup squid -N -f "$dir/squid/squid.conf" > "$dir/squid/squid.out" 2>&1 & +echo $! > "$dir/squid/pid" + +for port in "$kdc_port" "$neg_port" "$open_port"; do + for _ in $(seq 50); do + (exec 3<>"/dev/tcp/127.0.0.1/$port") 2> /dev/null && break + sleep 0.2 + done +done + +# Credential caches: valid, expired (10 s lifetime) and missing. +kinit -l 10s -k -t "$dir/kdc/alice.keytab" -c "FILE:$dir/ccache/expired" "alice@$realm" +expired_at=$((SECONDS + 11)) +kinit -k -t "$dir/kdc/alice.keytab" -c "FILE:$dir/ccache/valid" "alice@$realm" + +cat > "$dir/env" < /dev/null +done +exit 0 diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 871b21b8..231c9eda 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -460,6 +460,17 @@ KernelStatusCode kernel_session_config_set_proxy(KernelSessionConfig* config, co const char* username, const char* password, const char* bypass_hosts); +/* Authenticate to the `set_proxy` proxy with Kerberos (`Proxy-Authorization: + * Negotiate` on CONNECT), using the ambient credential cache / logon session. + * Target name `service/host[@realm]`; NULL or "" selects the default: `HTTP`, + * the proxy host, the Kerberos default realm. Session open fails before any + * network I/O when no token can be created, the proxy also has Basic + * credentials or is not http(s)://, `set_proxy` was not called, or the kernel + * was built without the `proxy-negotiate` feature. */ +KernelStatusCode kernel_session_config_set_proxy_negotiate(KernelSessionConfig* config, + const char* service, const char* host, + const char* realm); + /* Add a PEM-encoded CA-certificate bundle (`pem`/`len` bytes) to the TLS * trust store on top of the system roots (corporate re-signing proxy / * on-prem CA). */ diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index aeac93ff..e42bcaba 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -16,6 +16,7 @@ changes go in the root `NEXT_CHANGELOG.md`. - `Session(..., port=None)`: an optional connection port. A value outside `0..=65535` raises `ValueError`; a host the kernel can't combine with the port raises `KernelError` (`InvalidArgument`). +- `Session` accepts `proxy_url`, `proxy_bypass_hosts` and `proxy_negotiate_token` (a callable returning a Kerberos token as `bytes`) to authenticate to an HTTP proxy with `Proxy-Authorization: Negotiate`. The wheel links no GSSAPI library. ### Changed diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index ff74403b..6f85a844 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -260,6 +260,46 @@ fn build_http_config( Ok(Some(http)) } +/// Explicit proxy from the `proxy_*` kwargs; `None` keeps the kernel's +/// environment-variable proxy behaviour. `proxy_negotiate_token` is a +/// zero-argument callable returning one raw SPNEGO/Kerberos token +/// (`bytes`) for the proxy; the kernel calls it from a worker thread at +/// session open and once more if the proxy answers a `CONNECT` with 407. +/// If it raises or returns no token, the request fails closed. +fn build_proxy_config( + py: Python<'_>, + url: Option, + bypass_hosts: Option, + negotiate_token: Option>, +) -> PyResult> { + if url.is_none() && bypass_hosts.is_none() && negotiate_token.is_none() { + return Ok(None); + } + let mut proxy = databricks_sql_kernel::ProxyConfig::default(); + proxy.url = url; + proxy.bypass_hosts = bypass_hosts; + if let Some(callable) = negotiate_token { + if !callable.bind(py).is_callable() { + return Err(pyo3::exceptions::PyTypeError::new_err( + "proxy_negotiate_token must be a callable returning bytes", + )); + } + proxy.auth = databricks_sql_kernel::ProxyAuth::NegotiateCallback( + databricks_sql_kernel::NegotiateTokenCallback::new(move || { + Python::attach(|py| { + let value = callable.call0(py).map_err(|e| e.to_string())?; + let value = value.bind(py); + let bytes = value + .cast::() + .map_err(|_| "proxy_negotiate_token must return bytes".to_string())?; + Ok(bytes.as_bytes().to_vec()) + }) + }), + ); + } + Ok(Some(proxy)) +} + #[allow(clippy::too_many_arguments)] fn build_driver_system_configuration( driver_name: Option, @@ -347,6 +387,16 @@ impl Session { /// `tls_client_cert` + `tls_client_key` (both PEM bytes) configure /// mutual TLS. The two mTLS fields must be set together. /// + /// Proxy: `proxy_url` (`http://` or `https://`) overrides the + /// `HTTPS_PROXY` / `NO_PROXY` environment variables, with + /// `proxy_bypass_hosts` (comma-separated) as its bypass list. + /// `proxy_negotiate_token` (requires `proxy_url`) authenticates to it + /// with `Proxy-Authorization: Negotiate`: a zero-argument callable + /// returning one raw SPNEGO/Kerberos token as `bytes`, called at + /// session open and once more if the proxy answers 407. If it raises + /// or returns no token, the connection fails; it never falls back to + /// another proxy or a direct connection. + /// /// Retry/backoff: all optional, default to the kernel's built-in /// policy (1s/60s backoff, 6 total attempts, 900s budget) when /// unset. `retry_min_wait_secs` / `retry_max_wait_secs` bound the @@ -417,6 +467,9 @@ impl Session { tls_skip_hostname_verify=false, tls_client_cert=None, tls_client_key=None, + proxy_url=None, + proxy_bypass_hosts=None, + proxy_negotiate_token=None, sea_response_compression_enabled=false, request_timeout_secs=None, max_connections=None, @@ -485,6 +538,9 @@ impl Session { tls_skip_hostname_verify: bool, tls_client_cert: Option>, tls_client_key: Option>, + proxy_url: Option, + proxy_bypass_hosts: Option, + proxy_negotiate_token: Option>, sea_response_compression_enabled: bool, request_timeout_secs: Option, max_connections: Option, @@ -589,6 +645,9 @@ impl Session { None }; + let proxy_config = + build_proxy_config(py, proxy_url, proxy_bypass_hosts, proxy_negotiate_token)?; + // Build an HttpConfig only when the caller tuned the request timeout, // retry/backoff, or supplied custom headers; otherwise leave the // builder on its defaults (120s request timeout, @@ -667,6 +726,9 @@ impl Session { if let Some(tls) = tls_config { builder = builder.tls(tls); } + if let Some(proxy) = proxy_config { + builder = builder.proxy(proxy); + } if let Some(http) = http_config { builder = builder.http(http); } diff --git a/pyo3/tests/test_proxy_negotiate.py b/pyo3/tests/test_proxy_negotiate.py new file mode 100644 index 00000000..a28d5d80 --- /dev/null +++ b/pyo3/tests/test_proxy_negotiate.py @@ -0,0 +1,135 @@ +# Copyright (c) 2026 Databricks, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""`proxy_negotiate_token`: Negotiate proxy auth from a Python callable. + +No network: a local stub proxy records each CONNECT's Proxy-Authorization +and answers 407, so no request reaches a warehouse. +""" + +from __future__ import annotations + +import base64 +import socket +import threading + +import pytest + +import databricks_sql_kernel as k + + +class StubProxy: + def __init__(self) -> None: + self.connects: list[str | None] = [] + self._sock = socket.socket() + self._sock.bind(("127.0.0.1", 0)) + self._sock.listen(16) + self.url = "http://127.0.0.1:%d" % self._sock.getsockname()[1] + threading.Thread(target=self._serve, daemon=True).start() + + def _serve(self) -> None: + while True: + try: + conn, _ = self._sock.accept() + except OSError: + return + with conn: + head = b"" + while b"\r\n\r\n" not in head: + chunk = conn.recv(4096) + if not chunk: + break + head += chunk + auth = None + for line in head.decode("latin-1").split("\r\n")[1:]: + name, _, value = line.partition(":") + if name.lower() == "proxy-authorization": + auth = value.strip() + self.connects.append(auth) + conn.sendall( + b"HTTP/1.1 407 Proxy Authentication Required\r\n" + b"Proxy-Authenticate: Negotiate\r\nContent-Length: 0\r\n\r\n" + ) + + def close(self) -> None: + self._sock.close() + + +@pytest.fixture +def proxy(): + stub = StubProxy() + yield stub + stub.close() + + +def open_session(proxy_url, token): + return k.Session( + host="warehouse.invalid", + http_path="/sql/1.0/warehouses/x", + access_token="not-a-real-token", + proxy_url=proxy_url, + proxy_negotiate_token=token, + retry_max_attempts=1, + ) + + +def negotiate(raw: bytes) -> str: + return "Negotiate " + base64.b64encode(raw).decode() + + +def test_token_rides_connect_and_regenerates_once_on_407(proxy): + calls = [] + + def token(): + calls.append(1) + return b"token-%d" % len(calls) + + with pytest.raises(k.KernelError) as exc: + open_session(proxy.url, token) + assert exc.value.code == "Unauthenticated", str(exc.value) + assert "407" in str(exc.value) + # Preemptive token, one fresh token after the 407, then fail closed. + assert proxy.connects == [negotiate(b"token-1"), negotiate(b"token-2")] + assert "dG9rZW4t" not in str(exc.value) + + +def test_raising_callable_fails_before_any_connect(proxy): + def token(): + raise RuntimeError("no Kerberos ticket") + + with pytest.raises(k.KernelError) as exc: + open_session(proxy.url, token) + assert exc.value.code == "Unauthenticated" + assert "no Kerberos ticket" in str(exc.value) + assert proxy.connects == [] + + +@pytest.mark.parametrize("value", [b"", "dG9r", None]) +def test_invalid_token_fails_before_any_connect(proxy, value): + with pytest.raises(k.KernelError) as exc: + open_session(proxy.url, lambda: value) + assert exc.value.code == "Unauthenticated" + assert proxy.connects == [] + + +def test_non_callable_token_is_a_type_error(proxy): + with pytest.raises(TypeError): + open_session(proxy.url, b"token") + + +@pytest.mark.parametrize("proxy_url", [None, "socks5://127.0.0.1:1080", "http://u:p@127.0.0.1:1"]) +def test_negotiate_needs_a_plain_http_proxy_url(proxy_url): + with pytest.raises(k.KernelError) as exc: + open_session(proxy_url, lambda: b"token") + assert exc.value.code == "InvalidArgument" diff --git a/src/auth/oauth/u2m.rs b/src/auth/oauth/u2m.rs index 0035724e..98cbd888 100644 --- a/src/auth/oauth/u2m.rs +++ b/src/auth/oauth/u2m.rs @@ -47,8 +47,8 @@ use crate::kernel_error::{Error, Result}; use crate::util::runtime::block_on_in_runtime; use oauth2::basic::BasicClient; use oauth2::{ - AuthUrl, AuthorizationCode, ClientId, CsrfToken, PkceCodeChallenge, RedirectUrl, RefreshToken, - Scope, TokenResponse, TokenUrl, + AuthUrl, AuthorizationCode, ClientId, CsrfToken, HttpRequest, HttpResponse, PkceCodeChallenge, + RedirectUrl, RefreshToken, RequestTokenError, Scope, TokenResponse, TokenUrl, }; use std::sync::{Arc, Weak}; use std::time::Duration; @@ -62,6 +62,40 @@ const DEFAULT_CALLBACK_PORT: u16 = 8030; /// Default timeout for waiting for the OAuth callback. const DEFAULT_CALLBACK_TIMEOUT: Duration = Duration::from_secs(120); +/// Send an `oauth2`-built token request once through the kernel client: +/// no retry ladder (error statuses reach `oauth2` as before), but a +/// Negotiate proxy 407 gets its fresh-token retry (D3). +pub(crate) async fn send_token_request( + http_client: &DatabricksHttpClient, + request: HttpRequest, +) -> Result { + let request = reqwest::Request::try_from(request).map_err(|e| { + Error::invalid_argument().message(format!("failed to build token request: {e}")) + })?; + let response = http_client + .send_once(request) + .await? + .map_err(|e| Error::network_error().message(format!("token request failed: {e}")))?; + let status = response.status(); + let headers = response.headers().clone(); + let body = response.bytes().await.map_err(|e| { + Error::network_error().message(format!("failed to read token response: {e}")) + })?; + let mut http_response = HttpResponse::new(body.to_vec()); + *http_response.status_mut() = status; + *http_response.headers_mut() = headers; + Ok(http_response) +} + +/// A token-request failure for the user: `oauth2` shows a transport +/// failure only as "Request failed", so use the kernel's own message. +fn token_error_text(e: &RequestTokenError) -> String { + match e { + RequestTokenError::Request(e) => e.message.clone(), + other => other.to_string(), + } +} + /// Persist `token` to the on-disk cache, or do nothing when disk caching /// is disabled (`passphrase` is `None`). /// @@ -405,7 +439,7 @@ impl AuthProvider for AuthorizationCodeProvider { .exchange_refresh_token(&RefreshToken::new( refresh_token_str.clone(), )) - .request_async(http_client.inner()) + .request_async(&|request| send_token_request(&http_client, request)) .await { Ok(token_response) => { @@ -466,6 +500,7 @@ impl AuthProvider for AuthorizationCodeProvider { // browser flow remains reachable only for a // genuine first connect (no cached token), // below. + let e = token_error_text(&e); crate::klog::warn!("OAuth token refresh failed: {}", e); return Err(Error::unauthenticated().message(format!( "OAuth token refresh failed (refresh token expired or \ @@ -535,11 +570,14 @@ impl AuthProvider for AuthorizationCodeProvider { let token_response = oauth_client .exchange_code(AuthorizationCode::new(authorization_code)) .set_pkce_verifier(pkce_verifier) - .request_async(http_client.inner()) + .request_async(&|request| send_token_request(&http_client, request)) .await .map_err(|e| { Error::unauthenticated() - .message(format!("U2M authorization code exchange failed: {}", e)) + .message(format!( + "U2M authorization code exchange failed: {}", + token_error_text(&e) + )) .context("authorization code grant") })?; diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index b28eee7e..5004e713 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -27,8 +27,8 @@ use super::{block_on_ffi, KernelStatusCode}; use crate::config::{ - AuthConfig, ConnectionConfig, GeospatialResultRepresentation, HttpConfig, ProxyConfig, - ResultConfig, TelemetryConfig, TlsConfig, TokenCacheConfig, + AuthConfig, ConnectionConfig, GeospatialResultRepresentation, HttpConfig, ProxyAuth, + ProxyConfig, ResultConfig, TelemetryConfig, TlsConfig, TokenCacheConfig, }; use crate::kernel_error::Error; use crate::logging::{LoggingOutcome, LoggingSink}; @@ -149,6 +149,9 @@ pub struct KernelSessionConfig { /// Programmatic HTTP proxy (populated by `..._set_proxy`). `None` ⇒ /// reqwest's env-var proxy behaviour. proxy: Option, + /// Negotiate proxy auth (populated by `..._set_proxy_negotiate`); + /// requires `proxy`. + proxy_negotiate: Option, /// TLS relaxations / custom trust (populated by the `..._set_tls_*` /// setters). Defaults to the kernel's strict validation. tls: TlsSpec, @@ -294,6 +297,7 @@ pub unsafe extern "C" fn kernel_session_config_new( session_conf: HashMap::new(), geospatial_result_representation: None, proxy: None, + proxy_negotiate: None, tls: TlsSpec::default(), custom_headers: Vec::new(), sea_response_compression_enabled: false, @@ -1288,6 +1292,34 @@ pub unsafe extern "C" fn kernel_session_config_set_proxy( }) } +/// Authenticate to the proxy set by `kernel_session_config_set_proxy` with +/// Kerberos (`Proxy-Authorization: Negotiate`), using the ambient +/// credential cache / logon session. The target is `service/host[@realm]`: +/// NULL or empty `service` means `HTTP`, `host` the proxy host and `realm` +/// the Kerberos default realm. Session open fails if the proxy has Basic +/// credentials, is not `http(s)://`, or the kernel lacks the +/// `proxy-negotiate` feature. Maps to `ProxyAuth::Negotiate`. +/// +/// # Safety +/// `config` must be a live config handle; the args, if non-null, must be +/// NUL-terminated C strings. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_proxy_negotiate( + config: *mut KernelSessionConfig, + service: *const c_char, + host: *const c_char, + realm: *const c_char, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.proxy_negotiate = Some(ProxyAuth::Negotiate { + service: optional_str(service, "proxy negotiate service")?, + host: optional_str(host, "proxy negotiate host")?, + realm: optional_str(realm, "proxy negotiate realm")?, + }); + Ok(()) + }) +} + /// Add a PEM-encoded CA-certificate bundle (bytes) to the TLS trust store /// on top of the system roots — for a corporate re-signing proxy or an /// on-prem CA. Maps to `TlsConfig::custom_ca_cert`. @@ -1755,6 +1787,7 @@ fn build_session(config: KernelSessionConfig) -> Result Result, + /// Proxy authentication scheme (Basic/none or Negotiate). + pub auth: crate::config::ProxyAuth, } impl std::fmt::Debug for ProxyConfig { @@ -136,6 +139,7 @@ impl std::fmt::Debug for ProxyConfig { .field("username", &self.username) .field("password", &self.password.as_ref().map(|_| "[REDACTED]")) .field("bypass_hosts", &self.bypass_hosts) + .field("auth", &self.auth) .finish() } } @@ -393,6 +397,143 @@ fn build_mtls_identity(cert_pem: &[u8], key_pem: &[u8]) -> Result>> = std::sync::Mutex::new(Vec::new()); + +/// The token-independent, costly part of a Negotiate client's TLS setup. It +/// is loaded once per [`DatabricksHttpClient`] and shared by its first client +/// and every proxy-407 rebuild, so a rebuild only creates a client with the +/// new token instead of reloading the system trust store. It comes from the +/// same [`TlsConfig`] settings as reqwest's own setup, with the same result. +#[derive(Clone)] +struct ReusableTls { + /// The connector, built with the native-tls calls reqwest 0.12 makes for + /// these settings: system roots, custom CAs, mTLS identity, verification + /// flags and SNI. reqwest's `http2` and `native-tls-alpn` are off, so it + /// sets no ALPN. + #[cfg(feature = "tls-native")] + connector: native_tls::TlsConnector, + /// The OS trust store, which `rustls-tls-native-roots` otherwise reloads + /// on every build. reqwest still builds the rest of the rustls setup. + #[cfg(feature = "tls-rustls")] + system_roots: Vec, + /// With revocation on: the whole rustls config, as + /// [`super::tls_revocation::client_config`] builds it (session resumption + /// off, so clients share no session state). + #[cfg(all(windows, feature = "tls-rustls"))] + revocation: Option, +} + +impl std::fmt::Debug for ReusableTls { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("ReusableTls") + } +} + +/// Built at the first Negotiate client build; `None` keeps reqwest's own setup. +type SharedTls = OnceLock>; + +impl ReusableTls { + /// `None` for a custom CA bundle that native-tls and reqwest would parse + /// differently: that client keeps reqwest's own TLS setup. + /// `revocation` is the effective mode; this backend rejects it at open. + #[cfg(feature = "tls-native")] + fn load(config: &TlsConfig, _revocation: Option) -> Result> { + let mut tls = native_tls::TlsConnector::builder(); + tls.danger_accept_invalid_hostnames(config.allow_hostname_mismatch.unwrap_or(false)) + .danger_accept_invalid_certs(config.allow_self_signed.unwrap_or(false)) + .use_sni(true) + .disable_built_in_roots(false); + let file = match &config.trusted_certificate_path { + Some(path) => Some(std::fs::read(path).map_err(|e| { + Error::invalid_argument() + .message(format!("Failed to read TLS certificate '{path}': {e}")) + })?), + None => None, + }; + for pem in file.iter().chain(&config.trusted_certificate_pem) { + // reqwest reads only `CERTIFICATE` blocks and OpenSSL also reads + // other labels, so the same count means the same certificates. + let (Ok(certs), Ok(expected)) = ( + native_tls::Certificate::stack_from_pem(pem), + reqwest::Certificate::from_pem_bundle(pem), + ) else { + return Ok(None); + }; + if certs.len() != expected.len() { + return Ok(None); + } + for cert in certs { + tls.add_root_certificate(cert); + } + } + if let (Some(cert), Some(key)) = (&config.client_cert_pem, &config.client_key_pem) { + tls.identity(native_tls::Identity::from_pkcs8(cert, key).map_err(|e| { + Error::invalid_argument().message(format!( + "Invalid mTLS client certificate/key in TlsConfig.client_cert_pem/client_key_pem: {e}" + )) + })?); + } + let connector = tls.build().map_err(|e| { + Error::invalid_argument().message(format!("Failed to create HTTP client: {e}")) + })?; + Ok(Some(Self { connector })) + } + + /// `revocation` is the effective mode (Windows only; rejected at open elsewhere). + #[cfg(feature = "tls-rustls")] + fn load(config: &TlsConfig, revocation: Option) -> Result> { + #[cfg(windows)] + if let Some(accept_undetermined) = revocation { + let config = super::tls_revocation::client_config(config, accept_undetermined)?; + return Ok(Some(Self { + system_roots: Vec::new(), + revocation: Some(config), + })); + } + let _ = (config, revocation); + let loaded = rustls_native_certs::load_native_certs(); + let mut store = rustls::RootCertStore::empty(); + let (mut system_roots, mut invalid) = (Vec::new(), 0); + for cert in loaded.certs { + // Like reqwest, skip certificates rustls cannot use as roots. + if store.add(cert.clone()).is_err() { + invalid += 1; + continue; + } + system_roots.push(reqwest::Certificate::from_der(&cert).map_err(|e| { + Error::invalid_argument().message(format!("Failed to create HTTP client: {e}")) + })?); + } + if system_roots.is_empty() && invalid > 0 { + return Err(Error::invalid_argument().message( + "Failed to create HTTP client: zero valid certificates found in native root store", + )); + } + Ok(Some(Self { + system_roots, + #[cfg(windows)] + revocation: None, + })) + } + + fn apply(&self, builder: reqwest::ClientBuilder) -> reqwest::ClientBuilder { + #[cfg(all(windows, feature = "tls-rustls"))] + if let Some(config) = &self.revocation { + return builder.use_preconfigured_tls(config.clone()); + } + #[cfg(feature = "tls-native")] + let builder = builder.use_preconfigured_tls(self.connector.clone()); + #[cfg(feature = "tls-rustls")] + let builder = self.system_roots.iter().cloned().fold( + builder.tls_built_in_native_certs(false), + reqwest::ClientBuilder::add_root_certificate, + ); + builder + } +} + /// HTTP client for communicating with Databricks SQL endpoints. /// /// This client handles: @@ -417,6 +558,11 @@ fn build_mtls_identity(cert_pem: &[u8], key_pem: &[u8]) -> Result>, + /// With Negotiate, the TLS setup shared by every client build. + negotiate_tls: Arc, config: HttpClientConfig, auth_provider: OnceLock>, retry_configs: HashMap, @@ -529,8 +675,13 @@ impl DatabricksHttpClient { let revocation = revocation.filter(|_| config.tls.allow_self_signed != Some(true)); // Follow redirects for normal traffic (reqwest's default policy). - let client = - Self::build_reqwest_client(&config, reqwest::redirect::Policy::default(), revocation)?; + let negotiate_tls = Arc::new(SharedTls::new()); + let client = Self::build_reqwest_client( + &config, + Self::redirect_policy(&config), + revocation, + Self::shared_tls(&config, &negotiate_tls), + )?; // Surface which TLS backend was compiled in so oncall debugging // a handshake / unknown-CA report can tell at a glance whether @@ -550,6 +701,8 @@ impl DatabricksHttpClient { Ok(Self { client, + negotiate_client: std::sync::RwLock::new(None), + negotiate_tls, config, auth_provider: OnceLock::new(), retry_configs, @@ -557,16 +710,37 @@ impl DatabricksHttpClient { }) } + /// [`Self::with_revocation`] for async callers: with Negotiate the first + /// token is created off the async workers (GSSAPI may contact the KDC; a + /// token callback may block). Default proxy auth builds inline. + pub(crate) async fn with_revocation_async( + config: HttpClientConfig, + retry_configs: HashMap, + revocation: Option, + ) -> Result { + if matches!(config.proxy.auth, crate::config::ProxyAuth::Default) { + return Self::with_revocation(config, retry_configs, revocation); + } + tokio::task::spawn_blocking(move || { + Self::with_revocation(config, retry_configs, revocation) + }) + .await + .map_err(|e| Error::internal().message(format!("Negotiate token task failed: {e}")))? + } + /// Build a `reqwest::Client` from `config` with the given redirect policy. /// /// Factored out of `new()` so tenant discovery can obtain a client that /// does NOT follow redirects (to read the first `/aad/auth` hop's /// `Location`) while still honouring the workspace's TLS, proxy, timeout, /// and user-agent configuration. + /// + /// `tls` (Negotiate only) is loaded at the first build and reused after. fn build_reqwest_client( config: &HttpClientConfig, redirect: reqwest::redirect::Policy, revocation: Option, + tls: Option<&SharedTls>, ) -> Result { check_revocation_support(&config.tls, revocation)?; let mut builder = Client::builder() @@ -698,6 +872,15 @@ impl DatabricksHttpClient { (None, None) => {} } + // Negotiate: validated before any I/O; the token is created per + // client build (preemptive) and rides only on the proxy CONNECT. + let negotiate = NegotiateSource::resolve( + config.proxy.url.as_deref(), + config.proxy.username.as_deref(), + config.proxy.password.as_deref(), + &config.proxy.auth, + )?; + // Apply proxy configuration if let Some(ref proxy_url) = config.proxy.url { // Validate proxy URL scheme @@ -713,9 +896,13 @@ impl DatabricksHttpClient { .message(format!("Invalid proxy URL '{}': {}", proxy_url, e)) })?; + if let Some(ref negotiate) = negotiate { + proxy = proxy.custom_http_auth(negotiate.header()?); + debug!("HTTP proxy auth: Negotiate configured ({negotiate:?})"); + } // Add basic auth if credentials provided. // Explicit username/password override any credentials embedded in the URL. - if let Some(ref username) = config.proxy.username { + else if let Some(ref username) = config.proxy.username { if proxy_url.contains('@') { warn!("Proxy URL contains embedded credentials, but explicit username/password are also set; explicit credentials take precedence"); } @@ -756,16 +943,28 @@ impl DatabricksHttpClient { // With revocation on, the verifier replaces reqwest's trust roots and identity. // Those were already validated above. `allow_self_signed` turns revocation off. + // With Negotiate it is part of the reused TLS setup below. + let revocation = revocation.filter(|_| config.tls.allow_self_signed != Some(true)); #[cfg(all(windows, feature = "tls-rustls"))] - if let Some(accept_undetermined) = - revocation.filter(|_| config.tls.allow_self_signed != Some(true)) - { + if let Some(accept_undetermined) = revocation.filter(|_| tls.is_none()) { builder = builder.use_preconfigured_tls(super::tls_revocation::client_config( &config.tls, accept_undetermined, )?); } + // After the token, so a missing ticket still fails fast. + if let Some(shared) = tls { + if shared.get().is_none() { + #[cfg(test)] + TLS_LOADS.lock().unwrap().push(config.proxy.url.clone()); + let _ = shared.set(ReusableTls::load(&config.tls, revocation)?); + } + if let Some(Some(reusable)) = shared.get() { + builder = reusable.apply(builder); + } + } + builder.build().map_err(|e| { Error::invalid_argument().message(format!("Failed to create HTTP client: {e}")) }) @@ -808,6 +1007,132 @@ impl DatabricksHttpClient { &self.client } + /// The client new requests go through: the Negotiate rebuild, if any. + pub(crate) fn current_client(&self) -> Client { + self.negotiate_client + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .unwrap_or_else(|| self.client.clone()) + } + + /// Negotiate clients follow no redirects: [`Self::send_once`] follows + /// them hop by hop so a proxy 407 is retried at the failing hop. + fn redirect_policy(config: &HttpClientConfig) -> reqwest::redirect::Policy { + match config.proxy.auth { + crate::config::ProxyAuth::Default => reqwest::redirect::Policy::default(), + _ => reqwest::redirect::Policy::none(), + } + } + + /// The shared TLS setup to build with: only with Negotiate. + fn shared_tls<'a>(config: &HttpClientConfig, tls: &'a SharedTls) -> Option<&'a SharedTls> { + (!matches!(config.proxy.auth, crate::config::ProxyAuth::Default)).then_some(tls) + } + + /// Rebuild the client with a fresh Negotiate token after a proxy 407. + async fn rebuild_negotiate_client(&self) -> Result { + self.build_negotiate_client(Self::redirect_policy(&self.config)) + .await + } + + /// Build a client with a fresh Negotiate token, off the async workers + /// (GSSAPI may contact the KDC; a token callback may block). It reuses + /// the client's TLS setup, so only the token is new. + async fn build_negotiate_client(&self, redirect: reqwest::redirect::Policy) -> Result { + let (config, tls) = (self.config.clone(), self.negotiate_tls.clone()); + let revocation = self.revocation; + tokio::task::spawn_blocking(move || { + Self::build_reqwest_client(&config, redirect, revocation, Some(&tls)) + }) + .await + .map_err(|e| Error::internal().message(format!("Negotiate token task failed: {e}")))? + } + + /// Send `request` once, without the retry ladder. The outer error is a + /// kernel failure; the inner result is the transport outcome. + /// + /// Without Negotiate this is `execute` on the client. With Negotiate (D3) + /// it follows redirects itself ([`next_redirect`]). A proxy 407 on a + /// hop's `CONNECT` gets one retry of that hop on a client rebuilt with a + /// fresh token, so hops that already reached their server are never + /// resent. A second 407 on the same hop fails closed. + /// + /// Like reqwest's own redirect handling, one deadline (the request's + /// timeout, else the client's) covers every hop, the token rebuild and + /// the final response body: each hop is sent with the remaining time. + pub(crate) async fn send_once( + &self, + request: Request, + ) -> Result> { + let mut client = self.current_client(); + if matches!(self.config.proxy.auth, crate::config::ProxyAuth::Default) { + return Ok(client.execute(request).await); + } + let budget = request + .timeout() + .copied() + .unwrap_or(self.config.read_timeout); + let deadline = tokio::time::Instant::now() + budget; + // An exhausted budget fails the hop with reqwest's own timeout error. + let remaining = || deadline.saturating_duration_since(tokio::time::Instant::now()); + let mut rebuilt = false; + let mut previous = Vec::new(); + let mut hop = request; + loop { + let mut fresh_token = false; + let response = loop { + // A streaming body cannot be resent: one plain attempt. + let Some(mut attempt) = hop.try_clone() else { + *hop.timeout_mut() = Some(remaining()); + return Ok(client.execute(hop).await); + }; + *attempt.timeout_mut() = Some(remaining()); + match client.execute(attempt).await { + Ok(response) => break response, + Err(mut e) if is_proxy_auth_required(&e) => { + if fresh_token { + if let Some(url) = e.url_mut() { + url.set_query(None); + } + let mut causes = super::error_chain(&e) + .map(ToString::to_string) + .collect::>(); + causes.dedup(); + return Err(Error::unauthenticated().message(format!( + "Negotiate proxy authentication failed: the proxy rejected a \ + fresh token (HTTP 407): {}", + causes.join(": ") + ))); + } + debug!("proxy 407; retrying this hop once with a fresh Negotiate token"); + client = tokio::time::timeout(remaining(), self.rebuild_negotiate_client()) + .await + .map_err(|_| { + Error::timeout().message(format!( + "Negotiate proxy authentication timed out: no fresh token \ + within the {budget:?} request timeout" + )) + })??; + (rebuilt, fresh_token) = (true, true); + } + Err(e) => return Ok(Err(e)), + } + }; + if rebuilt { + // Its tunnel is up: later requests reuse its pool. + *self + .negotiate_client + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(client.clone()); + } + match next_redirect(&hop, &response, &mut previous)? { + Some(next) => hop = next, + None => return Ok(Ok(response)), + } + } + } + /// Get the authorization header value. /// /// Returns an error if the auth provider has not been set via `set_auth_provider()`. @@ -877,11 +1202,12 @@ impl DatabricksHttpClient { /// `azure_tenant_id` (which skips discovery entirely). A single hop is /// sufficient for discovery, so no retry is attempted here. pub async fn first_redirect_location(&self, url: &str) -> Result> { - let client = Self::build_reqwest_client( - &self.config, - reqwest::redirect::Policy::none(), - self.revocation, - )?; + let redirect = reqwest::redirect::Policy::none(); + let client = if matches!(self.config.proxy.auth, crate::config::ProxyAuth::Default) { + Self::build_reqwest_client(&self.config, redirect, self.revocation, None)? + } else { + self.build_negotiate_client(redirect).await? + }; let response = client.get(url).send().await.map_err(|e| { Error::network_error().message(format!("Redirect-probe request to {url} failed: {e}")) })?; @@ -920,7 +1246,6 @@ impl DatabricksHttpClient { .body() .and_then(|b| b.as_bytes()) .map(|b| b.to_vec()); - loop { attempts += 1; @@ -1016,7 +1341,8 @@ impl DatabricksHttpClient { max_attempts ); - match self.client.execute(request).await { + // Negotiate's proxy 407 retry happens per hop inside `send_once`. + match self.send_once(request).await? { Ok(response) => { let status = response.status(); @@ -1196,6 +1522,10 @@ mod revocation_support_tests { } } +#[cfg(test)] +#[path = "http_negotiate_tests.rs"] +mod negotiate_tests; + #[cfg(test)] mod tests { use super::*; @@ -1933,6 +2263,7 @@ lGrv15pBcePj username: Some("user".to_string()), password: Some("secret123".to_string()), bypass_hosts: None, + ..Default::default() }; let debug_output = format!("{:?}", config); assert!(debug_output.contains("[REDACTED]")); diff --git a/src/client/http_negotiate_tests.rs b/src/client/http_negotiate_tests.rs new file mode 100644 index 00000000..e8cc7688 --- /dev/null +++ b/src/client/http_negotiate_tests.rs @@ -0,0 +1,1164 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Negotiate proxy auth against a stub `CONNECT` proxy that, like a Kerberos +//! acceptor with a replay cache, rejects any token it has already seen +//! (`407 Negotiate, Basic`). The stub terminates the tunnel with its own TLS +//! origin. No KDC needed; `tests/proxy_negotiate_kdc.rs` covers real tokens. + +use super::*; +use crate::auth::PersonalAccessToken; +use crate::config::{NegotiateTokenCallback, ProxyAuth}; +use crate::kernel_error::ErrorCode; +use std::collections::HashSet; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Mutex; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; +use tokio::net::TcpListener; + +#[derive(Default)] +struct Seen { + /// (`Proxy-Authorization` of each CONNECT, status the proxy answered). + connects: Vec<(Option, u16)>, + tokens: HashSet, + /// Header names of requests that came through a tunnel. + origin_headers: Vec, + /// ` ` and header names of each tunnelled request. + requests: Vec<(String, Vec)>, +} + +struct StubProxy { + url: String, + seen: Arc>, +} + +async fn read_head(stream: &mut S) -> Option { + let mut head = Vec::new(); + let mut byte = [0_u8; 1]; + while !head.ends_with(b"\r\n\r\n") { + if stream.read(&mut byte).await.ok()? == 0 { + return None; + } + head.push(byte[0]); + } + Some(String::from_utf8_lossy(&head).into_owned()) +} + +fn header<'a>(head: &'a str, name: &str) -> Option<&'a str> { + head.lines().find_map(|line| { + let (n, v) = line.split_once(':')?; + n.eq_ignore_ascii_case(name).then(|| v.trim()) + }) +} + +async fn serve_origin( + mut stream: S, + seen: Arc>, + delay: Duration, +) { + while let Some(head) = read_head(&mut stream).await { + let names = head + .lines() + .skip(1) + .filter_map(|l| l.split_once(':').map(|(n, _)| n.to_ascii_lowercase())) + .collect::>(); + let mut line = head.lines().next().unwrap_or_default().split(' '); + let (method, path) = ( + line.next().unwrap_or_default(), + line.next().unwrap_or_default(), + ); + let length = header(&head, "content-length").map_or(0, |v| v.parse().unwrap()); + let mut body = vec![0_u8; length]; + if stream.read_exact(&mut body).await.is_err() { + return; + } + { + let mut seen = seen.lock().unwrap(); + seen.origin_headers.extend(names.clone()); + seen.requests.push((format!("{method} {path}"), names)); + } + tokio::time::sleep(delay).await; + if path == "/slowbody" { + // Headers now, the body one more `delay` later. + let head = b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n"; + if stream.write_all(head).await.is_err() || stream.flush().await.is_err() { + return; + } + tokio::time::sleep(delay).await; + if stream.write_all(b"ok").await.is_err() { + return; + } + continue; + } + let reply = match path { + "/rbody" => "HTTP/1.1 307 Redirect\r\nLocation: https://other.test/slowbody\r\n\ + Content-Length: 0\r\n\r\n" + .to_string(), + "/loop" => { + "HTTP/1.1 302 Found\r\nLocation: /loop\r\nContent-Length: 0\r\n\r\n".to_string() + } + // `/r` redirects to another origin, so another tunnel. + redirect if redirect.starts_with("/r") => format!( + "HTTP/1.1 {} Redirect\r\nLocation: https://other.test/final\r\n\ + Content-Length: 0\r\n\r\n", + &redirect[2..] + ), + "/oidc/v1/token" => { + let token = r#"{"access_token":"at","token_type":"Bearer","expires_in":3600}"#; + format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\ + Content-Length: {}\r\n\r\n{token}", + token.len() + ) + } + _ => "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok".to_string(), + }; + if stream.write_all(reply.as_bytes()).await.is_err() { + return; + } + } +} + +fn tls_acceptor() -> tokio_rustls::TlsAcceptor { + let key = rcgen::KeyPair::generate().unwrap(); + let cert = rcgen::CertificateParams::new(vec!["127.0.0.1".to_string()]) + .unwrap() + .self_signed(&key) + .unwrap(); + let tls = rustls::ServerConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_safe_default_protocol_versions() + .unwrap() + .with_no_client_auth() + .with_single_cert( + vec![cert.der().clone()], + rustls::pki_types::PrivatePkcs8KeyDer::from(key.serialize_der()).into(), + ) + .unwrap(); + tokio_rustls::TlsAcceptor::from(Arc::new(tls)) +} + +impl StubProxy { + /// `reject_all`: answer every CONNECT with 407. `delay`: origin latency. + async fn start(reject_all: bool, delay: Duration) -> Self { + let acceptor = tls_acceptor(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let seen = Arc::new(Mutex::new(Seen::default())); + let state = seen.clone(); + tokio::spawn(async move { + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + let (acceptor, seen) = (acceptor.clone(), state.clone()); + tokio::spawn(async move { + let Some(head) = read_head(&mut socket).await else { + return; + }; + let auth = header(&head, "proxy-authorization").map(str::to_string); + let fresh = { + let mut seen = seen.lock().unwrap(); + let token = auth.as_deref().and_then(|a| a.strip_prefix("Negotiate ")); + let fresh = + !reject_all && token.is_some_and(|t| seen.tokens.insert(t.to_string())); + seen.connects.push((auth, if fresh { 200 } else { 407 })); + fresh + }; + if !fresh { + let reply = "HTTP/1.1 407 Proxy Authentication Required\r\n\ + Proxy-Authenticate: Negotiate\r\n\ + Proxy-Authenticate: Basic realm=\"stub\"\r\n\ + Content-Length: 0\r\n\r\n"; + let _ = socket.write_all(reply.as_bytes()).await; + return; + } + let established = b"HTTP/1.1 200 Connection established\r\n\r\n"; + if socket.write_all(established).await.is_ok() { + if let Ok(tls) = acceptor.accept(socket).await { + serve_origin(tls, seen, delay).await; + } + } + }); + } + }); + Self { url, seen } + } +} + +/// A directly reachable origin that counts connections: any direct +/// (non-proxied) attempt would land here. +async fn direct_origin() -> (String, Arc) { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("https://{}/probe", listener.local_addr().unwrap()); + let hits = Arc::new(AtomicUsize::new(0)); + let counter = hits.clone(); + tokio::spawn(async move { + while listener.accept().await.is_ok() { + counter.fetch_add(1, Ordering::SeqCst); + } + }); + (url, hits) +} + +/// Client whose token callback yields `tok-1`, `tok-2`, ... (or fails). +fn client(proxy: &StubProxy, calls: &Arc, fail: bool) -> Result { + slow_token_client(proxy, calls, fail, Duration::ZERO) +} + +/// As [`client`], but every token after the first takes `slow` to create. +fn slow_token_client( + proxy: &StubProxy, + calls: &Arc, + fail: bool, + slow: Duration, +) -> Result { + let calls = calls.clone(); + let callback = NegotiateTokenCallback::new(move || { + let n = calls.fetch_add(1, Ordering::SeqCst) + 1; + if fail { + return Err("no Kerberos credentials".to_string()); + } + if n > 1 { + std::thread::sleep(slow); + } + Ok(format!("tok-{n}").into_bytes()) + }); + let mut config = HttpClientConfig::default(); + config.proxy.url = Some(proxy.url.clone()); + config.proxy.auth = ProxyAuth::NegotiateCallback(callback); + config.tls.allow_self_signed = Some(true); + config.tls.allow_hostname_mismatch = Some(true); + let client = DatabricksHttpClient::with_default_retry(config)?; + client.set_auth_provider(Arc::new(PersonalAccessToken::new("pat".to_string()))); + Ok(client) +} + +async fn get(client: &DatabricksHttpClient, url: &str) -> Result { + let request = client.inner().get(url).build().unwrap(); + let response = client + .execute(request, RequestType::GetStatementStatus) + .await?; + Ok(response.status().as_u16()) +} + +fn assert_negotiate_only(seen: &Seen) { + for (auth, _) in &seen.connects { + let auth = auth.as_deref().unwrap_or_default(); + assert!( + auth.starts_with("Negotiate "), + "non-Negotiate CONNECT: {auth:?}" + ); + } + assert!( + !seen + .origin_headers + .iter() + .any(|h| h == "proxy-authorization"), + "Proxy-Authorization reached the origin" + ); +} + +#[tokio::test] +async fn negotiate_token_is_preemptive_and_only_on_connect() { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let (origin, direct_hits) = direct_origin().await; + let calls = Arc::new(AtomicUsize::new(0)); + let client = client(&proxy, &calls, false).unwrap(); + for _ in 0..3 { + assert_eq!(get(&client, &origin).await.unwrap(), 200); + } + let seen = proxy.seen.lock().unwrap(); + // One token at client build, one tunnel reused by the pool. + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert_eq!( + seen.connects, + vec![(Some("Negotiate dG9rLTE=".to_string()), 200)] + ); + assert!(seen.origin_headers.iter().any(|h| h == "authorization")); + assert_negotiate_only(&seen); + assert_eq!(direct_hits.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn negotiate_survives_a_replay_cache_across_tunnels() { + let proxy = StubProxy::start(false, Duration::from_millis(200)).await; + let (origin, direct_hits) = direct_origin().await; + let calls = Arc::new(AtomicUsize::new(0)); + + // Sequential sessions: each client build mints its own token. + for _ in 0..6 { + let client = client(&proxy, &calls, false).unwrap(); + assert_eq!(get(&client, &origin).await.unwrap(), 200); + } + // Concurrent tunnels within one client: every new tunnel after the first + // replays the client's token, gets 407 and retries once with a new one. + let client = client(&proxy, &calls, false).unwrap(); + let results = futures::future::join_all((0..6).map(|_| get(&client, &origin))).await; + for result in results { + assert_eq!(result.unwrap(), 200); + } + // A second wave goes through the promoted rebuilt client the same way. + let results = futures::future::join_all((0..6).map(|_| get(&client, &origin))).await; + assert!(results.into_iter().all(|r| r.unwrap() == 200)); + + let seen = proxy.seen.lock().unwrap(); + assert_negotiate_only(&seen); + let rejected = seen.connects.iter().filter(|(_, s)| *s == 407).count(); + let accepted = seen.connects.len() - rejected; + // At least 4 concurrent tunnels beyond the 6 sequential sessions, and + // every token was used for exactly one accepted tunnel: 7 preemptive + // ones plus one regenerated token per 407 (so at most one 407 each). + assert!(accepted >= 6 + 4, "accepted {accepted}"); + assert_eq!( + accepted, + 7 + rejected, + "accepted {accepted}, rejected {rejected}" + ); + assert_eq!(calls.load(Ordering::SeqCst), accepted); + assert_eq!(direct_hits.load(Ordering::SeqCst), 0); + // Each of the 7 clients loaded its TLS setup once; its rebuilds reused it. + assert_eq!(tls_loads(&proxy.url), 7, "{rejected} rebuilds"); +} + +/// How many clients behind `proxy_url` loaded a [`ReusableTls`]. +fn tls_loads(proxy_url: &str) -> usize { + let loads = TLS_LOADS.lock().unwrap(); + loads + .iter() + .filter(|u| u.as_deref() == Some(proxy_url)) + .count() +} + +#[tokio::test] +async fn negotiate_second_407_fails_closed_without_downgrade() { + let proxy = StubProxy::start(true, Duration::ZERO).await; + let (origin, direct_hits) = direct_origin().await; + let calls = Arc::new(AtomicUsize::new(0)); + let client = client(&proxy, &calls, false).unwrap(); + let err = get(&client, &origin).await.unwrap_err(); + assert_eq!(err.code, ErrorCode::Unauthenticated, "{}", err.message); + assert!(!err.retryable); + assert!(err.message.contains("407"), "{}", err.message); + assert!( + !err.message.contains("dG9r"), + "token bytes in error: {}", + err.message + ); + let seen = proxy.seen.lock().unwrap(); + // Preemptive token, one regenerated token, then stop: no Basic, no + // direct connection, no generic retries. + assert_eq!(seen.connects.len(), 2); + assert_eq!(calls.load(Ordering::SeqCst), 2); + assert_negotiate_only(&seen); + assert_eq!(direct_hits.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn negotiate_token_failure_fails_before_any_io() { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let calls = Arc::new(AtomicUsize::new(0)); + let err = client(&proxy, &calls, true).unwrap_err(); + assert_eq!(err.code, ErrorCode::Unauthenticated); + assert!( + err.message.contains("no Kerberos credentials"), + "{}", + err.message + ); + assert!(proxy.seen.lock().unwrap().connects.is_empty()); +} + +/// A slow first token (session open) or redirect-probe token is created off +/// the async workers: on a single-threaded runtime an unrelated timer still +/// fires while the callback blocks, and the failure still fails closed. +#[tokio::test(flavor = "current_thread")] +async fn negotiate_slow_token_does_not_block_async_workers() { + // (case, the token call that is slow and then fails) + let cases = [("session open", 1), ("redirect probe", 2)]; + for (case, slow_call) in cases { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let calls = Arc::new(AtomicUsize::new(0)); + let ticked = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let ticked_during_token = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let callback = { + let (calls, ticked) = (calls.clone(), ticked.clone()); + let during = ticked_during_token.clone(); + NegotiateTokenCallback::new(move || { + let n = calls.fetch_add(1, Ordering::SeqCst) + 1; + if n != slow_call { + return Ok(format!("tok-{n}").into_bytes()); + } + std::thread::sleep(Duration::from_millis(500)); + during.store(ticked.load(Ordering::SeqCst), Ordering::SeqCst); + Err("no Kerberos credentials".to_string()) + }) + }; + let proxy_config = crate::config::ProxyConfig { + url: Some(proxy.url.clone()), + auth: ProxyAuth::NegotiateCallback(callback), + ..Default::default() + }; + // The probe case builds its client (fast first token) up front. + let probe_client = (case == "redirect probe").then(|| { + let mut config = HttpClientConfig::default(); + config.proxy.url = proxy_config.url.clone(); + config.proxy.auth = proxy_config.auth.clone(); + DatabricksHttpClient::with_default_retry(config).unwrap() + }); + + let ticker = { + let ticked = ticked.clone(); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(20)).await; + ticked.store(true, Ordering::SeqCst); + }) + }; + let err = match probe_client { + None => crate::session::Session::builder() + .connection(crate::config::ConnectionConfig::new( + "https://workspace.invalid", + "test_wh", + )) + .auth(crate::config::AuthConfig::Pat { + token: "dapi-test".to_string(), + identity_federation_client_id: None, + }) + .proxy(proxy_config) + .open() + .await + .map(|_| ()) + .unwrap_err(), + Some(client) => client + .first_redirect_location("https://workspace.invalid/aad/auth") + .await + .unwrap_err(), + }; + ticker.await.unwrap(); + + assert!( + ticked_during_token.load(Ordering::SeqCst), + "{case}: the timer could not fire while the token was created" + ); + assert_eq!(calls.load(Ordering::SeqCst), slow_call, "{case}"); + assert_eq!( + err.code, + ErrorCode::Unauthenticated, + "{case}: {}", + err.message + ); + assert!( + err.message.contains("no Kerberos credentials"), + "{case}: {}", + err.message + ); + assert!(proxy.seen.lock().unwrap().connects.is_empty(), "{case}"); + } +} + +/// The CONNECTs of a request whose second tunnel replayed the first token. +/// (`tok-1` accepted, `tok-1` replayed, `tok-2` accepted.) +fn one_replay_407() -> Vec<(Option, u16)> { + let tok = |n: &str| Some(format!("Negotiate {n}")); + vec![ + (tok("dG9rLTE="), 200), + (tok("dG9rLTE="), 407), + (tok("dG9rLTI="), 200), + ] +} + +#[tokio::test] +async fn negotiate_redirect_retries_only_the_failed_hop() { + // A cross-origin redirect opens a second tunnel, which replays the + // spent token: only that hop is retried, the origin request is not. + let cases = [ + ("POST", "/r307", "POST /final"), + ("POST", "/r308", "POST /final"), + ("POST", "/r302", "GET /final"), + ("GET", "/r303", "GET /final"), + ]; + for (verb, path, final_hop) in cases { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let (_, direct_hits) = direct_origin().await; + let calls = Arc::new(AtomicUsize::new(0)); + let client = client(&proxy, &calls, false).unwrap(); + let request = client + .inner() + .request(verb.parse().unwrap(), format!("https://origin.test{path}")) + .body("{}") + .build() + .unwrap(); + let response = client + .execute(request, RequestType::ExecuteStatement) + .await + .unwrap_or_else(|e| panic!("{path}: {e}")); + assert_eq!(response.status().as_u16(), 200, "{path}"); + + let seen = proxy.seen.lock().unwrap(); + let hops = seen + .requests + .iter() + .map(|(r, _)| r.as_str()) + .collect::>(); + assert_eq!( + hops, + [format!("{verb} {path}").as_str(), final_hop], + "{path}" + ); + // Cross-origin hop: reqwest's rule drops the bearer token. + assert!(seen.requests[0].1.iter().any(|h| h == "authorization")); + assert!(!seen.requests[1].1.iter().any(|h| h == "authorization")); + assert_eq!(seen.connects, one_replay_407(), "{path}"); + assert_eq!(calls.load(Ordering::SeqCst), 2, "{path}"); + assert_negotiate_only(&seen); + assert_eq!(direct_hits.load(Ordering::SeqCst), 0); + } +} + +#[tokio::test] +async fn negotiate_redirects_stop_after_ten_hops() { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let calls = Arc::new(AtomicUsize::new(0)); + let client = client(&proxy, &calls, false).unwrap(); + let err = get(&client, "https://origin.test/loop").await.unwrap_err(); + assert_eq!(err.code, ErrorCode::NetworkError, "{}", err.message); + assert!( + err.message.contains("too many redirects"), + "{}", + err.message + ); + let seen = proxy.seen.lock().unwrap(); + // The original request plus 10 redirects, as reqwest's default policy. + assert_eq!(seen.requests.len(), 11); + assert_eq!(seen.connects.len(), 1, "same origin: one tunnel"); +} + +#[tokio::test] +async fn negotiate_deadline_spans_redirects_token_and_body() { + // One request timeout covers every hop, the fresh-token rebuild after + // the cross-origin hop's 407, and the final body (as reqwest does for + // the redirects it follows itself). Each case would succeed if every + // hop restarted the timeout. + let ms = Duration::from_millis; + let cases = [ + // (name, path, origin delay, token delay, timeout, origin hops) + ("delayed redirect", "/r307", ms(500), ms(0), ms(800), 2), + ("delayed body", "/rbody", ms(400), ms(0), ms(1000), 2), + ("slow fresh token", "/r307", ms(0), ms(1500), ms(500), 1), + ]; + for (name, path, delay, slow, timeout, hops) in cases { + let proxy = StubProxy::start(false, delay).await; + let calls = Arc::new(AtomicUsize::new(0)); + let client = slow_token_client(&proxy, &calls, false, slow).unwrap(); + let request = client + .inner() + .post(format!("https://origin.test{path}")) + .body("{}") + .timeout(timeout) + .build() + .unwrap(); + let started = tokio::time::Instant::now(); + let outcome = match client.send_once(request).await { + Ok(Ok(response)) => response.bytes().await.map(|_| ()).map_err(|e| { + assert!(e.is_timeout(), "{name}: {e}"); + "body timed out".to_string() + }), + Ok(Err(e)) => { + assert!(e.is_timeout(), "{name}: {e}"); + Err("hop timed out".to_string()) + } + Err(e) => { + assert_eq!(e.code, ErrorCode::Timeout, "{name}: {}", e.message); + assert!(e.message.contains("fresh token"), "{name}: {}", e.message); + Err("token timed out".to_string()) + } + }; + let elapsed = started.elapsed(); + assert!(outcome.is_err(), "{name}: completed in {elapsed:?}"); + assert!(elapsed < timeout + ms(300), "{name}: took {elapsed:?}"); + let seen = proxy.seen.lock().unwrap(); + assert_eq!(seen.requests.len(), hops, "{name}: {:?}", seen.requests); + assert_eq!(seen.connects[..2], one_replay_407()[..2], "{name}"); + assert_negotiate_only(&seen); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn negotiate_u2m_token_requests_regenerate_on_a_new_tunnel() { + use crate::auth::oauth::u2m::send_token_request; + use oauth2::basic::BasicClient; + use oauth2::{AuthUrl, AuthorizationCode, ClientId, RefreshToken, TokenResponse, TokenUrl}; + + // The token endpoint is another origin, so each grant opens a new tunnel + // after the client's token was spent on the first one. + let cases = ["refresh", "code"]; + for grant in cases { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let calls = Arc::new(AtomicUsize::new(0)); + let client = client(&proxy, &calls, false).unwrap(); + assert_eq!( + get(&client, "https://origin.test/probe").await.unwrap(), + 200 + ); + + let oauth = BasicClient::new(ClientId::new("databricks-sql-connector".to_string())) + .set_auth_uri(AuthUrl::new("https://idp.test/oidc/v1/authorize".to_string()).unwrap()) + .set_token_uri(TokenUrl::new("https://idp.test/oidc/v1/token".to_string()).unwrap()); + let send = |request| send_token_request(&client, request); + let token = match grant { + "refresh" => oauth + .exchange_refresh_token(&RefreshToken::new("rt".to_string())) + .request_async(&send) + .await + .map(|t| t.access_token().secret().clone()), + _ => oauth + .exchange_code(AuthorizationCode::new("code".to_string())) + .request_async(&send) + .await + .map(|t| t.access_token().secret().clone()), + }; + assert_eq!(token.unwrap_or_else(|e| panic!("{grant}: {e:?}")), "at"); + + let seen = proxy.seen.lock().unwrap(); + assert_eq!(seen.connects, one_replay_407(), "{grant}"); + let hops = seen + .requests + .iter() + .map(|(r, _)| r.as_str()) + .collect::>(); + assert_eq!(hops, ["GET /probe", "POST /oidc/v1/token"], "{grant}"); + assert_negotiate_only(&seen); + } +} + +/// Records each ClientHello (SNI, ALPN, cipher suites, signature schemes). +#[derive(Debug)] +struct HelloRecorder { + key: Arc, + seen: Arc>, +} + +impl rustls::server::ResolvesServerCert for HelloRecorder { + fn resolve( + &self, + hello: rustls::server::ClientHello<'_>, + ) -> Option> { + let alpn = hello + .alpn() + .map(|a| a.map(<[u8]>::to_vec).collect::>()); + self.seen.lock().unwrap().hellos.push(format!( + "sni {:?} alpn {alpn:?} suites {:?} schemes {:?}", + hello.server_name(), + hello.cipher_suites(), + hello.signature_schemes() + )); + Some(self.key.clone()) + } +} + +/// What a TLS origin behind a CONNECT proxy saw. +#[derive(Default, Debug, PartialEq)] +struct TlsSeen { + hellos: Vec, + /// Protocol version and whether a client certificate was presented. + sessions: Vec, + connects: Vec<(Option, u16)>, +} + +/// A CONNECT proxy that accepts unauthenticated CONNECTs (`Default`) and +/// fresh Negotiate tokens, except `tok-1` when `spend_first` (so the client +/// rebuilds), in front of a TLS origin with `cert` that asks for an optional +/// client certificate from `ca`. +async fn tls_probe_proxy( + cert: &rcgen::Certificate, + key: &rcgen::KeyPair, + ca: &rcgen::Certificate, + spend_first: bool, +) -> (String, Arc>) { + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let signer = provider + .key_provider + .load_private_key(rustls::pki_types::PrivatePkcs8KeyDer::from(key.serialize_der()).into()) + .unwrap(); + let mut roots = rustls::RootCertStore::empty(); + roots.add(ca.der().clone()).unwrap(); + let verifier = rustls::server::WebPkiClientVerifier::builder_with_provider( + Arc::new(roots), + provider.clone(), + ) + .allow_unauthenticated() + .build() + .unwrap(); + let seen = Arc::new(Mutex::new(TlsSeen::default())); + let server = rustls::ServerConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .unwrap() + .with_client_cert_verifier(verifier) + .with_cert_resolver(Arc::new(HelloRecorder { + key: Arc::new(rustls::sign::CertifiedKey::new( + vec![cert.der().clone()], + signer, + )), + seen: seen.clone(), + })); + let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(server)); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let state = seen.clone(); + let spent = spend_first.then(|| "dG9rLTE=".to_string()); + let tokens = Arc::new(Mutex::new(spent.into_iter().collect::>())); + tokio::spawn(async move { + loop { + let (mut socket, _) = listener.accept().await.unwrap(); + let (acceptor, seen, tokens) = (acceptor.clone(), state.clone(), tokens.clone()); + tokio::spawn(async move { + let Some(head) = read_head(&mut socket).await else { + return; + }; + let auth = header(&head, "proxy-authorization").map(str::to_string); + let open = match auth.as_deref().and_then(|a| a.strip_prefix("Negotiate ")) { + Some(token) => tokens.lock().unwrap().insert(token.to_string()), + None => auth.is_none(), + }; + seen.lock() + .unwrap() + .connects + .push((auth, if open { 200 } else { 407 })); + if !open { + let reply = "HTTP/1.1 407 Proxy Authentication Required\r\n\ + Proxy-Authenticate: Negotiate\r\nContent-Length: 0\r\n\r\n"; + let _ = socket.write_all(reply.as_bytes()).await; + return; + } + let _ = socket + .write_all(b"HTTP/1.1 200 Connection established\r\n\r\n") + .await; + let Ok(tls) = acceptor.accept(socket).await else { + return; + }; + let session = tls.get_ref().1; + seen.lock().unwrap().sessions.push(format!( + "{:?} client cert {}", + session.protocol_version(), + session.peer_certificates().is_some() + )); + serve_origin(tls, Arc::new(Mutex::new(Seen::default())), Duration::ZERO).await; + }); + } + }); + (url, seen) +} + +#[tokio::test] +async fn negotiate_rebuild_keeps_the_tls_behavior() { + use rcgen::{BasicConstraints, CertificateParams, IsCa, Issuer, KeyPair}; + + // Per TLS setting, a Default-auth client (reqwest's own TLS setup), a + // Negotiate client and a Negotiate client rebuilt after a 407 (both on + // the reused setup) get the same outcome, offer the same ClientHello, + // negotiate the same version and present the same client certificate. + let mut ca_params = CertificateParams::new(Vec::new()).unwrap(); + ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); + (ca_params.distinguished_name).push(rcgen::DnType::CommonName, "Negotiate test CA"); + let ca_key = KeyPair::generate().unwrap(); + let ca = ca_params.self_signed(&ca_key).unwrap(); + let issuer = Issuer::new(ca_params, ca_key); + let leaf = |name: &str, expired: bool| { + let mut params = CertificateParams::new(vec![name.to_string()]).unwrap(); + (params.distinguished_name).push(rcgen::DnType::CommonName, name); + if expired { + params.not_before = rcgen::date_time_ymd(2000, 1, 1); + params.not_after = rcgen::date_time_ymd(2001, 1, 1); + } + let key = KeyPair::generate().unwrap(); + (params.signed_by(&key, &issuer).unwrap(), key) + }; + let self_signed = || { + let key = KeyPair::generate().unwrap(); + let params = CertificateParams::new(vec!["127.0.0.1".to_string()]).unwrap(); + (params.self_signed(&key).unwrap(), key) + }; + let (client_cert, client_key) = leaf("client", false); + let trust = TlsConfig { + trusted_certificate_pem: Some(ca.pem().into_bytes()), + ..TlsConfig::default() + }; + let cases = [ + // (name, server certificate, client TLS config, succeeds) + ("custom CA", leaf("127.0.0.1", false), trust.clone(), true), + ( + "unknown CA", + leaf("127.0.0.1", false), + TlsConfig::default(), + false, + ), + ( + "hostname mismatch", + leaf("wrong.invalid", false), + trust.clone(), + false, + ), + ( + "hostname mismatch allowed", + leaf("wrong.invalid", false), + TlsConfig { + allow_hostname_mismatch: Some(true), + ..trust.clone() + }, + true, + ), + ("expired", leaf("127.0.0.1", true), trust.clone(), false), + ("self-signed", self_signed(), trust.clone(), false), + ( + "self-signed allowed", + self_signed(), + TlsConfig { + allow_self_signed: Some(true), + ..TlsConfig::default() + }, + true, + ), + ( + "mTLS identity", + leaf("127.0.0.1", false), + TlsConfig { + client_cert_pem: Some(client_cert.pem().into_bytes()), + client_key_pem: Some(client_key.serialize_pem().into_bytes()), + ..trust.clone() + }, + true, + ), + ]; + for (name, (cert, key), tls, succeeds) in cases { + let mut runs = Vec::new(); + for via in ["default", "negotiate", "rebuilt"] { + let (url, seen) = tls_probe_proxy(&cert, &key, &ca, via == "rebuilt").await; + let mut config = HttpClientConfig::default(); + config.proxy.url = Some(url.clone()); + config.tls = tls.clone(); + if via != "default" { + let calls = AtomicUsize::new(0); + config.proxy.auth = + ProxyAuth::NegotiateCallback(NegotiateTokenCallback::new(move || { + Ok(format!("tok-{}", calls.fetch_add(1, Ordering::SeqCst) + 1).into()) + })); + } + let client = DatabricksHttpClient::with_default_retry(config).unwrap(); + let request = client + .inner() + .get("https://127.0.0.1/probe") + .build() + .unwrap(); + let outcome = match client.send_once(request).await.unwrap() { + Ok(response) => Ok(response.status().as_u16()), + // Digits masked: rustls's expiry error names the current second. + Err(e) => Err(crate::client::error_chain(&e) + .map(ToString::to_string) + .collect::>() + .join(": ") + .replace(|c: char| c.is_ascii_digit(), "#")), + }; + assert_eq!(outcome.is_ok(), succeeds, "{name} via {via}: {outcome:?}"); + let mut seen = std::mem::take(&mut *seen.lock().unwrap()); + let connects = std::mem::take(&mut seen.connects); + let expected = match via { + "default" => vec![(None, 200)], + "negotiate" => vec![(Some("Negotiate dG9rLTE=".to_string()), 200)], + _ => one_replay_407()[1..].to_vec(), + }; + assert_eq!(connects, expected, "{name} via {via}"); + let loads = if via == "default" { 0 } else { 1 }; + assert_eq!(tls_loads(&url), loads, "{name} via {via}"); + assert!(!seen.hellos.is_empty(), "{name} via {via}"); + runs.push((via, outcome, seen)); + } + let (_, outcome, seen) = &runs[0]; + for (via, other_outcome, other_seen) in &runs[1..] { + assert_eq!(other_outcome, outcome, "{name}: {via} vs default"); + assert_eq!(other_seen, seen, "{name}: {via} vs default"); + } + if name == "mTLS identity" { + assert!(seen.sessions[0].ends_with("client cert true"), "{seen:?}"); + } + } +} + +/// The native-tls setup is reused only when OpenSSL reads the same custom +/// CA certificates as reqwest (which skips non-`CERTIFICATE` PEM labels). +#[cfg(feature = "tls-native")] +#[test] +fn reusable_tls_keeps_reqwest_setup_when_parsers_disagree() { + let key = rcgen::KeyPair::generate().unwrap(); + let ca = rcgen::CertificateParams::new(vec!["ca.test".to_string()]) + .unwrap() + .self_signed(&key) + .unwrap() + .pem(); + let relabelled = ca.replace("CERTIFICATE-----", "X509 CERTIFICATE-----"); + let cases = [ + ("one certificate", ca.clone(), true), + ("two certificates", format!("{ca}{ca}"), true), + ("X509 CERTIFICATE label", format!("{ca}{relabelled}"), false), + ]; + for (name, pem, reused) in cases { + let config = TlsConfig { + trusted_certificate_pem: Some(pem.into_bytes()), + ..TlsConfig::default() + }; + let tls = ReusableTls::load(&config, None).unwrap(); + assert_eq!(tls.is_some(), reused, "{name}"); + } +} + +/// Real tokens: MIT KDC + squid `negotiate_kerberos_auth` (replay cache on) +/// from `ci/proxy/negotiate/start.sh`, in front of a local TLS origin. +#[cfg(feature = "proxy-negotiate")] +mod kdc { + use super::*; + use std::time::Instant; + + fn env(name: &str) -> String { + std::env::var(name).unwrap_or_else(|_| panic!("{name} not set: source the fixture env")) + } + + fn log_len(path: &str) -> usize { + std::fs::metadata(path).map_or(0, |m| m.len() as usize) + } + + /// Lines squid appended to its access log after `from` bytes. + fn log_since(path: &str, from: usize) -> Vec { + let log = std::fs::read_to_string(path).unwrap_or_default(); + log[from.min(log.len())..] + .lines() + .map(str::to_string) + .collect() + } + + async fn settled_log(path: &str, from: usize) -> Vec { + // squid writes the access log asynchronously. + tokio::time::sleep(Duration::from_millis(500)).await; + log_since(path, from) + } + + fn kerberos(proxy_url: &str, host: Option<&str>, service: Option<&str>) -> HttpClientConfig { + let mut config = HttpClientConfig::default(); + config.proxy.url = Some(proxy_url.to_string()); + config.proxy.auth = ProxyAuth::Negotiate { + service: service.map(str::to_string), + host: host.map(str::to_string), + realm: None, + }; + config.tls.allow_self_signed = Some(true); + config.tls.allow_hostname_mismatch = Some(true); + config + } + + fn build(config: HttpClientConfig) -> Result { + let client = DatabricksHttpClient::with_default_retry(config)?; + client.set_auth_provider(Arc::new(PersonalAccessToken::new("pat".to_string()))); + Ok(client) + } + + /// Captures every log line at TRACE (kernel `tracing` plus reqwest / + /// hyper `log` records) to prove no token bytes are logged. + fn capture_logs() -> Arc>> { + #[derive(Clone)] + struct Sink(Arc>>); + impl std::io::Write for Sink { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let buffer = Arc::new(Mutex::new(Vec::new())); + let sink = Sink(buffer.clone()); + tracing_subscriber::fmt() + .with_max_level(tracing::Level::TRACE) + .with_writer(move || sink.clone()) + .try_init() + .expect("first subscriber in this test process"); + buffer + } + + fn has_token_bytes(text: &str) -> bool { + text.match_indices("Negotiate ").any(|(i, m)| { + let rest = &text[i + m.len()..]; + rest.chars() + .take_while(|c| c.is_ascii_alphanumeric() || "+/=".contains(*c)) + .count() + >= 16 + }) + } + + #[tokio::test(flavor = "multi_thread")] + #[ignore = "needs the ci/proxy/negotiate fixture: source DIR/env"] + async fn negotiate_through_kerberos_squid() { + let logs = capture_logs(); + let dir = env("NEGOTIATE_FIXTURE_DIR"); + let proxy = env("NEGOTIATE_PROXY_URL"); + let access_log = env("NEGOTIATE_PROXY_ACCESS_LOG"); + let realm = env("NEGOTIATE_REALM"); + // The proxy listens on 127.0.0.1; its service principal is + // HTTP/localhost, so an IP proxy URL needs the host override. + let proxy_ip = proxy.replace("localhost", "127.0.0.1"); + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("https://{}/probe", listener.local_addr().unwrap()); + let seen = Arc::new(Mutex::new(Seen::default())); + let (acceptor, state) = (tls_acceptor(), seen.clone()); + tokio::spawn(async move { + while let Ok((socket, _)) = listener.accept().await { + let (acceptor, seen) = (acceptor.clone(), state.clone()); + tokio::spawn(async move { + if let Ok(tls) = acceptor.accept(socket).await { + serve_origin(tls, seen, Duration::from_millis(150)).await; + } + }); + } + }); + + let ccache = |name: &str| format!("FILE:{dir}/ccache/{name}"); + let set_ccache = |name: &str| std::env::set_var("KRB5CCNAME", ccache(name)); + let principal = format!("user=alice@{realm}"); + + // AC-1 / AC-8: default target HTTP/, and an override. + let ok_cases = [ + ("default target", kerberos(&proxy, None, None)), + ( + "host override", + kerberos(&proxy_ip, Some("localhost"), Some("HTTP")), + ), + ]; + for (name, config) in ok_cases { + set_ccache("valid"); + let from = log_len(&access_log); + let client = build(config).unwrap(); + assert_eq!(get(&client, &origin).await.unwrap(), 200, "{name}"); + // squid logs a CONNECT when its tunnel closes. + drop(client); + let lines = settled_log(&access_log, from).await; + assert!(!lines.is_empty(), "{name}: no CONNECT logged"); + for line in &lines { + assert!( + line.contains("TCP_TUNNEL/200 CONNECT 127.0.0.1"), + "{name}: {line}" + ); + assert!(line.contains(&principal), "{name}: {line}"); + } + } + + // AC-2 / AC-3 / P-3: no ticket, expired ticket and unknown target + // names fail closed in under a second with zero CONNECTs. + let fail_cases = [ + ( + "no ticket", + "missing", + kerberos(&proxy, None, None), + "credentials", + ), + ( + "expired ticket", + "expired", + kerberos(&proxy, None, None), + "expired", + ), + ( + "unknown host", + "valid", + kerberos(&proxy_ip, None, None), + "not found", + ), + ( + "unknown service", + "valid", + kerberos(&proxy, None, Some("nosuch")), + "not found", + ), + ]; + for (name, cache, config, needle) in fail_cases { + set_ccache(cache); + let from = log_len(&access_log); + let started = Instant::now(); + let err = build(config).unwrap_err(); + let elapsed = started.elapsed(); + eprintln!("{name}: {elapsed:?}: {}", err.message); + assert_eq!( + err.code, + ErrorCode::Unauthenticated, + "{name}: {}", + err.message + ); + assert!( + err.message.to_lowercase().contains(needle), + "{name}: {}", + err.message + ); + assert!(elapsed < Duration::from_secs(1), "{name}: took {elapsed:?}"); + assert!( + settled_log(&access_log, from).await.is_empty(), + "{name}: CONNECT sent" + ); + } + + // AC-5: 6 sequential sessions, then concurrent tunnels in one client, + // all through squid's replay cache; at most one 407 per tunnel. + set_ccache("valid"); + let from = log_len(&access_log); + for _ in 0..6 { + let client = build(kerberos(&proxy, None, None)).unwrap(); + assert_eq!(get(&client, &origin).await.unwrap(), 200); + } + let client = build(kerberos(&proxy, None, None)).unwrap(); + for _ in 0..2 { + let results = futures::future::join_all((0..6).map(|_| get(&client, &origin))).await; + for result in results { + assert_eq!(result.unwrap(), 200); + } + } + drop(client); + let lines = settled_log(&access_log, from).await; + let accepted = lines + .iter() + .filter(|l| l.contains("TCP_TUNNEL/200")) + .count(); + let rejected = lines.iter().filter(|l| l.contains("/407 CONNECT")).count(); + assert_eq!(accepted + rejected, lines.len(), "{lines:#?}"); + assert!(accepted >= 6 + 4, "{lines:#?}"); + // Every 407 was followed by one accepted fresh-token retry. (squid's + // helper children may each accept a token another child has seen, + // so not every reused token is rejected.) + assert!(rejected + 7 <= accepted, "{lines:#?}"); + eprintln!("tunnels: {accepted} accepted, {rejected} rejected with 407"); + + // AC-6: no Proxy-Authorization at the origin, no token in any log. + assert!(!seen + .lock() + .unwrap() + .origin_headers + .iter() + .any(|h| h == "proxy-authorization")); + let logs = String::from_utf8_lossy(&logs.lock().unwrap()).into_owned(); + assert!( + logs.contains("Negotiate configured"), + "trace capture is empty" + ); + assert!(!has_token_bytes(&logs), "token bytes in logs"); + let squid_cache_log = std::fs::read_to_string(format!("{dir}/squid/cache.log")).unwrap(); + eprintln!( + "replay rejections in squid cache.log (cumulative): {}", + squid_cache_log.matches("Request is a replay").count() + ); + } +} diff --git a/src/client/mod.rs b/src/client/mod.rs index 0edc69d2..89a81e89 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -32,6 +32,7 @@ //! [`sea`]: self::sea pub mod http; +pub(crate) mod proxy_negotiate; pub mod retry; pub mod sea; #[cfg(all(windows, feature = "tls-rustls"))] diff --git a/src/client/proxy_negotiate.rs b/src/client/proxy_negotiate.rs new file mode 100644 index 00000000..35dc196a --- /dev/null +++ b/src/client/proxy_negotiate.rs @@ -0,0 +1,442 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! `Proxy-Authorization: Negotiate` tokens for HTTP `CONNECT` proxies. + +use crate::config::{NegotiateTokenCallback, ProxyAuth}; +use crate::kernel_error::{Error, Result}; +use base64::Engine; +use reqwest::header::HeaderValue; + +/// Where Negotiate tokens come from. Never holds token bytes. +#[derive(Clone)] +pub(crate) enum NegotiateSource { + /// Platform GSSAPI / SSPI for this target name. + #[cfg(feature = "proxy-negotiate")] + Kerberos { + target: String, + }, + Callback(NegotiateTokenCallback), +} + +impl std::fmt::Debug for NegotiateSource { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + #[cfg(feature = "proxy-negotiate")] + NegotiateSource::Kerberos { target } => write!(f, "Kerberos({target})"), + NegotiateSource::Callback(_) => f.write_str("Callback"), + } + } +} + +impl NegotiateSource { + /// Validate a proxy configuration and resolve its Negotiate source. + /// `Ok(None)` means [`ProxyAuth::Default`]. Does no I/O. + pub(crate) fn resolve( + url: Option<&str>, + username: Option<&str>, + password: Option<&str>, + auth: &ProxyAuth, + ) -> Result> { + let kerberos = match auth { + ProxyAuth::Default => return Ok(None), + ProxyAuth::Negotiate { + service, + host, + realm, + } => Some((service, host, realm)), + ProxyAuth::NegotiateCallback(_) => None, + }; + let invalid = |msg: &str| { + Err(Error::invalid_argument().message(format!("Negotiate proxy authentication {msg}"))) + }; + let Some(url) = url else { + return invalid("requires an explicit proxy URL (ProxyConfig.url)"); + }; + let parsed = match reqwest::Url::parse(url) { + Ok(parsed) if matches!(parsed.scheme(), "http" | "https") => parsed, + Ok(_) => return invalid("supports only http:// and https:// proxy URLs"), + Err(e) => return invalid(&format!("has an invalid proxy URL: {e}")), + }; + if username.is_some() + || password.is_some() + || !parsed.username().is_empty() + || parsed.password().is_some() + { + return invalid("cannot be combined with Basic proxy credentials"); + } + let Some((service, host, realm)) = kerberos else { + let ProxyAuth::NegotiateCallback(callback) = auth else { + unreachable!("only the callback variant has no Kerberos target") + }; + return Ok(Some(NegotiateSource::Callback(callback.clone()))); + }; + let Some(proxy_host) = parsed.host_str() else { + return invalid("requires a proxy URL with a host"); + }; + // IPv6 literals keep their URL brackets in `host_str`. + let proxy_host = proxy_host.trim_start_matches('[').trim_end_matches(']'); + let target = target_name(service, host, realm, proxy_host); + #[cfg(feature = "proxy-negotiate")] + { + Ok(Some(NegotiateSource::Kerberos { target })) + } + #[cfg(not(feature = "proxy-negotiate"))] + { + Err(Error::not_implemented().message(format!( + "Negotiate proxy authentication (target {target}) is unsupported: the kernel was \ + built without the `proxy-negotiate` cargo feature" + ))) + } + } + + /// Create a fresh `Negotiate ` header value. Blocking: GSSAPI + /// may contact the KDC and a callback may block. + pub(crate) fn header(&self) -> Result { + let token = match self { + #[cfg(feature = "proxy-negotiate")] + NegotiateSource::Kerberos { target } => kerberos_token(target)?, + NegotiateSource::Callback(callback) => (callback.0)().map_err(|e| { + Error::unauthenticated().message(format!( + "Negotiate proxy authentication failed: the token callback failed: {e}" + )) + })?, + }; + if token.is_empty() { + return Err(Error::unauthenticated().message( + "Negotiate proxy authentication failed: the token source returned no token", + )); + } + let encoded = base64::engine::general_purpose::STANDARD.encode(token); + let mut value = HeaderValue::try_from(format!("Negotiate {encoded}")).map_err(|_| { + Error::internal().message("Negotiate header is not a valid header value") + })?; + value.set_sensitive(true); + Ok(value) + } +} + +/// `/[@]`; blank overrides fall back to the defaults +/// (`HTTP` and the proxy host). +fn target_name( + service: &Option, + host: &Option, + realm: &Option, + proxy_host: &str, +) -> String { + let pick = |v: &Option| { + v.as_deref() + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string) + }; + let mut target = format!( + "{}/{}", + pick(service).unwrap_or_else(|| "HTTP".to_string()), + pick(host).unwrap_or_else(|| proxy_host.to_string()) + ); + if let Some(realm) = pick(realm) { + target.push('@'); + target.push_str(&realm); + } + target +} + +#[cfg(feature = "proxy-negotiate")] +fn kerberos_token(target: &str) -> Result> { + // Ambient credentials (`None` principal); no delegation. Unix sends a + // raw Kerberos token (accepted under `Negotiate` by MIT/Heimdal + // acceptors); Windows uses the SSPI Negotiate package. + #[cfg(windows)] + let flags = cross_krb5::InitiateFlags::NEGOTIATE_TOKEN; + #[cfg(not(windows))] + let flags = cross_krb5::InitiateFlags::empty(); + let (_pending, token) = cross_krb5::ClientCtx::new(flags, None, target, None).map_err(|e| { + Error::unauthenticated().message(format!( + "Negotiate proxy authentication failed: no Kerberos token for {target}: {e:#}" + )) + })?; + Ok(token.to_vec()) +} + +/// Whether a request failed because the proxy answered `CONNECT` with 407. +pub(crate) fn is_proxy_auth_required(error: &reqwest::Error) -> bool { + // hyper-util's `TunnelError::ProxyAuthRequired` is private; reqwest + // reports it as "tunnel error: proxy authorization required". + super::error_chain(error).any(|e| e.to_string().ends_with("proxy authorization required")) +} + +/// Redirect hops reqwest's default policy follows. +const MAX_REDIRECTS: usize = 10; + +/// The next request of a redirect chain, or `None` when `response` is final. +/// +/// Negotiate clients follow no redirects, so the kernel follows them hop by +/// hop and can retry a proxy 407 at the hop whose `CONNECT` failed. This +/// mirrors reqwest's default policy (tower-http `FollowRedirect` with +/// reqwest's `TowerRedirectPolicy`): 301/302 turn POST into GET, 303 turns +/// anything but HEAD into GET (both drop the body and its headers), +/// 307/308 resend as is. A hop to another host or port drops +/// `Authorization`, `Cookie`, `Proxy-Authorization` and `WWW-Authenticate`; +/// at most 10 hops. `previous` collects the URLs already sent. +pub(crate) fn next_redirect( + sent: &reqwest::Request, + response: &reqwest::Response, + previous: &mut Vec, +) -> Result> { + use reqwest::header::{ + AUTHORIZATION, CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TYPE, COOKIE, LOCATION, + PROXY_AUTHORIZATION, REFERER, TRANSFER_ENCODING, WWW_AUTHENTICATE, + }; + use reqwest::{Method, StatusCode}; + + let mut method = sent.method().clone(); + let keep_body = match response.status() { + StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND if method == Method::POST => { + method = Method::GET; + false + } + StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND => true, + StatusCode::SEE_OTHER => { + if method != Method::HEAD { + method = Method::GET; + } + false + } + StatusCode::TEMPORARY_REDIRECT | StatusCode::PERMANENT_REDIRECT => true, + _ => return Ok(None), + }; + let from = sent.url(); + let Some(next) = response + .headers() + .get(LOCATION) + .and_then(|v| std::str::from_utf8(v.as_bytes()).ok()) + .and_then(|location| from.join(location).ok()) + else { + return Ok(None); + }; + let mut shown = from.clone(); + shown.set_query(None); + previous.push(from.clone()); + if previous.len() > MAX_REDIRECTS { + return Err(Error::network_error().message(format!( + "error following redirect for url ({shown}): too many redirects" + ))); + } + if !matches!(next.scheme(), "http" | "https") { + return Err(Error::network_error().message(format!( + "error following redirect for url ({shown}): unsupported scheme {}", + next.scheme() + ))); + } + + let mut headers = sent.headers().clone(); + if !keep_body { + for name in [ + CONTENT_TYPE, + CONTENT_LENGTH, + CONTENT_ENCODING, + TRANSFER_ENCODING, + ] { + headers.remove(name); + } + } + if next.host_str() != from.host_str() + || next.port_or_known_default() != from.port_or_known_default() + { + for name in [AUTHORIZATION, COOKIE, PROXY_AUTHORIZATION, WWW_AUTHENTICATE] { + headers.remove(name); + } + headers.remove("cookie2"); + } + if !(next.scheme() == "http" && from.scheme() == "https") { + let mut referer = from.clone(); + let _ = referer.set_username(""); + let _ = referer.set_password(None); + referer.set_fragment(None); + if let Ok(value) = HeaderValue::try_from(referer.as_str()) { + headers.insert(REFERER, value); + } + } + + // Keeps the body (and timeout); a streaming body cannot be resent. + let Some(mut request) = sent.try_clone() else { + return Ok(None); + }; + *request.method_mut() = method; + *request.url_mut() = next; + *request.headers_mut() = headers; + if !keep_body { + *request.body_mut() = None; + } + Ok(Some(request)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::kernel_error::ErrorCode; + + fn callback() -> ProxyAuth { + ProxyAuth::NegotiateCallback(NegotiateTokenCallback::new(|| Ok(b"tok".to_vec()))) + } + + fn kerberos(service: Option<&str>, host: Option<&str>, realm: Option<&str>) -> ProxyAuth { + ProxyAuth::Negotiate { + service: service.map(str::to_string), + host: host.map(str::to_string), + realm: realm.map(str::to_string), + } + } + + #[test] + fn invalid_negotiate_configs_fail_before_io() { + let cases = [ + ("no url", None, None, None, callback()), + ("socks url", Some("socks5://p:1080"), None, None, callback()), + ( + "socks url kerberos", + Some("socks5h://p:1080"), + None, + None, + kerberos(None, None, None), + ), + ( + "basic username", + Some("http://p:3128"), + Some("u"), + None, + callback(), + ), + ( + "basic password", + Some("http://p:3128"), + None, + Some("x"), + kerberos(None, None, None), + ), + ( + "url userinfo", + Some("http://u:x@p:3128"), + None, + None, + callback(), + ), + ("bad url", Some("http://"), None, None, callback()), + ]; + for (name, url, user, pass, auth) in cases { + let err = NegotiateSource::resolve(url, user, pass, &auth).unwrap_err(); + assert_eq!( + err.code, + ErrorCode::InvalidArgument, + "{name}: {}", + err.message + ); + assert!(err.message.contains("Negotiate"), "{name}: {}", err.message); + } + } + + #[test] + fn default_auth_resolves_to_none() { + let resolved = + NegotiateSource::resolve(Some("http://p:3128"), Some("u"), None, &ProxyAuth::Default); + assert!(resolved.unwrap().is_none()); + } + + #[test] + fn target_names() { + let cases = [ + (None, None, None, "HTTP/proxy.corp"), + ( + Some("http"), + Some("fqdn.corp"), + Some("CORP.EXAMPLE"), + "http/fqdn.corp@CORP.EXAMPLE", + ), + (Some(" "), Some(""), Some(""), "HTTP/proxy.corp"), + (None, None, Some("R"), "HTTP/proxy.corp@R"), + ]; + for (service, host, realm, expected) in cases { + let to_owned = |v: Option<&str>| v.map(str::to_string); + let target = target_name( + &to_owned(service), + &to_owned(host), + &to_owned(realm), + "proxy.corp", + ); + assert_eq!(target, expected); + } + } + + #[cfg(not(feature = "proxy-negotiate"))] + #[test] + fn kerberos_without_feature_is_unsupported() { + let err = NegotiateSource::resolve( + Some("http://p:3128"), + None, + None, + &kerberos(None, None, None), + ) + .unwrap_err(); + assert!(err.message.contains("unsupported"), "{}", err.message); + assert!(err.message.contains("proxy-negotiate"), "{}", err.message); + assert!(err.message.contains("HTTP/p"), "{}", err.message); + } + + #[cfg(feature = "proxy-negotiate")] + #[test] + fn kerberos_target_defaults_to_proxy_host() { + let source = NegotiateSource::resolve( + Some("http://[::1]:3128"), + None, + None, + &kerberos(None, None, None), + ) + .unwrap() + .unwrap(); + assert_eq!(format!("{source:?}"), "Kerberos(HTTP/::1)"); + } + + #[test] + fn callback_header_is_sensitive_and_base64() { + let source = NegotiateSource::resolve(Some("http://p:3128"), None, None, &callback()) + .unwrap() + .unwrap(); + let value = source.header().unwrap(); + assert_eq!(value.to_str().unwrap(), "Negotiate dG9r"); + assert!(value.is_sensitive()); + assert_eq!(format!("{value:?}"), "Sensitive"); + assert_eq!(format!("{source:?}"), "Callback"); + } + + #[test] + fn callback_failures_are_unauthenticated() { + let cases: [(&str, NegotiateTokenCallback); 2] = [ + ( + "error", + NegotiateTokenCallback::new(|| Err("no ticket".to_string())), + ), + ("empty", NegotiateTokenCallback::new(|| Ok(Vec::new()))), + ]; + for (name, callback) in cases { + let auth = ProxyAuth::NegotiateCallback(callback); + let source = NegotiateSource::resolve(Some("http://p:3128"), None, None, &auth) + .unwrap() + .unwrap(); + let err = source.header().unwrap_err(); + assert_eq!(err.code, ErrorCode::Unauthenticated, "{name}"); + assert!(!err.retryable, "{name}"); + } + } +} diff --git a/src/config.rs b/src/config.rs index c83b9dc0..3d4eab75 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1079,6 +1079,10 @@ pub struct ProxyConfig { /// (e.g. `"localhost,*.internal.corp,.example.com"`). Only applied /// when [`url`](Self::url) is set. pub bypass_hosts: Option, + + /// Proxy authentication scheme. [`ProxyAuth::Default`] keeps Basic + /// credentials (from [`username`](Self::username) or the URL) or none. + pub auth: ProxyAuth, } impl std::fmt::Debug for ProxyConfig { @@ -1091,10 +1095,85 @@ impl std::fmt::Debug for ProxyConfig { .field("username", &self.username) .field("password", &self.password.as_ref().map(|_| "")) .field("bypass_hosts", &self.bypass_hosts) + .field("auth", &self.auth) .finish() } } +/// How the kernel authenticates to the HTTP proxy in [`ProxyConfig::url`]. +/// +/// Both Negotiate variants send `Proxy-Authorization: Negotiate ` on +/// the HTTP `CONNECT` to the proxy only, never to the warehouse or storage. +/// A token is created when the HTTP client is built (session open; failure +/// fails the session before any network I/O) and once more when the proxy +/// answers a `CONNECT` with `407`. A second `407` fails the request. Negotiate +/// never falls back to Basic, a direct connection or an environment proxy. +/// It needs an `http://` or `https://` [`ProxyConfig::url`] and no Basic +/// credentials. +#[non_exhaustive] +#[derive(Clone, Default)] +pub enum ProxyAuth { + /// Basic credentials from the URL or `username` / `password`, or none. + #[default] + Default, + /// Kerberos via the platform GSSAPI (MIT or Heimdal) or Windows SSPI, + /// using the caller's ambient credentials (credential cache or logon + /// session). No password, keytab or delegation. The target is + /// `/[@]`, by default `HTTP/` in the + /// default realm. Requires the `proxy-negotiate` cargo feature; without + /// it, `Session::open` rejects this variant as unsupported. + Negotiate { + /// Service part of the target name. Default `HTTP`. + service: Option, + /// Host part of the target name. Default: the proxy URL's host. + host: Option, + /// Realm of the target name. Default: the Kerberos default realm. + realm: Option, + }, + /// Tokens come from a caller-supplied callback (used by the Python + /// binding, which creates them with the same libraries as its Thrift + /// path). Needs no cargo feature. + NegotiateCallback(NegotiateTokenCallback), +} + +impl std::fmt::Debug for ProxyAuth { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ProxyAuth::Default => f.write_str("Default"), + ProxyAuth::Negotiate { + service, + host, + realm, + } => f + .debug_struct("Negotiate") + .field("service", service) + .field("host", host) + .field("realm", realm) + .finish(), + ProxyAuth::NegotiateCallback(_) => f.write_str("NegotiateCallback"), + } + } +} + +/// Callback returning one raw (not base64) SPNEGO or Kerberos token for the +/// proxy. It is called from a blocking thread, at most once per HTTP client +/// build plus once per proxy `407`, and must return a new token each time +/// (proxies reject replayed tokens). An `Err` or an empty token fails the +/// request closed; the message must not contain token bytes. +#[derive(Clone)] +pub struct NegotiateTokenCallback( + pub std::sync::Arc std::result::Result, String> + Send + Sync>, +); + +impl NegotiateTokenCallback { + /// Wrap a token-producing closure. + pub fn new( + f: impl Fn() -> std::result::Result, String> + Send + Sync + 'static, + ) -> Self { + Self(std::sync::Arc::new(f)) + } +} + // ─── TLS ──────────────────────────────────────────────────────────────────── /// TLS settings for the HTTP client. diff --git a/src/feature_flags/mod.rs b/src/feature_flags/mod.rs index 197ad0a6..16d1924a 100644 --- a/src/feature_flags/mod.rs +++ b/src/feature_flags/mod.rs @@ -354,16 +354,25 @@ impl FeatureFlagResolver { } async fn fetch(&self, request: reqwest::RequestBuilder) -> Result { - let response = request.send().await.map_err(|error| { - let kernel_error = if error.is_timeout() { - Error::timeout() - } else { - Error::network_error() - }; - kernel_error.message(format!( - "connector-service feature-flag GET failed: {error}" - )) + // Sent once, outside the retry loop; `send_once` still gives a + // Negotiate proxy 407 its fresh-token retry. + let request = request.build().map_err(|error| { + Error::invalid_argument().message(format!("feature-flag request is invalid: {error}")) })?; + let response = self + .http_client + .send_once(request) + .await? + .map_err(|error| { + let kernel_error = if error.is_timeout() { + Error::timeout() + } else { + Error::network_error() + }; + kernel_error.message(format!( + "connector-service feature-flag GET failed: {error}" + )) + })?; let status = response.status(); if !status.is_success() { return Err(Error::from_http_status(status.as_u16()).message(format!( diff --git a/src/lib.rs b/src/lib.rs index 9b5ebb50..569e2e1a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -135,8 +135,8 @@ pub mod c_abi; // === Public re-exports === pub use config::{ AuthConfig, ConnectionConfig, DefaultOpts, GeospatialResultRepresentation, HttpConfig, - LoggingConfig, ProxyConfig, ResultConfig, SessionConfig, TelemetryConfig, TlsConfig, - TokenCacheConfig, TransportMode, + LoggingConfig, NegotiateTokenCallback, ProxyAuth, ProxyConfig, ResultConfig, SessionConfig, + TelemetryConfig, TlsConfig, TokenCacheConfig, TransportMode, }; pub use kernel_error::{Error, ErrorCode, Result}; /// The `tracing` target string stamped on every kernel log event. diff --git a/src/session.rs b/src/session.rs index 6ed791e3..8b758688 100644 --- a/src/session.rs +++ b/src/session.rs @@ -375,11 +375,28 @@ impl Session { crate::client::http::check_revocation_support(&http_client_config.tls, revocation)?; validate_revocation_endpoint_scheme(&config, revocation)?; let retry_configs = build_retry_configs_for_session(&config); + // Invalid or unsupported Negotiate proxy settings keep their own + // error code, as does a failed Negotiate token (fail closed, D4). + let proxy = &http_client_config.proxy; + crate::client::proxy_negotiate::NegotiateSource::resolve( + proxy.url.as_deref(), + proxy.username.as_deref(), + proxy.password.as_deref(), + &proxy.auth, + )?; let http_client = Arc::new( - DatabricksHttpClient::with_revocation(http_client_config, retry_configs, revocation) - .map_err(|e| { - Error::network_error().message(format!("Failed to construct HTTP client: {e}")) - })?, + DatabricksHttpClient::with_revocation_async( + http_client_config, + retry_configs, + revocation, + ) + .await + .map_err(|e| { + if e.code == crate::kernel_error::ErrorCode::Unauthenticated { + return e; + } + Error::network_error().message(format!("Failed to construct HTTP client: {e}")) + })?, ); // 2. Auth provider — async because OAuth flows hit the OIDC @@ -1135,12 +1152,14 @@ fn build_proxy_config(proxy: Option<&ProxyConfig>) -> HttpProxyConfig { username, password, bypass_hosts, + auth, } = proxy.clone(); HttpProxyConfig { url, username, password, bypass_hosts, + auth, } } diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index a4f84f73..f2480a09 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -437,6 +437,35 @@ static void test_executed_null_handle_rejected(void) { CHECK(n == -1, "num_modified_rows(NULL exec) → -1"); } +/* Negotiate proxy setter; invalid combinations fail at open with + * InvalidArgument before any network I/O. */ +static void test_proxy_negotiate_setter(void) { + KernelStatusCode rc = kernel_session_config_set_proxy_negotiate(NULL, NULL, NULL, NULL); + CHECK(rc == KernelStatusCode_InvalidArgument, "set_proxy_negotiate(NULL config) → InvalidArgument"); + + const char* proxy_user[] = {"u", NULL}; + const char* expected[] = {"Basic", "set_proxy"}; + for (int i = 0; i < 2; i++) { + KernelSessionConfig* config = NULL; + (void)kernel_session_config_new(&config); + (void)kernel_session_config_set_warehouse(config, "https://192.0.2.1", "wh123"); + (void)kernel_session_config_set_auth_pat(config, "dapi-not-a-real-token"); + rc = kernel_session_config_set_proxy_negotiate(config, "HTTP", "proxy.corp", "CORP.EXAMPLE"); + CHECK(rc == KernelStatusCode_Success, "set_proxy_negotiate succeeds"); + if (proxy_user[i] != NULL) { + (void)kernel_session_config_set_proxy(config, "http://192.0.2.1:3128", proxy_user[i], "p", NULL); + } + kernel_session_t* session = NULL; + rc = kernel_session_open(config, &session); + CHECK(rc == KernelStatusCode_InvalidArgument, "invalid Negotiate proxy open → InvalidArgument"); + KernelError err; + memset(&err, 0, sizeof(err)); + CHECK(kernel_get_last_error(&err) && err.message != NULL && + strstr(err.message, expected[i]) != NULL, + "invalid Negotiate proxy error names the cause"); + } +} + int main(void) { test_config_lifecycle(); test_null_guards(); @@ -447,6 +476,7 @@ int main(void) { test_setter_null_arg_rejected(); test_proxy_and_tls_setters(); test_tls_certificate_revocation_setter(); + test_proxy_negotiate_setter(); test_u2m_and_header_setters(); test_identity_federation_client_id_setter(); test_client_conf_setter(); From 7b35f9a4f03a8781156b1e6659796edcda5d05f6 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:26:19 +0000 Subject: [PATCH 02/18] ci(proxy): drop the proxy-negotiate PR job and its KDC fixture The job ran on every PR, push and merge-queue entry, and its real KDC + squid replay test depended on how many tunnels happened to overlap. Remove the job, ci/proxy/negotiate/{start,stop}.sh and the ignored KDC test. The stub-proxy Negotiate tests still run in the existing PR jobs on both TLS backends, and the driver-test kernel nightly covers real Kerberos tokens through squid. Co-authored-by: Isaac Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> --- .github/workflows/pr-checks.yml | 51 ------ ci/proxy/negotiate/start.sh | 140 ---------------- ci/proxy/negotiate/stop.sh | 21 --- src/client/http_negotiate_tests.rs | 246 +---------------------------- 4 files changed, 1 insertion(+), 457 deletions(-) delete mode 100755 ci/proxy/negotiate/start.sh delete mode 100755 ci/proxy/negotiate/stop.sh diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index ad422031..2e6848a6 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -160,57 +160,6 @@ jobs: # link and call the kernel. `cc` is preinstalled on the runner. run: make c-abi-test - proxy-negotiate: - name: Proxy Negotiate (${{ matrix.tls }}) - runs-on: - group: databricks-protected-runner-group - labels: linux-ubuntu-latest - strategy: - fail-fast: false - matrix: - tls: [tls-native, tls-rustls] - env: - RUSTC_WRAPPER: sccache - SCCACHE_GHA_ENABLED: "true" - FIXTURE: ${{ github.workspace }}/target/negotiate-fixture - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - - uses: ./.github/actions/setup-public-package-proxies - with: - cargo: "true" - - - uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0 - with: - toolchain: stable - components: clippy - - - name: Setup sccache - uses: Mozilla-Actions/sccache-action@7d986dd989559c6ecdb630a3fd2557667be217ad # v0.0.9 - - - name: Install Kerberos and squid - # GSSAPI headers and libclang build `libgssapi-sys`. The KDC and - # squid run unprivileged from ci/proxy/negotiate/start.sh. - run: | - sudo apt-get update - sudo DEBIAN_FRONTEND=noninteractive apt-get install -y \ - krb5-kdc krb5-admin-server krb5-user squid libkrb5-dev libclang-dev - - - name: cargo clippy (proxy-negotiate) - run: cargo clippy --no-default-features --features ${{ matrix.tls }},proxy-negotiate --all-targets -- -D warnings - - - name: Start the KDC and Negotiate proxy - run: | - ci/proxy/negotiate/start.sh "$FIXTURE" - cat "$FIXTURE/env" >> "$GITHUB_ENV" - - - name: Negotiate tests (stub proxy and real KDC + squid) - run: cargo test --no-default-features --features ${{ matrix.tls }},proxy-negotiate --lib negotiate -- --include-ignored - - - name: Stop the fixture - if: always() - run: ci/proxy/negotiate/stop.sh "$FIXTURE" - adbc: name: ADBC native + C ABI runs-on: diff --git a/ci/proxy/negotiate/start.sh b/ci/proxy/negotiate/start.sh deleted file mode 100755 index 736c4fa1..00000000 --- a/ci/proxy/negotiate/start.sh +++ /dev/null @@ -1,140 +0,0 @@ -#!/usr/bin/env bash -# Copyright (c) 2026 Databricks, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# Throwaway Kerberos realm + squid Negotiate proxy for the `proxy-negotiate` -# tests. Runs unprivileged with everything under DIR; principals get random -# keys and nothing is committed. Needs krb5-kdc, krb5-admin-server, krb5-user -# and squid (with negotiate_kerberos_auth). Writes DIR/env (KEY=VALUE lines -# for $GITHUB_ENV); stop with ci/proxy/negotiate/stop.sh DIR. -# -# ci/proxy/negotiate/start.sh DIR -# -# Ports and realm: NEGOTIATE_KDC_PORT (48088), NEGOTIATE_PROXY_PORT (48128, -# Negotiate required), NEGOTIATE_OPEN_PROXY_PORT (48129, no auth), -# NEGOTIATE_REALM (KERNEL.TEST). NEGOTIATE_ALLOW_DOMAINS (squid dstdomain -# list) adds CONNECT targets beyond 127.0.0.1, e.g. ".databricks.com". -set -euo pipefail - -dir=$(mkdir -p "$1" && cd "$1" && pwd) -realm=${NEGOTIATE_REALM:-KERNEL.TEST} -kdc_port=${NEGOTIATE_KDC_PORT:-48088} -neg_port=${NEGOTIATE_PROXY_PORT:-48128} -open_port=${NEGOTIATE_OPEN_PROXY_PORT:-48129} -allow=${NEGOTIATE_ALLOW_DOMAINS:-localhost} -helper=${NEGOTIATE_SQUID_HELPER:-/usr/lib/squid/negotiate_kerberos_auth} -mkdir -p "$dir/kdc" "$dir/ccache" "$dir/rcache" "$dir/squid" -chmod 700 "$dir/kdc" "$dir/ccache" "$dir/rcache" - -cat > "$dir/krb5.conf" < "$dir/kdc/kdc.conf" < "$dir/kdc/kadm5.acl" - -export KRB5_CONFIG=$dir/krb5.conf KRB5_KDC_PROFILE=$dir/kdc/kdc.conf -if [ ! -f "$dir/kdc/principal" ]; then - kdb5_util create -s -r "$realm" -P "$(head -c 32 /dev/urandom | base64)" > "$dir/kdc/create.log" - for p in "alice@$realm" "HTTP/localhost@$realm"; do - kadmin.local -r "$realm" -q "addprinc -randkey $p" > /dev/null - done - kadmin.local -r "$realm" -q "ktadd -k $dir/kdc/alice.keytab alice@$realm" > /dev/null - kadmin.local -r "$realm" -q "ktadd -k $dir/kdc/http.keytab HTTP/localhost@$realm" > /dev/null - chmod 600 "$dir/kdc/"*.keytab -fi -nohup krb5kdc -n -P "$dir/kdc/krb5kdc.pid" > "$dir/kdc/krb5kdc.out" 2>&1 & -echo $! > "$dir/kdc/pid" - -# The acceptor's replay cache stays on (the default), as in production. -cat > "$dir/squid/squid.conf" <Hs %rm %ru user=%un ua="%{User-Agent}>h" -access_log stdio:$dir/squid/access.log negotiate -cache deny all -cache_mem 8 MB -coredump_dir $dir/squid -netdb_filename none -pinger_enable off -shutdown_lifetime 1 seconds -auth_param negotiate program $helper -s HTTP/localhost@$realm -k $dir/kdc/http.keytab -c $dir/rcache -auth_param negotiate children 5 startup=1 idle=1 -auth_param negotiate keep_alive on -acl negport myportname negport -acl openport myportname openport -acl local_dst dst 127.0.0.1 -acl allowed_dst dstdomain $allow -acl authed proxy_auth REQUIRED -http_access deny !local_dst !allowed_dst -http_access allow openport -http_access allow negport authed -http_access deny all -EOF -squid -k parse -f "$dir/squid/squid.conf" > "$dir/squid/parse.log" 2>&1 -nohup squid -N -f "$dir/squid/squid.conf" > "$dir/squid/squid.out" 2>&1 & -echo $! > "$dir/squid/pid" - -for port in "$kdc_port" "$neg_port" "$open_port"; do - for _ in $(seq 50); do - (exec 3<>"/dev/tcp/127.0.0.1/$port") 2> /dev/null && break - sleep 0.2 - done -done - -# Credential caches: valid, expired (10 s lifetime) and missing. -kinit -l 10s -k -t "$dir/kdc/alice.keytab" -c "FILE:$dir/ccache/expired" "alice@$realm" -expired_at=$((SECONDS + 11)) -kinit -k -t "$dir/kdc/alice.keytab" -c "FILE:$dir/ccache/valid" "alice@$realm" - -cat > "$dir/env" < /dev/null -done -exit 0 diff --git a/src/client/http_negotiate_tests.rs b/src/client/http_negotiate_tests.rs index e8cc7688..ce012f3b 100644 --- a/src/client/http_negotiate_tests.rs +++ b/src/client/http_negotiate_tests.rs @@ -15,7 +15,7 @@ //! Negotiate proxy auth against a stub `CONNECT` proxy that, like a Kerberos //! acceptor with a replay cache, rejects any token it has already seen //! (`407 Negotiate, Basic`). The stub terminates the tunnel with its own TLS -//! origin. No KDC needed; `tests/proxy_negotiate_kdc.rs` covers real tokens. +//! origin. No KDC needed; the driver-test kernel nightly covers real tokens. use super::*; use crate::auth::PersonalAccessToken; @@ -918,247 +918,3 @@ fn reusable_tls_keeps_reqwest_setup_when_parsers_disagree() { assert_eq!(tls.is_some(), reused, "{name}"); } } - -/// Real tokens: MIT KDC + squid `negotiate_kerberos_auth` (replay cache on) -/// from `ci/proxy/negotiate/start.sh`, in front of a local TLS origin. -#[cfg(feature = "proxy-negotiate")] -mod kdc { - use super::*; - use std::time::Instant; - - fn env(name: &str) -> String { - std::env::var(name).unwrap_or_else(|_| panic!("{name} not set: source the fixture env")) - } - - fn log_len(path: &str) -> usize { - std::fs::metadata(path).map_or(0, |m| m.len() as usize) - } - - /// Lines squid appended to its access log after `from` bytes. - fn log_since(path: &str, from: usize) -> Vec { - let log = std::fs::read_to_string(path).unwrap_or_default(); - log[from.min(log.len())..] - .lines() - .map(str::to_string) - .collect() - } - - async fn settled_log(path: &str, from: usize) -> Vec { - // squid writes the access log asynchronously. - tokio::time::sleep(Duration::from_millis(500)).await; - log_since(path, from) - } - - fn kerberos(proxy_url: &str, host: Option<&str>, service: Option<&str>) -> HttpClientConfig { - let mut config = HttpClientConfig::default(); - config.proxy.url = Some(proxy_url.to_string()); - config.proxy.auth = ProxyAuth::Negotiate { - service: service.map(str::to_string), - host: host.map(str::to_string), - realm: None, - }; - config.tls.allow_self_signed = Some(true); - config.tls.allow_hostname_mismatch = Some(true); - config - } - - fn build(config: HttpClientConfig) -> Result { - let client = DatabricksHttpClient::with_default_retry(config)?; - client.set_auth_provider(Arc::new(PersonalAccessToken::new("pat".to_string()))); - Ok(client) - } - - /// Captures every log line at TRACE (kernel `tracing` plus reqwest / - /// hyper `log` records) to prove no token bytes are logged. - fn capture_logs() -> Arc>> { - #[derive(Clone)] - struct Sink(Arc>>); - impl std::io::Write for Sink { - fn write(&mut self, buf: &[u8]) -> std::io::Result { - self.0.lock().unwrap().extend_from_slice(buf); - Ok(buf.len()) - } - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) - } - } - let buffer = Arc::new(Mutex::new(Vec::new())); - let sink = Sink(buffer.clone()); - tracing_subscriber::fmt() - .with_max_level(tracing::Level::TRACE) - .with_writer(move || sink.clone()) - .try_init() - .expect("first subscriber in this test process"); - buffer - } - - fn has_token_bytes(text: &str) -> bool { - text.match_indices("Negotiate ").any(|(i, m)| { - let rest = &text[i + m.len()..]; - rest.chars() - .take_while(|c| c.is_ascii_alphanumeric() || "+/=".contains(*c)) - .count() - >= 16 - }) - } - - #[tokio::test(flavor = "multi_thread")] - #[ignore = "needs the ci/proxy/negotiate fixture: source DIR/env"] - async fn negotiate_through_kerberos_squid() { - let logs = capture_logs(); - let dir = env("NEGOTIATE_FIXTURE_DIR"); - let proxy = env("NEGOTIATE_PROXY_URL"); - let access_log = env("NEGOTIATE_PROXY_ACCESS_LOG"); - let realm = env("NEGOTIATE_REALM"); - // The proxy listens on 127.0.0.1; its service principal is - // HTTP/localhost, so an IP proxy URL needs the host override. - let proxy_ip = proxy.replace("localhost", "127.0.0.1"); - - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let origin = format!("https://{}/probe", listener.local_addr().unwrap()); - let seen = Arc::new(Mutex::new(Seen::default())); - let (acceptor, state) = (tls_acceptor(), seen.clone()); - tokio::spawn(async move { - while let Ok((socket, _)) = listener.accept().await { - let (acceptor, seen) = (acceptor.clone(), state.clone()); - tokio::spawn(async move { - if let Ok(tls) = acceptor.accept(socket).await { - serve_origin(tls, seen, Duration::from_millis(150)).await; - } - }); - } - }); - - let ccache = |name: &str| format!("FILE:{dir}/ccache/{name}"); - let set_ccache = |name: &str| std::env::set_var("KRB5CCNAME", ccache(name)); - let principal = format!("user=alice@{realm}"); - - // AC-1 / AC-8: default target HTTP/, and an override. - let ok_cases = [ - ("default target", kerberos(&proxy, None, None)), - ( - "host override", - kerberos(&proxy_ip, Some("localhost"), Some("HTTP")), - ), - ]; - for (name, config) in ok_cases { - set_ccache("valid"); - let from = log_len(&access_log); - let client = build(config).unwrap(); - assert_eq!(get(&client, &origin).await.unwrap(), 200, "{name}"); - // squid logs a CONNECT when its tunnel closes. - drop(client); - let lines = settled_log(&access_log, from).await; - assert!(!lines.is_empty(), "{name}: no CONNECT logged"); - for line in &lines { - assert!( - line.contains("TCP_TUNNEL/200 CONNECT 127.0.0.1"), - "{name}: {line}" - ); - assert!(line.contains(&principal), "{name}: {line}"); - } - } - - // AC-2 / AC-3 / P-3: no ticket, expired ticket and unknown target - // names fail closed in under a second with zero CONNECTs. - let fail_cases = [ - ( - "no ticket", - "missing", - kerberos(&proxy, None, None), - "credentials", - ), - ( - "expired ticket", - "expired", - kerberos(&proxy, None, None), - "expired", - ), - ( - "unknown host", - "valid", - kerberos(&proxy_ip, None, None), - "not found", - ), - ( - "unknown service", - "valid", - kerberos(&proxy, None, Some("nosuch")), - "not found", - ), - ]; - for (name, cache, config, needle) in fail_cases { - set_ccache(cache); - let from = log_len(&access_log); - let started = Instant::now(); - let err = build(config).unwrap_err(); - let elapsed = started.elapsed(); - eprintln!("{name}: {elapsed:?}: {}", err.message); - assert_eq!( - err.code, - ErrorCode::Unauthenticated, - "{name}: {}", - err.message - ); - assert!( - err.message.to_lowercase().contains(needle), - "{name}: {}", - err.message - ); - assert!(elapsed < Duration::from_secs(1), "{name}: took {elapsed:?}"); - assert!( - settled_log(&access_log, from).await.is_empty(), - "{name}: CONNECT sent" - ); - } - - // AC-5: 6 sequential sessions, then concurrent tunnels in one client, - // all through squid's replay cache; at most one 407 per tunnel. - set_ccache("valid"); - let from = log_len(&access_log); - for _ in 0..6 { - let client = build(kerberos(&proxy, None, None)).unwrap(); - assert_eq!(get(&client, &origin).await.unwrap(), 200); - } - let client = build(kerberos(&proxy, None, None)).unwrap(); - for _ in 0..2 { - let results = futures::future::join_all((0..6).map(|_| get(&client, &origin))).await; - for result in results { - assert_eq!(result.unwrap(), 200); - } - } - drop(client); - let lines = settled_log(&access_log, from).await; - let accepted = lines - .iter() - .filter(|l| l.contains("TCP_TUNNEL/200")) - .count(); - let rejected = lines.iter().filter(|l| l.contains("/407 CONNECT")).count(); - assert_eq!(accepted + rejected, lines.len(), "{lines:#?}"); - assert!(accepted >= 6 + 4, "{lines:#?}"); - // Every 407 was followed by one accepted fresh-token retry. (squid's - // helper children may each accept a token another child has seen, - // so not every reused token is rejected.) - assert!(rejected + 7 <= accepted, "{lines:#?}"); - eprintln!("tunnels: {accepted} accepted, {rejected} rejected with 407"); - - // AC-6: no Proxy-Authorization at the origin, no token in any log. - assert!(!seen - .lock() - .unwrap() - .origin_headers - .iter() - .any(|h| h == "proxy-authorization")); - let logs = String::from_utf8_lossy(&logs.lock().unwrap()).into_owned(); - assert!( - logs.contains("Negotiate configured"), - "trace capture is empty" - ); - assert!(!has_token_bytes(&logs), "token bytes in logs"); - let squid_cache_log = std::fs::read_to_string(format!("{dir}/squid/cache.log")).unwrap(); - eprintln!( - "replay rejections in squid cache.log (cumulative): {}", - squid_cache_log.matches("Request is a replay").count() - ); - } -} From edc9103d29dc55fe7271f6c15b840a075785ada4 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:52:36 +0000 Subject: [PATCH 03/18] test(proxy): make the Negotiate stub tests independent of timing The replay test now holds each origin answer until a wave of six requests has all reached its tunnel, and the deadline test doubles its delays and timeouts. The slow-token test waits on an async signal instead of a 20 ms ticker racing a 500 ms block. Test-only change; proxy code is untouched. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- src/client/http_negotiate_tests.rs | 116 +++++++++++++++++++++-------- 1 file changed, 84 insertions(+), 32 deletions(-) diff --git a/src/client/http_negotiate_tests.rs b/src/client/http_negotiate_tests.rs index ce012f3b..63363f24 100644 --- a/src/client/http_negotiate_tests.rs +++ b/src/client/http_negotiate_tests.rs @@ -36,6 +36,10 @@ struct Seen { origin_headers: Vec, /// ` ` and header names of each tunnelled request. requests: Vec<(String, Vec)>, + /// When set, every origin answer waits here until all parties arrive. + gate: Option>, + /// Gate waits that gave up (a request never arrived, or a tunnel was reused). + gate_timeouts: usize, } struct StubProxy { @@ -88,6 +92,15 @@ async fn serve_origin( seen.origin_headers.extend(names.clone()); seen.requests.push((format!("{method} {path}"), names)); } + let gate = seen.lock().unwrap().gate.clone(); + if let Some(gate) = gate { + if tokio::time::timeout(Duration::from_secs(10), gate.wait()) + .await + .is_err() + { + seen.lock().unwrap().gate_timeouts += 1; + } + } tokio::time::sleep(delay).await; if path == "/slowbody" { // Headers now, the body one more `delay` later. @@ -290,9 +303,31 @@ async fn negotiate_token_is_preemptive_and_only_on_connect() { assert_eq!(direct_hits.load(Ordering::SeqCst), 0); } +/// Number of CONNECTs the proxy has answered with 407 so far. +fn replays(proxy: &StubProxy) -> usize { + let seen = proxy.seen.lock().unwrap(); + seen.connects.iter().filter(|(_, s)| *s == 407).count() +} + +/// Six concurrent requests on `client`. Each origin answer waits until all six +/// have reached their tunnels, so no tunnel can serve two of them and the +/// overlap does not depend on timing. +async fn gated_wave(proxy: &StubProxy, client: &DatabricksHttpClient, origin: &str) { + proxy.seen.lock().unwrap().gate = Some(Arc::new(tokio::sync::Barrier::new(6))); + let results = futures::future::join_all((0..6).map(|_| get(client, origin))).await; + assert_eq!( + proxy.seen.lock().unwrap().gate_timeouts, + 0, + "a wave did not reach the origin together: a request never arrived or a tunnel was reused" + ); + for result in results { + assert_eq!(result.unwrap(), 200); + } +} + #[tokio::test] async fn negotiate_survives_a_replay_cache_across_tunnels() { - let proxy = StubProxy::start(false, Duration::from_millis(200)).await; + let proxy = StubProxy::start(false, Duration::ZERO).await; let (origin, direct_hits) = direct_origin().await; let calls = Arc::new(AtomicUsize::new(0)); @@ -304,22 +339,24 @@ async fn negotiate_survives_a_replay_cache_across_tunnels() { // Concurrent tunnels within one client: every new tunnel after the first // replays the client's token, gets 407 and retries once with a new one. let client = client(&proxy, &calls, false).unwrap(); - let results = futures::future::join_all((0..6).map(|_| get(&client, &origin))).await; - for result in results { - assert_eq!(result.unwrap(), 200); - } - // A second wave goes through the promoted rebuilt client the same way. - let results = futures::future::join_all((0..6).map(|_| get(&client, &origin))).await; - assert!(results.into_iter().all(|r| r.unwrap() == 200)); + let before = replays(&proxy); + gated_wave(&proxy, &client, &origin).await; + // The first tunnel takes the client's token; the other five replay it. + assert_eq!(replays(&proxy) - before, 5, "first wave"); + // A second wave goes through the promoted rebuilt client, whose token is + // spent. At most one of its requests can reuse the pooled tunnel, so at + // least five replay. + let before = replays(&proxy); + gated_wave(&proxy, &client, &origin).await; + assert!(replays(&proxy) - before >= 5, "second wave"); let seen = proxy.seen.lock().unwrap(); assert_negotiate_only(&seen); let rejected = seen.connects.iter().filter(|(_, s)| *s == 407).count(); let accepted = seen.connects.len() - rejected; - // At least 4 concurrent tunnels beyond the 6 sequential sessions, and - // every token was used for exactly one accepted tunnel: 7 preemptive + // Every token was used for exactly one accepted tunnel: 7 preemptive // ones plus one regenerated token per 407 (so at most one 407 each). - assert!(accepted >= 6 + 4, "accepted {accepted}"); + assert!(rejected >= 10, "rejected {rejected}"); assert_eq!( accepted, 7 + rejected, @@ -379,8 +416,8 @@ async fn negotiate_token_failure_fails_before_any_io() { } /// A slow first token (session open) or redirect-probe token is created off -/// the async workers: on a single-threaded runtime an unrelated timer still -/// fires while the callback blocks, and the failure still fails closed. +/// the async workers: on a single-threaded runtime an unrelated task still +/// runs while the callback blocks, and the failure still fails closed. #[tokio::test(flavor = "current_thread")] async fn negotiate_slow_token_does_not_block_async_workers() { // (case, the token call that is slow and then fails) @@ -388,21 +425,36 @@ async fn negotiate_slow_token_does_not_block_async_workers() { for (case, slow_call) in cases { let proxy = StubProxy::start(false, Duration::ZERO).await; let calls = Arc::new(AtomicUsize::new(0)); - let ticked = Arc::new(std::sync::atomic::AtomicBool::new(false)); - let ticked_during_token = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let signalled = Arc::new(std::sync::atomic::AtomicBool::new(false)); + // The callback announces that it has started blocking; an async task + // answers over `signal` only once it runs, which needs the worker free. + let (entered_tx, mut entered_rx) = tokio::sync::mpsc::unbounded_channel::<()>(); + let (signal_tx, signal_rx) = std::sync::mpsc::channel::<()>(); + let signal_rx = Mutex::new(signal_rx); let callback = { - let (calls, ticked) = (calls.clone(), ticked.clone()); - let during = ticked_during_token.clone(); + let (calls, signalled) = (calls.clone(), signalled.clone()); NegotiateTokenCallback::new(move || { let n = calls.fetch_add(1, Ordering::SeqCst) + 1; if n != slow_call { return Ok(format!("tok-{n}").into_bytes()); } - std::thread::sleep(Duration::from_millis(500)); - during.store(ticked.load(Ordering::SeqCst), Ordering::SeqCst); + let _ = entered_tx.send(()); + // Only a free async worker can run the signalling task. If the + // token is created on the worker, this expires instead. + let arrived = signal_rx + .lock() + .unwrap() + .recv_timeout(Duration::from_secs(10)) + .is_ok(); + signalled.store(arrived, Ordering::SeqCst); Err("no Kerberos credentials".to_string()) }) }; + let signaller = tokio::spawn(async move { + if entered_rx.recv().await.is_some() { + let _ = signal_tx.send(()); + } + }); let proxy_config = crate::config::ProxyConfig { url: Some(proxy.url.clone()), auth: ProxyAuth::NegotiateCallback(callback), @@ -416,13 +468,6 @@ async fn negotiate_slow_token_does_not_block_async_workers() { DatabricksHttpClient::with_default_retry(config).unwrap() }); - let ticker = { - let ticked = ticked.clone(); - tokio::spawn(async move { - tokio::time::sleep(Duration::from_millis(20)).await; - ticked.store(true, Ordering::SeqCst); - }) - }; let err = match probe_client { None => crate::session::Session::builder() .connection(crate::config::ConnectionConfig::new( @@ -443,11 +488,11 @@ async fn negotiate_slow_token_does_not_block_async_workers() { .await .unwrap_err(), }; - ticker.await.unwrap(); + signaller.abort(); assert!( - ticked_during_token.load(Ordering::SeqCst), - "{case}: the timer could not fire while the token was created" + signalled.load(Ordering::SeqCst), + "{case}: no async task ran while the token was created (or the token was never created)" ); assert_eq!(calls.load(Ordering::SeqCst), slow_call, "{case}"); assert_eq!( @@ -548,11 +593,18 @@ async fn negotiate_deadline_spans_redirects_token_and_body() { // the cross-origin hop's 407, and the final body (as reqwest does for // the redirects it follows itself). Each case would succeed if every // hop restarted the timeout. + // Margins: the case must reach its timeout, with the second hop (and for + // the body case, its headers) at the origin before the deadline. The + // slack is 600 ms for the redirect case and 400 ms for the body case, + // covering the new tunnel, TLS and client rebuild on a loaded runner. + // A per-hop restart would let each case finish within about 2x its budget. let ms = Duration::from_millis; let cases = [ // (name, path, origin delay, token delay, timeout, origin hops) - ("delayed redirect", "/r307", ms(500), ms(0), ms(800), 2), - ("delayed body", "/rbody", ms(400), ms(0), ms(1000), 2), + // Hop 1 answers at 1000 ms, hop 2 would answer at about 2000 ms. + ("delayed redirect", "/r307", ms(1000), ms(0), ms(1600), 2), + // Hop 1 answers at 800 ms, headers at about 1600 ms, body at 2400 ms. + ("delayed body", "/rbody", ms(800), ms(0), ms(2000), 2), ("slow fresh token", "/r307", ms(0), ms(1500), ms(500), 1), ]; for (name, path, delay, slow, timeout, hops) in cases { @@ -584,7 +636,7 @@ async fn negotiate_deadline_spans_redirects_token_and_body() { }; let elapsed = started.elapsed(); assert!(outcome.is_err(), "{name}: completed in {elapsed:?}"); - assert!(elapsed < timeout + ms(300), "{name}: took {elapsed:?}"); + assert!(elapsed < timeout + ms(1000), "{name}: took {elapsed:?}"); let seen = proxy.seen.lock().unwrap(); assert_eq!(seen.requests.len(), hops, "{name}: {:?}", seen.requests); assert_eq!(seen.connects[..2], one_replay_407()[..2], "{name}"); From e27c50da8293cf73c8d0c905175f172ba9825319 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:15:30 +0000 Subject: [PATCH 04/18] chore(proxy): keep adbc/NOTICE in sync with NOTICE The license check requires adbc/NOTICE to match NOTICE byte for byte. Copy the optional cross-krb5 entry into it, and separate that entry from the one before it like every other entry. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- NOTICE | 2 ++ adbc/NOTICE | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/NOTICE b/NOTICE index 0a01b892..098df5a8 100644 --- a/NOTICE +++ b/NOTICE @@ -35,6 +35,8 @@ Copyright: Copyright (c) 2014--2026, Kang Seonghoon and contributors; Copyright Package: chrono-tz Project URL: https://github.com/chronotope/chrono-tz Copyright: Copyright (c) 2016-2024 Benjamin Sago & the chronotope maintainers + + Package: cross-krb5 (optional, `proxy-negotiate` feature; links the system GSSAPI library, e.g. MIT `libgssapi_krb5`) Project URL: https://github.com/estokes/cross-krb5 Copyright: Copyright cross-krb5 Authors. diff --git a/adbc/NOTICE b/adbc/NOTICE index cdc63bbf..098df5a8 100644 --- a/adbc/NOTICE +++ b/adbc/NOTICE @@ -37,6 +37,11 @@ Project URL: https://github.com/chronotope/chrono-tz Copyright: Copyright (c) 2016-2024 Benjamin Sago & the chronotope maintainers +Package: cross-krb5 (optional, `proxy-negotiate` feature; links the system GSSAPI library, e.g. MIT `libgssapi_krb5`) +Project URL: https://github.com/estokes/cross-krb5 +Copyright: Copyright cross-krb5 Authors. + + Package: dashmap Project URL: https://github.com/xacrimon/dashmap Copyright: Copyright (c) 2025 Joel Wejdenstål From 4624e8792752bcc73d4c07ca72f2015b72a7039c Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:51:07 +0000 Subject: [PATCH 05/18] fix(oauth): drop the endpoint URL from U2M token-request errors The token request and token-response read errors now format the reqwest error without its URL, as request errors elsewhere already do. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- src/auth/oauth/u2m.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/auth/oauth/u2m.rs b/src/auth/oauth/u2m.rs index 98cbd888..40adc0c7 100644 --- a/src/auth/oauth/u2m.rs +++ b/src/auth/oauth/u2m.rs @@ -72,14 +72,16 @@ pub(crate) async fn send_token_request( let request = reqwest::Request::try_from(request).map_err(|e| { Error::invalid_argument().message(format!("failed to build token request: {e}")) })?; - let response = http_client - .send_once(request) - .await? - .map_err(|e| Error::network_error().message(format!("token request failed: {e}")))?; + let response = http_client.send_once(request).await?.map_err(|e| { + Error::network_error().message(format!("token request failed: {}", e.without_url())) + })?; let status = response.status(); let headers = response.headers().clone(); let body = response.bytes().await.map_err(|e| { - Error::network_error().message(format!("failed to read token response: {e}")) + Error::network_error().message(format!( + "failed to read token response: {}", + e.without_url() + )) })?; let mut http_response = HttpResponse::new(body.to_vec()); *http_response.status_mut() = status; From 7ee5f85b010174174d42907f0e9dfa51e92e7e0a Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:00:08 +0000 Subject: [PATCH 06/18] fix(proxy): address review round 2 on the Negotiate client - Make NegotiateTokenCallback's inner closure pub(crate); `new` stays the public constructor. - Pin the CONNECT-407 detection against a real tunnel error from the stub proxy, so a reqwest or hyper-util bump that rewords it fails a test. - Document why concurrent 407 rebuilds are not coalesced. - Document that kernel_session_config_set_proxy_negotiate stays on the config. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- include/databricks_kernel.h | 4 +++- src/c_abi/session.rs | 4 +++- src/client/http.rs | 8 +++++++- src/client/http_negotiate_tests.rs | 32 ++++++++++++++++++++++++++++++ src/config.rs | 2 +- 5 files changed, 46 insertions(+), 4 deletions(-) diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 231c9eda..926b2835 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -466,7 +466,9 @@ KernelStatusCode kernel_session_config_set_proxy(KernelSessionConfig* config, co * the proxy host, the Kerberos default realm. Session open fails before any * network I/O when no token can be created, the proxy also has Basic * credentials or is not http(s)://, `set_proxy` was not called, or the kernel - * was built without the `proxy-negotiate` feature. */ + * was built without the `proxy-negotiate` feature. The setting stays on the + * config (a later call replaces the target; there is no call that clears it), + * so use a new config for a session without Negotiate. */ KernelStatusCode kernel_session_config_set_proxy_negotiate(KernelSessionConfig* config, const char* service, const char* host, const char* realm); diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 5004e713..a6c3bf1e 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -1298,7 +1298,9 @@ pub unsafe extern "C" fn kernel_session_config_set_proxy( /// NULL or empty `service` means `HTTP`, `host` the proxy host and `realm` /// the Kerberos default realm. Session open fails if the proxy has Basic /// credentials, is not `http(s)://`, or the kernel lacks the -/// `proxy-negotiate` feature. Maps to `ProxyAuth::Negotiate`. +/// `proxy-negotiate` feature. Maps to `ProxyAuth::Negotiate`. The setting +/// stays on the config: a later call replaces the target, and no call clears +/// it, so use a new config for a session without Negotiate. /// /// # Safety /// `config` must be a live config handle; the args, if non-null, must be diff --git a/src/client/http.rs b/src/client/http.rs index 34aa1077..e832eb88 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -1120,7 +1120,13 @@ impl DatabricksHttpClient { } }; if rebuilt { - // Its tunnel is up: later requests reuse its pool. + // Its tunnel is up: later requests reuse its pool. Concurrent + // 407s each rebuild their own client and the last one to land + // here wins, so the other rebuilt clients' tunnels close after + // their requests. A later new tunnel then pays the one 407 per + // new tunnel that a replay-caching proxy costs anyway (each + // tunnel needs a token the proxy has not seen); coalescing the + // rebuilds would keep a few more pooled tunnels, not avoid it. *self .negotiate_client .write() diff --git a/src/client/http_negotiate_tests.rs b/src/client/http_negotiate_tests.rs index 63363f24..8b1c4e48 100644 --- a/src/client/http_negotiate_tests.rs +++ b/src/client/http_negotiate_tests.rs @@ -944,6 +944,38 @@ async fn negotiate_rebuild_keeps_the_tls_behavior() { } } +/// The fresh-token retry keys on reqwest's text for hyper-util's private +/// `TunnelError::ProxyAuthRequired`. Pin it against a real CONNECT 407, so a +/// reqwest or hyper-util bump that rewords it fails here, not silently. +#[tokio::test] +async fn proxy_407_is_detected_from_the_real_tunnel_error() { + let proxy = StubProxy::start(true, Duration::ZERO).await; + let (origin, _) = direct_origin().await; + let client = reqwest::Client::builder() + .proxy(reqwest::Proxy::all(&proxy.url).unwrap()) + .build() + .unwrap(); + let err = client.get(&origin).send().await.unwrap_err(); + assert!( + is_proxy_auth_required(&err), + "a CONNECT 407 was not recognised: {err:?}" + ); + + // A proxy that is not listening is a plain connection error, not a 407. + let closed = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let closed_url = format!("http://{}", closed.local_addr().unwrap()); + drop(closed); + let client = reqwest::Client::builder() + .proxy(reqwest::Proxy::all(&closed_url).unwrap()) + .build() + .unwrap(); + let err = client.get(&origin).send().await.unwrap_err(); + assert!( + !is_proxy_auth_required(&err), + "a refused connection looked like a 407: {err:?}" + ); +} + /// The native-tls setup is reused only when OpenSSL reads the same custom /// CA certificates as reqwest (which skips non-`CERTIFICATE` PEM labels). #[cfg(feature = "tls-native")] diff --git a/src/config.rs b/src/config.rs index 3d4eab75..7c341d2a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1162,7 +1162,7 @@ impl std::fmt::Debug for ProxyAuth { /// request closed; the message must not contain token bytes. #[derive(Clone)] pub struct NegotiateTokenCallback( - pub std::sync::Arc std::result::Result, String> + Send + Sync>, + pub(crate) std::sync::Arc std::result::Result, String> + Send + Sync>, ); impl NegotiateTokenCallback { From 2a66825e9cf12baaa45e832bd1853330e3c79540 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:06:53 +0000 Subject: [PATCH 07/18] docs(changelog): note the new client::ProxyConfig field client::ProxyConfig is re-exported as stable surface for advanced wrappers, so code that builds it with a struct literal needs `..Default::default()` now that it has an `auth` field. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- NEXT_CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index fec0060f..a884a9cf 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -24,6 +24,8 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Changed +- `client::ProxyConfig`, the advanced HTTP-client proxy settings, has a new `auth` field. Code that builds it with a struct literal must add `..Default::default()`. + ### Updated ### Fixed From 551e63d172d9f9951aab119b925edaabb6ff5721 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:15:35 +0000 Subject: [PATCH 08/18] fix(pyo3): fail closed after interpreter shutdown and reject a bypass list without a proxy - Fail closed when the Negotiate token callback runs after interpreter shutdown: use Python::try_attach and return an error instead of attaching during finalization. - Raise ValueError for proxy_bypass_hosts without proxy_url instead of silently dropping the bypass list, and document the requirement. - Document that a streaming (non-cloneable) body gets one plain attempt with no 407 retry and no redirect following; all current callers send cloneable JSON or empty bodies. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- pyo3/src/session.rs | 26 +++++++++++++++++++++++--- pyo3/tests/test_proxy_negotiate.py | 11 +++++++++++ src/client/http.rs | 6 ++++++ 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 6f85a844..aa23427f 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -272,6 +272,13 @@ fn build_proxy_config( bypass_hosts: Option, negotiate_token: Option>, ) -> PyResult> { + // The kernel ignores a bypass list without a proxy URL, so reject it here + // rather than drop it silently. + if url.is_none() && bypass_hosts.is_some() { + return Err(pyo3::exceptions::PyValueError::new_err( + "proxy_bypass_hosts requires proxy_url: without a proxy URL the bypass list is ignored", + )); + } if url.is_none() && bypass_hosts.is_none() && negotiate_token.is_none() { return Ok(None); } @@ -286,14 +293,26 @@ fn build_proxy_config( } proxy.auth = databricks_sql_kernel::ProxyAuth::NegotiateCallback( databricks_sql_kernel::NegotiateTokenCallback::new(move || { - Python::attach(|py| { + // The kernel can ask for a token after the interpreter has + // started shutting down (background CloudFetch or telemetry + // requests that get a 407). `try_attach` returns `None` then + // instead of attaching during finalization, so fail closed. + // The error names no token bytes. + let attached = Python::try_attach(|py| { let value = callable.call0(py).map_err(|e| e.to_string())?; let value = value.bind(py); let bytes = value .cast::() .map_err(|_| "proxy_negotiate_token must return bytes".to_string())?; Ok(bytes.as_bytes().to_vec()) - }) + }); + match attached { + Some(token) => token, + None => Err( + "Python interpreter is not running; no Negotiate token is available" + .to_string(), + ), + } }), ); } @@ -389,7 +408,8 @@ impl Session { /// /// Proxy: `proxy_url` (`http://` or `https://`) overrides the /// `HTTPS_PROXY` / `NO_PROXY` environment variables, with - /// `proxy_bypass_hosts` (comma-separated) as its bypass list. + /// `proxy_bypass_hosts` (comma-separated) as its bypass list. The bypass + /// list requires `proxy_url`: passing it alone raises `ValueError`. /// `proxy_negotiate_token` (requires `proxy_url`) authenticates to it /// with `Proxy-Authorization: Negotiate`: a zero-argument callable /// returning one raw SPNEGO/Kerberos token as `bytes`, called at diff --git a/pyo3/tests/test_proxy_negotiate.py b/pyo3/tests/test_proxy_negotiate.py index a28d5d80..85d25645 100644 --- a/pyo3/tests/test_proxy_negotiate.py +++ b/pyo3/tests/test_proxy_negotiate.py @@ -133,3 +133,14 @@ def test_negotiate_needs_a_plain_http_proxy_url(proxy_url): with pytest.raises(k.KernelError) as exc: open_session(proxy_url, lambda: b"token") assert exc.value.code == "InvalidArgument" + + +def test_bypass_hosts_without_proxy_url_is_a_value_error(): + # Rejected before any connect, so no proxy or warehouse is involved. + with pytest.raises(ValueError, match="proxy_bypass_hosts requires proxy_url"): + k.Session( + host="warehouse.invalid", + http_path="/sql/1.0/warehouses/x", + access_token="not-a-real-token", + proxy_bypass_hosts="localhost", + ) diff --git a/src/client/http.rs b/src/client/http.rs index e832eb88..c0cf4136 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -1061,6 +1061,12 @@ impl DatabricksHttpClient { /// Like reqwest's own redirect handling, one deadline (the request's /// timeout, else the client's) covers every hop, the token rebuild and /// the final response body: each hop is sent with the remaining time. + /// + /// Limit: a request whose body cannot be cloned (a streaming body) gets + /// one plain attempt. It has no 407 retry, and a redirect on it comes back + /// to the caller unfollowed, because the Negotiate client does not follow + /// redirects itself. Every kernel request today has a cloneable body: the + /// callers send JSON bodies (`sea.rs`) or none, so this path is not reached. pub(crate) async fn send_once( &self, request: Request, From 6766fa96722406b58c342972e99636c4ca06f0aa Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:21:45 +0000 Subject: [PATCH 09/18] fix(proxy): refuse plain-HTTP hops under Negotiate reqwest forwards a plain-HTTP request to the proxy with the Negotiate token attached and no tunnel, and a 407 there gets no fresh-token retry. With Negotiate, a plain-HTTP request now fails with InvalidArgument before any I/O, and a redirect to plain HTTP fails with NetworkError before that hop, so the token only ever rides on CONNECT. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- src/client/http.rs | 22 ++++++++++++++++++ src/client/http_negotiate_tests.rs | 36 ++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/src/client/http.rs b/src/client/http.rs index c0cf4136..c739870c 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -1062,6 +1062,10 @@ impl DatabricksHttpClient { /// timeout, else the client's) covers every hop, the token rebuild and /// the final response body: each hop is sent with the remaining time. /// + /// With Negotiate, plain-HTTP requests are refused (`InvalidArgument`, no + /// I/O), and so is a redirect to plain HTTP (`NetworkError`): the token + /// is only ever sent on a `CONNECT`. + /// /// Limit: a request whose body cannot be cloned (a streaming body) gets /// one plain attempt. It has no 407 retry, and a redirect on it comes back /// to the caller unfollowed, because the Negotiate client does not follow @@ -1086,6 +1090,24 @@ impl DatabricksHttpClient { let mut previous = Vec::new(); let mut hop = request; loop { + // The token must ride only on CONNECT. reqwest forwards a plain-HTTP + // request to the proxy with the token and no tunnel, and a 407 there + // is an ordinary response that gets no fresh-token retry. So refuse + // plain-HTTP hops: the request itself, or an https -> http redirect. + if hop.url().scheme() != "https" { + let host = hop.url().host_str().unwrap_or("").to_string(); + return Err(if previous.is_empty() { + Error::invalid_argument().message(format!( + "Negotiate proxy authentication needs https:// requests; refusing a \ + plain-HTTP request to {host}" + )) + } else { + Error::network_error().message(format!( + "Negotiate proxy authentication needs https:// requests; refusing a \ + redirect to plain HTTP at {host}" + )) + }); + } let mut fresh_token = false; let response = loop { // A streaming body cannot be resent: one plain attempt. diff --git a/src/client/http_negotiate_tests.rs b/src/client/http_negotiate_tests.rs index 8b1c4e48..d045f0f9 100644 --- a/src/client/http_negotiate_tests.rs +++ b/src/client/http_negotiate_tests.rs @@ -121,6 +121,9 @@ async fn serve_origin( "/loop" => { "HTTP/1.1 302 Found\r\nLocation: /loop\r\nContent-Length: 0\r\n\r\n".to_string() } + "/downgrade" => "HTTP/1.1 302 Found\r\nLocation: http://other.test/final\r\n\ + Content-Length: 0\r\n\r\n" + .to_string(), // `/r` redirects to another origin, so another tunnel. redirect if redirect.starts_with("/r") => format!( "HTTP/1.1 {} Redirect\r\nLocation: https://other.test/final\r\n\ @@ -587,6 +590,39 @@ async fn negotiate_redirects_stop_after_ten_hops() { assert_eq!(seen.connects.len(), 1, "same origin: one tunnel"); } +/// The token rides only on CONNECT, so a plain-HTTP request (which reqwest +/// would forward to the proxy, token attached, with no tunnel) is refused +/// before any I/O, and an https -> http redirect is refused before its hop. +#[tokio::test] +async fn negotiate_refuses_plain_http_hops() { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let calls = Arc::new(AtomicUsize::new(0)); + let client = client(&proxy, &calls, false).unwrap(); + + let err = get(&client, "http://origin.test/plain").await.unwrap_err(); + assert_eq!(err.code, ErrorCode::InvalidArgument, "{}", err.message); + assert!(err.message.contains("plain-HTTP"), "{}", err.message); + assert!(proxy.seen.lock().unwrap().connects.is_empty()); + + let err = get(&client, "https://origin.test/downgrade") + .await + .unwrap_err(); + assert_eq!(err.code, ErrorCode::NetworkError, "{}", err.message); + assert!( + err.message.contains("redirect to plain HTTP"), + "{}", + err.message + ); + let seen = proxy.seen.lock().unwrap(); + assert_eq!( + seen.requests.len(), + 1, + "only the https hop: {:?}", + seen.requests + ); + assert_negotiate_only(&seen); +} + #[tokio::test] async fn negotiate_deadline_spans_redirects_token_and_body() { // One request timeout covers every hop, the fresh-token rebuild after From 889e73993f6f0fbd9398a8b6a61e2e49d4742699 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:25:15 +0000 Subject: [PATCH 10/18] test(proxy): widen the Negotiate deadline test's margins again The second hop now has 1200 ms (redirect) and 800 ms (body) of slack before the deadline, and the deadline still lands at least 800 ms before the request could finish, so a per-hop timeout restart is still caught. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- src/client/http_negotiate_tests.rs | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/client/http_negotiate_tests.rs b/src/client/http_negotiate_tests.rs index d045f0f9..0f4a7784 100644 --- a/src/client/http_negotiate_tests.rs +++ b/src/client/http_negotiate_tests.rs @@ -631,16 +631,18 @@ async fn negotiate_deadline_spans_redirects_token_and_body() { // hop restarted the timeout. // Margins: the case must reach its timeout, with the second hop (and for // the body case, its headers) at the origin before the deadline. The - // slack is 600 ms for the redirect case and 400 ms for the body case, - // covering the new tunnel, TLS and client rebuild on a loaded runner. - // A per-hop restart would let each case finish within about 2x its budget. + // slack is 1200 ms for the redirect case and 800 ms for the body case, + // covering the new tunnel, TLS and client rebuild on a loaded runner, and + // the deadline still lands at least 800 ms before the request could + // finish. A per-hop restart would let each case finish within about 2x + // its budget, so the test still catches one. let ms = Duration::from_millis; let cases = [ // (name, path, origin delay, token delay, timeout, origin hops) - // Hop 1 answers at 1000 ms, hop 2 would answer at about 2000 ms. - ("delayed redirect", "/r307", ms(1000), ms(0), ms(1600), 2), - // Hop 1 answers at 800 ms, headers at about 1600 ms, body at 2400 ms. - ("delayed body", "/rbody", ms(800), ms(0), ms(2000), 2), + // Hop 1 answers at 2000 ms, hop 2 would answer at about 4000 ms. + ("delayed redirect", "/r307", ms(2000), ms(0), ms(3200), 2), + // Hop 1 answers at 1600 ms, headers at about 3200 ms, body at 4800 ms. + ("delayed body", "/rbody", ms(1600), ms(0), ms(4000), 2), ("slow fresh token", "/r307", ms(0), ms(1500), ms(500), 1), ]; for (name, path, delay, slow, timeout, hops) in cases { @@ -672,7 +674,7 @@ async fn negotiate_deadline_spans_redirects_token_and_body() { }; let elapsed = started.elapsed(); assert!(outcome.is_err(), "{name}: completed in {elapsed:?}"); - assert!(elapsed < timeout + ms(1000), "{name}: took {elapsed:?}"); + assert!(elapsed < timeout + ms(1500), "{name}: took {elapsed:?}"); let seen = proxy.seen.lock().unwrap(); assert_eq!(seen.requests.len(), hops, "{name}: {:?}", seen.requests); assert_eq!(seen.connects[..2], one_replay_407()[..2], "{name}"); From 148200edfe53760bc83a3f403cb3e87edfe3420c Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 3 Dec 2026 00:26:13 +0000 Subject: [PATCH 11/18] fix(proxy): refuse a plain-HTTP tenant-discovery probe under Negotiate The Azure tenant-discovery probe sends through its own client, so it now applies the same https-only rule as send_once. The Negotiate docs also say the rule covers hosts on the bypass list. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- src/client/http.rs | 12 +++++++++++- src/client/http_negotiate_tests.rs | 8 ++++++++ src/config.rs | 4 +++- 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/client/http.rs b/src/client/http.rs index c739870c..1b54a8f3 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -1064,7 +1064,9 @@ impl DatabricksHttpClient { /// /// With Negotiate, plain-HTTP requests are refused (`InvalidArgument`, no /// I/O), and so is a redirect to plain HTTP (`NetworkError`): the token - /// is only ever sent on a `CONNECT`. + /// is only ever sent on a `CONNECT`. This applies to hosts on the bypass + /// list too: reqwest does not expose its bypass matching, and every + /// Databricks endpoint the kernel calls is `https://`. /// /// Limit: a request whose body cannot be cloned (a streaming body) gets /// one plain attempt. It has no 407 retry, and a redirect on it comes back @@ -1240,6 +1242,14 @@ impl DatabricksHttpClient { let client = if matches!(self.config.proxy.auth, crate::config::ProxyAuth::Default) { Self::build_reqwest_client(&self.config, redirect, self.revocation, None)? } else { + // As in `send_once`: the token rides only on CONNECT, so refuse a + // plain-HTTP probe rather than forward it to the proxy with the token. + if reqwest::Url::parse(url).map_or(true, |u| u.scheme() != "https") { + return Err(Error::invalid_argument().message( + "Negotiate proxy authentication needs https:// requests; refusing a \ + plain-HTTP tenant-discovery probe", + )); + } self.build_negotiate_client(redirect).await? }; let response = client.get(url).send().await.map_err(|e| { diff --git a/src/client/http_negotiate_tests.rs b/src/client/http_negotiate_tests.rs index 0f4a7784..40353c1d 100644 --- a/src/client/http_negotiate_tests.rs +++ b/src/client/http_negotiate_tests.rs @@ -604,6 +604,14 @@ async fn negotiate_refuses_plain_http_hops() { assert!(err.message.contains("plain-HTTP"), "{}", err.message); assert!(proxy.seen.lock().unwrap().connects.is_empty()); + // The Azure tenant-discovery probe, which sends through its own client. + let err = client + .first_redirect_location("http://origin.test/aad/auth") + .await + .unwrap_err(); + assert_eq!(err.code, ErrorCode::InvalidArgument, "{}", err.message); + assert!(proxy.seen.lock().unwrap().connects.is_empty()); + let err = get(&client, "https://origin.test/downgrade") .await .unwrap_err(); diff --git a/src/config.rs b/src/config.rs index 7c341d2a..53b860b5 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1109,7 +1109,9 @@ impl std::fmt::Debug for ProxyConfig { /// answers a `CONNECT` with `407`. A second `407` fails the request. Negotiate /// never falls back to Basic, a direct connection or an environment proxy. /// It needs an `http://` or `https://` [`ProxyConfig::url`] and no Basic -/// credentials. +/// credentials. The token is only ever sent on a `CONNECT`, so with +/// Negotiate every request must be `https://`: a plain-HTTP request, or a +/// redirect to one, is refused, even to a host on the bypass list. #[non_exhaustive] #[derive(Clone, Default)] pub enum ProxyAuth { From 47f58690ec0dd4236ae73d196f36bfb0ed54f26d Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 3 Dec 2026 02:26:22 +0000 Subject: [PATCH 12/18] fix(proxy): load GSSAPI at run time on Linux instead of linking it With `proxy-negotiate`, Linux builds linked libgssapi_krb5.so.2, so a binary built with the feature (the OSS ODBC driver) failed to load on machines without MIT Kerberos, even for users who never use Kerberos. Linux and other non-Apple Unix now open libgssapi_krb5.so.2 with dlopen the first time a Negotiate token is needed and make the same GSSAPI calls cross-krb5 made. If the library is missing, Negotiate fails session open (Unauthenticated) with an install hint. macOS (GSS.framework) and Windows (SSPI) keep cross-krb5; their libraries ship with the OS. Linux builds no longer need the GSSAPI headers or libclang. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- CONNECTION_PARAMETERS.md | 2 +- Cargo.toml | 16 +- NEXT_CHANGELOG.md | 2 +- src/client/gssapi_runtime.rs | 504 ++++++++++++++++++++++++++++++++++ src/client/mod.rs | 2 + src/client/proxy_negotiate.rs | 35 ++- src/config.rs | 3 +- 7 files changed, 547 insertions(+), 17 deletions(-) create mode 100644 src/client/gssapi_runtime.rs diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index b28d5687..2e5a07e6 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -204,7 +204,7 @@ userinfo replaced by `***`. | `username` | Proxy basic-auth (SOCKS5: RFC 1929) username. Overrides credentials embedded in `url`. | `None` | | `password` | Proxy basic-auth password. Ignored unless `username` is set. Redacted in `Debug`. | `None` | | `bypass_hosts` | Comma-separated hosts/domains to bypass the proxy, e.g. `localhost,*.internal.corp,.example.com`. | `None` | -| `auth` | `ProxyAuth::Default` (Basic from `username` or the URL, or none), `ProxyAuth::Negotiate { service, host, realm }` (Kerberos with the ambient credential cache / Windows logon; target `service/host[@realm]`, defaults `HTTP`, the proxy host, the default realm) or `ProxyAuth::NegotiateCallback` (tokens from a caller callback). Negotiate sends `Proxy-Authorization: Negotiate` on the proxy `CONNECT` only, creates a token at session open and once more on a proxy 407, and never falls back to Basic, a direct connection or an env proxy. It requires an `http(s)://` `url` and no Basic credentials (`InvalidArgument`); a failed token fails session open before any network I/O (`Unauthenticated`). `Negotiate` needs the non-default cargo feature `proxy-negotiate`, which links the system GSSAPI (`libgssapi_krb5`; building needs its headers and libclang) or uses SSPI on Windows; without it, it is rejected as unsupported. C ABI: `kernel_session_config_set_proxy_negotiate`. Python: `proxy_negotiate_token` (a callable returning `bytes`). | `Default` | +| `auth` | `ProxyAuth::Default` (Basic from `username` or the URL, or none), `ProxyAuth::Negotiate { service, host, realm }` (Kerberos with the ambient credential cache / Windows logon; target `service/host[@realm]`, defaults `HTTP`, the proxy host, the default realm) or `ProxyAuth::NegotiateCallback` (tokens from a caller callback). Negotiate sends `Proxy-Authorization: Negotiate` on the proxy `CONNECT` only, creates a token at session open and once more on a proxy 407, and never falls back to Basic, a direct connection or an env proxy. It requires an `http(s)://` `url` and no Basic credentials (`InvalidArgument`); a failed token fails session open before any network I/O (`Unauthenticated`). `Negotiate` needs the non-default cargo feature `proxy-negotiate`; without it, it is rejected as unsupported. On Linux the feature adds no link dependency: MIT Kerberos (`libgssapi_krb5.so.2`) is loaded only when a token is needed, and if it is missing, `Negotiate` fails session open (`Unauthenticated`) with an install hint. macOS uses GSS.framework (building needs libclang) and Windows uses SSPI. C ABI: `kernel_session_config_set_proxy_negotiate`. Python: `proxy_negotiate_token` (a callable returning `bytes`). | `Default` | ## `TlsConfig` — TLS / SSL (optional) diff --git a/Cargo.toml b/Cargo.toml index 7c34308b..3b9528aa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -170,9 +170,12 @@ jsonwebtoken = { version = "9", default-features = false, features = ["use_pem"] pkcs8 = { version = "0.10", features = ["encryption", "pem", "std"] } # PKCS#8 PEM parsing + PBES2 passphrase decryption # Kerberos/SPNEGO (`Proxy-Authorization: Negotiate`) proxy auth, behind the -# non-default `proxy-negotiate` feature. MIT GSSAPI or Heimdal via -# `libgssapi` on Unix (dynamically links `libgssapi_krb5`; building needs -# the GSSAPI headers and libclang), SSPI on Windows. MIT. +# non-default `proxy-negotiate` feature, on macOS (GSS.framework; building +# needs libclang) and Windows (SSPI), whose libraries ship with the OS. Linux +# and other Unix load MIT GSSAPI (`libgssapi_krb5.so.2`) at run time instead +# (`src/client/gssapi_runtime.rs`), so they link no GSSAPI library and need +# no GSSAPI headers to build. MIT. +[target.'cfg(any(windows, target_vendor = "apple"))'.dependencies] cross-krb5 = { version = "0.5", optional = true, default-features = false } # Windows CryptoAPI for TLS certificate revocation (`src/client/tls_revocation.rs`). @@ -254,9 +257,10 @@ tls-rustls = [ "dep:webpki-roots", "dep:rustls-native-certs", ] -# Kerberos token generation for `ProxyAuth::Negotiate`. Off by default so -# default builds link no GSSAPI library; without it `Negotiate` is rejected -# as unsupported. `ProxyAuth::NegotiateCallback` works either way. +# Kerberos token generation for `ProxyAuth::Negotiate`; without it `Negotiate` +# is rejected as unsupported. On Linux the feature adds no link dependency: +# MIT GSSAPI is loaded only when a token is needed (see `cross-krb5` above). +# `ProxyAuth::NegotiateCallback` works either way. proxy-negotiate = ["dep:cross-krb5"] [lib] diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 55a29b27..596bedd7 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -22,7 +22,7 @@ changes go in their respective binding's NEXT_CHANGELOG. if the host has credentials, a path, query or fragment. - `ProxyConfig.url`, the Rust ADBC driver's `adbc.databricks.proxy.url`, `HTTPS_PROXY` and `ALL_PROXY` accept SOCKS4 and SOCKS5 proxy URLs. -- Kerberos (`Proxy-Authorization: Negotiate`) authentication to HTTP proxies via `ProxyConfig::auth` / `ProxyAuth::Negotiate` and the C ABI setter `kernel_session_config_set_proxy_negotiate`. Requires the non-default cargo feature `proxy-negotiate`, which links the system GSSAPI library (SSPI on Windows). +- Kerberos (`Proxy-Authorization: Negotiate`) authentication to HTTP proxies via `ProxyConfig::auth` / `ProxyAuth::Negotiate` and the C ABI setter `kernel_session_config_set_proxy_negotiate`, behind the non-default cargo feature `proxy-negotiate`. On Linux it loads MIT Kerberos (`libgssapi_krb5.so.2`) only when used, so builds with the feature still run without it. ### Changed diff --git a/src/client/gssapi_runtime.rs b/src/client/gssapi_runtime.rs new file mode 100644 index 00000000..34ca2b5e --- /dev/null +++ b/src/client/gssapi_runtime.rs @@ -0,0 +1,504 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! MIT Kerberos GSSAPI loaded at run time (Linux and other non-Apple Unix). +//! +//! `libgssapi_krb5.so.2` is opened with `dlopen` the first time a Negotiate +//! token is needed, never at load time. A binary built with the +//! `proxy-negotiate` feature therefore has no `NEEDED` entry for it: it loads +//! and runs on a machine without MIT Kerberos, and only +//! `ProxyAuth::Negotiate` fails there, closed, with an install hint. +//! +//! The calls are the ones `cross-krb5` makes on Unix: the default initiator +//! credential for the krb5 mechanism, the target imported as a krb5 principal +//! name and canonicalized, and the first `gss_init_sec_context` token (raw +//! krb5, with integrity, mutual authentication and confidentiality +//! requested). Errors read like libgssapi's: the major status text, then the +//! minor status in parentheses. macOS (GSS.framework) and Windows (SSPI) ship +//! their libraries with the OS and keep linking them through `cross-krb5`. + +use std::ffi::{c_int, c_void, CStr}; +use std::ptr; +use std::sync::OnceLock; + +/// The MIT GSSAPI library: package `libgssapi-krb5-2` on Debian and Ubuntu, +/// `krb5-libs` on RHEL and Fedora. +const LIBRARY: &CStr = c"libgssapi_krb5.so.2"; + +type OmUint32 = u32; +type GssName = *mut c_void; +type GssCtx = *mut c_void; +type GssCred = *mut c_void; + +/// `gss_buffer_desc`. +#[repr(C)] +struct Buffer { + length: usize, + value: *mut c_void, +} + +/// `gss_OID_desc`. +#[repr(C)] +struct Oid { + length: OmUint32, + elements: *mut c_void, +} + +/// `gss_OID_set_desc`. +#[repr(C)] +struct OidSet { + count: usize, + elements: *mut Oid, +} + +/// The krb5 mechanism, 1.2.840.113554.1.2.2 (`gss_mech_krb5`). +const KRB5_MECH: &[u8] = b"\x2a\x86\x48\x86\xf7\x12\x01\x02\x02"; +/// The krb5 principal name type, 1.2.840.113554.1.2.2.1 +/// (`GSS_KRB5_NT_PRINCIPAL_NAME`). +const KRB5_NT_PRINCIPAL_NAME: &[u8] = b"\x2a\x86\x48\x86\xf7\x12\x01\x02\x02\x01"; + +const GSS_C_INDEFINITE: OmUint32 = 0xffff_ffff; +const GSS_C_INITIATE: c_int = 1; +const GSS_C_GSS_CODE: c_int = 1; +const GSS_C_MECH_CODE: c_int = 2; +const GSS_C_MUTUAL_FLAG: OmUint32 = 2; +const GSS_C_CONF_FLAG: OmUint32 = 16; +const GSS_C_INTEG_FLAG: OmUint32 = 32; +const GSS_S_COMPLETE: OmUint32 = 0; +const GSS_S_CONTINUE_NEEDED: OmUint32 = 1; +/// The calling-error and routine-error bits of a major status (RFC 2744 +/// `GSS_ERROR`); the low 16 bits are supplementary information. +const GSS_ERROR_BITS: OmUint32 = 0xffff_0000; + +// C signatures from RFC 2744 and MIT's gssapi.h. +type AcquireCred = unsafe extern "C" fn( + *mut OmUint32, + GssName, + OmUint32, + *mut OidSet, + c_int, + *mut GssCred, + *mut *mut OidSet, + *mut OmUint32, +) -> OmUint32; +type ReleaseCred = unsafe extern "C" fn(*mut OmUint32, *mut GssCred) -> OmUint32; +type ImportName = + unsafe extern "C" fn(*mut OmUint32, *mut Buffer, *mut Oid, *mut GssName) -> OmUint32; +type CanonicalizeName = + unsafe extern "C" fn(*mut OmUint32, GssName, *mut Oid, *mut GssName) -> OmUint32; +type ReleaseName = unsafe extern "C" fn(*mut OmUint32, *mut GssName) -> OmUint32; +type InitSecContext = unsafe extern "C" fn( + *mut OmUint32, + GssCred, + *mut GssCtx, + GssName, + *mut Oid, + OmUint32, + OmUint32, + *mut c_void, + *mut Buffer, + *mut *mut Oid, + *mut Buffer, + *mut OmUint32, + *mut OmUint32, +) -> OmUint32; +type DeleteSecContext = unsafe extern "C" fn(*mut OmUint32, *mut GssCtx, *mut Buffer) -> OmUint32; +type ReleaseBuffer = unsafe extern "C" fn(*mut OmUint32, *mut Buffer) -> OmUint32; +type DisplayStatus = unsafe extern "C" fn( + *mut OmUint32, + OmUint32, + c_int, + *mut Oid, + *mut OmUint32, + *mut Buffer, +) -> OmUint32; + +/// The GSSAPI functions this module calls. The library handle is never +/// closed, so the pointers stay valid for the life of the process. +struct Gss { + acquire_cred: AcquireCred, + release_cred: ReleaseCred, + import_name: ImportName, + canonicalize_name: CanonicalizeName, + release_name: ReleaseName, + init_sec_context: InitSecContext, + delete_sec_context: DeleteSecContext, + release_buffer: ReleaseBuffer, + display_status: DisplayStatus, +} + +/// The library, opened once per process on first use. A failed load is kept +/// too, so every later Negotiate attempt fails the same way at once. +static GSS: OnceLock> = OnceLock::new(); + +fn library() -> Result<&'static Gss, String> { + GSS.get_or_init(|| load(LIBRARY)) + .as_ref() + .map_err(String::clone) +} + +/// The text of the last `dlopen` / `dlsym` failure on this thread. +fn dl_error() -> String { + // SAFETY: `dlerror` returns NULL or a NUL-terminated string that stays + // valid until the next dl* call on this thread; it is copied at once. + unsafe { + let message = libc::dlerror(); + if message.is_null() { + "unknown error".to_string() + } else { + CStr::from_ptr(message).to_string_lossy().into_owned() + } + } +} + +fn load(library: &CStr) -> Result { + let name = library.to_string_lossy(); + // SAFETY: `library` is NUL-terminated. Loading runs the library's + // initializers, as linking it at load time did. + let handle = unsafe { libc::dlopen(library.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) }; + if handle.is_null() { + return Err(format!( + "MIT Kerberos (GSSAPI) is not installed or could not be loaded: {}. Install \ + libgssapi-krb5-2 (Debian, Ubuntu) or krb5-libs (RHEL, Fedora)", + dl_error() + )); + } + let symbol = |symbol: &CStr| { + // SAFETY: `handle` is a live handle and `symbol` is NUL-terminated. + let address = unsafe { libc::dlsym(handle, symbol.as_ptr()) }; + if address.is_null() { + Err(format!( + "{name} has no {}: {}", + symbol.to_string_lossy(), + dl_error() + )) + } else { + Ok(address) + } + }; + let resolve = || -> Result { + // SAFETY: each address is the MIT GSSAPI function of that name, and + // each target type is that function's C signature (RFC 2744). + unsafe { + Ok(Gss { + acquire_cred: std::mem::transmute::<*mut c_void, AcquireCred>(symbol( + c"gss_acquire_cred", + )?), + release_cred: std::mem::transmute::<*mut c_void, ReleaseCred>(symbol( + c"gss_release_cred", + )?), + import_name: std::mem::transmute::<*mut c_void, ImportName>(symbol( + c"gss_import_name", + )?), + canonicalize_name: std::mem::transmute::<*mut c_void, CanonicalizeName>(symbol( + c"gss_canonicalize_name", + )?), + release_name: std::mem::transmute::<*mut c_void, ReleaseName>(symbol( + c"gss_release_name", + )?), + init_sec_context: std::mem::transmute::<*mut c_void, InitSecContext>(symbol( + c"gss_init_sec_context", + )?), + delete_sec_context: std::mem::transmute::<*mut c_void, DeleteSecContext>(symbol( + c"gss_delete_sec_context", + )?), + release_buffer: std::mem::transmute::<*mut c_void, ReleaseBuffer>(symbol( + c"gss_release_buffer", + )?), + display_status: std::mem::transmute::<*mut c_void, DisplayStatus>(symbol( + c"gss_display_status", + )?), + }) + } + }; + resolve().inspect_err(|_| { + // SAFETY: nothing from this handle escapes when resolving fails. + unsafe { libc::dlclose(handle) }; + }) +} + +/// An OID over static bytes. GSSAPI takes `gss_OID` as non-const for +/// historical reasons but only reads it. +fn oid(bytes: &'static [u8]) -> Oid { + Oid { + length: bytes.len() as OmUint32, + elements: bytes.as_ptr() as *mut c_void, + } +} + +/// A buffer GSSAPI allocated, released on drop. +struct Output<'a> { + gss: &'a Gss, + buffer: Buffer, +} + +impl<'a> Output<'a> { + fn new(gss: &'a Gss) -> Self { + Output { + gss, + buffer: Buffer { + length: 0, + value: ptr::null_mut(), + }, + } + } + + fn bytes(&self) -> &[u8] { + if self.buffer.value.is_null() { + return &[]; + } + // SAFETY: GSSAPI filled `buffer` with `length` bytes at `value`; + // they stay valid until the buffer is released on drop. + unsafe { std::slice::from_raw_parts(self.buffer.value as *const u8, self.buffer.length) } + } +} + +impl Drop for Output<'_> { + fn drop(&mut self) { + if !self.buffer.value.is_null() { + let mut minor = 0; + // SAFETY: the buffer came from GSSAPI and is released once. + unsafe { (self.gss.release_buffer)(&mut minor, &mut self.buffer) }; + } + } +} + +/// A credential handle, released on drop. +struct Cred<'a> { + gss: &'a Gss, + handle: GssCred, +} + +impl Drop for Cred<'_> { + fn drop(&mut self) { + if !self.handle.is_null() { + let mut minor = 0; + // SAFETY: the handle came from `gss_acquire_cred` and is released once. + unsafe { (self.gss.release_cred)(&mut minor, &mut self.handle) }; + } + } +} + +/// A name handle, released on drop. +struct Name<'a> { + gss: &'a Gss, + handle: GssName, +} + +impl Drop for Name<'_> { + fn drop(&mut self) { + if !self.handle.is_null() { + let mut minor = 0; + // SAFETY: the handle came from GSSAPI and is released once. + unsafe { (self.gss.release_name)(&mut minor, &mut self.handle) }; + } + } +} + +/// A security context, deleted on drop (no output token). +struct Context<'a> { + gss: &'a Gss, + handle: GssCtx, +} + +impl Drop for Context<'_> { + fn drop(&mut self) { + if !self.handle.is_null() { + let mut minor = 0; + // SAFETY: the handle came from `gss_init_sec_context` and is + // deleted once; a NULL output token is allowed. + unsafe { (self.gss.delete_sec_context)(&mut minor, &mut self.handle, ptr::null_mut()) }; + } + } +} + +/// The parts of a status code's text (`gss_display_status` may return more +/// than one). +fn status_parts(gss: &Gss, code: OmUint32, kind: c_int) -> Vec { + let mut parts = Vec::new(); + let mut message_context: OmUint32 = 0; + // Bounded, in case a library never clears `message_context`. + for _ in 0..8 { + let mut minor = 0; + let mut text = Output::new(gss); + // SAFETY: all pointers are to live locals; a NULL mechanism selects + // the default one, as libgssapi does. + let major = unsafe { + (gss.display_status)( + &mut minor, + code, + kind, + ptr::null_mut(), + &mut message_context, + &mut text.buffer, + ) + }; + if major != GSS_S_COMPLETE && major != GSS_S_CONTINUE_NEEDED { + parts.push(format!("unknown GSSAPI status code {code}")); + break; + } + parts.push(String::from_utf8_lossy(text.bytes()).into_owned()); + if message_context == 0 { + break; + } + } + parts +} + +/// `Err` with libgssapi's message format when `major` is an error. +fn check(gss: &Gss, major: OmUint32, minor: OmUint32) -> Result<(), String> { + if major & GSS_ERROR_BITS == 0 { + return Ok(()); + } + let mut message = status_parts(gss, major, GSS_C_GSS_CODE).concat(); + for part in status_parts(gss, minor, GSS_C_MECH_CODE) { + message.push_str(&format!(" ({part})")); + } + Err(message) +} + +/// The first Kerberos token for `target` (`service/host[@realm]`), with the +/// ambient credentials (the credential cache). Loads the library on first +/// use. Blocking: GSSAPI may contact the KDC. +pub(crate) fn initial_token(target: &str) -> Result, String> { + let gss = library()?; + let mut mech = oid(KRB5_MECH); + let mech_ptr: *mut Oid = &mut mech; + let mut minor = 0; + + let mut mechs = OidSet { + count: 1, + elements: mech_ptr, + }; + let mut cred = Cred { + gss, + handle: ptr::null_mut(), + }; + // SAFETY: all pointers are to live locals; a NULL desired name means + // the default principal, and NULL outputs are optional (RFC 2744). + let major = unsafe { + (gss.acquire_cred)( + &mut minor, + ptr::null_mut(), + GSS_C_INDEFINITE, + &mut mechs, + GSS_C_INITIATE, + &mut cred.handle, + ptr::null_mut(), + ptr::null_mut(), + ) + }; + check(gss, major, minor)?; + + let mut input = Buffer { + length: target.len(), + value: target.as_ptr() as *mut c_void, + }; + let mut name_type = oid(KRB5_NT_PRINCIPAL_NAME); + let mut name = Name { + gss, + handle: ptr::null_mut(), + }; + // SAFETY: `input` covers `target`'s bytes, which GSSAPI copies and does + // not write; the other pointers are to live locals. + let major = + unsafe { (gss.import_name)(&mut minor, &mut input, &mut name_type, &mut name.handle) }; + check(gss, major, minor)?; + + let mut canonical = Name { + gss, + handle: ptr::null_mut(), + }; + // SAFETY: `name.handle` is a live name; the other pointers are to live locals. + let major = unsafe { + (gss.canonicalize_name)(&mut minor, name.handle, mech_ptr, &mut canonical.handle) + }; + check(gss, major, minor)?; + + let mut context = Context { + gss, + handle: ptr::null_mut(), + }; + let mut token = Output::new(gss); + // SAFETY: the credential and name handles are live; no channel bindings, + // no input token (the first call), and the optional outputs are NULL. + let major = unsafe { + (gss.init_sec_context)( + &mut minor, + cred.handle, + &mut context.handle, + canonical.handle, + mech_ptr, + GSS_C_MUTUAL_FLAG | GSS_C_CONF_FLAG | GSS_C_INTEG_FLAG, + GSS_C_INDEFINITE, + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut(), + &mut token.buffer, + ptr::null_mut(), + ptr::null_mut(), + ) + }; + check(gss, major, minor)?; + match token.bytes() { + [] => Err("expected token".to_string()), + bytes => Ok(bytes.to_vec()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn missing_library_fails_with_an_install_hint() { + let err = load(c"libdatabricks-no-such-gssapi.so.2") + .err() + .expect("a library that does not exist must not load"); + assert!( + err.contains("MIT Kerberos (GSSAPI) is not installed"), + "{err}" + ); + assert!(err.contains("libdatabricks-no-such-gssapi.so.2"), "{err}"); + assert!(err.contains("libgssapi-krb5-2"), "{err}"); + assert!(err.contains("krb5-libs"), "{err}"); + } + + /// With the library present, a token for a principal in a realm that does + /// not exist fails, and the error carries the major and minor status text. + /// Skipped where MIT Kerberos is not installed. + #[test] + fn token_failure_reports_gssapi_status() { + if let Err(e) = library() { + eprintln!("skipped: {e}"); + return; + } + let err = initial_token("HTTP/proxy.invalid@DATABRICKS-KERNEL-TEST.INVALID") + .expect_err("no credentials or KDC exist for this realm"); + assert!(!err.is_empty()); + assert!( + err.contains(" ("), + "major status, then the minor in parentheses: {err}" + ); + assert!(!err.contains("unknown GSSAPI status code"), "{err}"); + } + + #[test] + fn oids_match_rfc_1964() { + // 1.2.840.113554.1.2.2 and 1.2.840.113554.1.2.2.1, DER-encoded. + assert_eq!(KRB5_MECH.len(), 9); + assert_eq!(&KRB5_NT_PRINCIPAL_NAME[..9], KRB5_MECH); + assert_eq!(KRB5_NT_PRINCIPAL_NAME[9], 0x01); + } +} diff --git a/src/client/mod.rs b/src/client/mod.rs index 89a81e89..01fa7806 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -31,6 +31,8 @@ //! [`transport`]: self::transport //! [`sea`]: self::sea +#[cfg(all(feature = "proxy-negotiate", unix, not(target_vendor = "apple")))] +mod gssapi_runtime; pub mod http; pub(crate) mod proxy_negotiate; pub mod retry; diff --git a/src/client/proxy_negotiate.rs b/src/client/proxy_negotiate.rs index 35dc196a..c655fb40 100644 --- a/src/client/proxy_negotiate.rs +++ b/src/client/proxy_negotiate.rs @@ -155,21 +155,40 @@ fn target_name( #[cfg(feature = "proxy-negotiate")] fn kerberos_token(target: &str) -> Result> { - // Ambient credentials (`None` principal); no delegation. Unix sends a - // raw Kerberos token (accepted under `Negotiate` by MIT/Heimdal - // acceptors); Windows uses the SSPI Negotiate package. + platform_token(target).map_err(|e| { + Error::unauthenticated().message(format!( + "Negotiate proxy authentication failed: no Kerberos token for {target}: {e}" + )) + }) +} + +/// Linux and other non-Apple Unix: MIT GSSAPI, loaded at run time only when +/// a token is needed, so the binary does not depend on it. A raw Kerberos +/// token, accepted under `Negotiate` by MIT and Heimdal acceptors. +#[cfg(all(feature = "proxy-negotiate", unix, not(target_vendor = "apple")))] +fn platform_token(target: &str) -> std::result::Result, String> { + super::gssapi_runtime::initial_token(target) +} + +/// macOS (GSS.framework, a raw Kerberos token) and Windows (the SSPI +/// Negotiate package), linked through cross-krb5; both ship with the OS. +/// Ambient credentials (`None` principal); no delegation. +#[cfg(all(feature = "proxy-negotiate", any(windows, target_vendor = "apple")))] +fn platform_token(target: &str) -> std::result::Result, String> { #[cfg(windows)] let flags = cross_krb5::InitiateFlags::NEGOTIATE_TOKEN; #[cfg(not(windows))] let flags = cross_krb5::InitiateFlags::empty(); - let (_pending, token) = cross_krb5::ClientCtx::new(flags, None, target, None).map_err(|e| { - Error::unauthenticated().message(format!( - "Negotiate proxy authentication failed: no Kerberos token for {target}: {e:#}" - )) - })?; + let (_pending, token) = + cross_krb5::ClientCtx::new(flags, None, target, None).map_err(|e| format!("{e:#}"))?; Ok(token.to_vec()) } +#[cfg(all(feature = "proxy-negotiate", not(any(unix, windows))))] +fn platform_token(_target: &str) -> std::result::Result, String> { + Err("Kerberos is not supported on this platform".to_string()) +} + /// Whether a request failed because the proxy answered `CONNECT` with 407. pub(crate) fn is_proxy_auth_required(error: &reqwest::Error) -> bool { // hyper-util's `TunnelError::ProxyAuthRequired` is private; reqwest diff --git a/src/config.rs b/src/config.rs index fce1fbdb..9006bb75 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1123,7 +1123,8 @@ pub enum ProxyAuth { /// Basic credentials from the URL or `username` / `password`, or none. #[default] Default, - /// Kerberos via the platform GSSAPI (MIT or Heimdal) or Windows SSPI, + /// Kerberos via MIT GSSAPI on Linux (`libgssapi_krb5.so.2`, loaded only + /// when a token is needed), GSS.framework on macOS or SSPI on Windows, /// using the caller's ambient credentials (credential cache or logon /// session). No password, keytab or delegation. The target is /// `/[@]`, by default `HTTP/` in the From 8d4ad3952bb1009154f08ffb5846def8b78fdde1 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 3 Dec 2026 03:11:31 +0000 Subject: [PATCH 13/18] fix(proxy): bound the first Negotiate token and fail a probe 407 closed - The first token at session open, and the tenant-discovery probe's token, are created within the request timeout (read_timeout), like a token rebuilt after a 407; a hung GSSAPI or callback call fails with Timeout instead of stalling Session::open. The blocking thread is documented as kept until the call returns. - A 407 on the probe's fresh token is Unauthenticated, as in send_once, not a generic NetworkError. - A failed libgssapi_krb5.so.2 load is no longer cached, so installing MIT Kerberos takes effect without restarting the host. - Document that Linux and macOS send a raw Kerberos token (MIT and Heimdal acceptors accept it; a SPNEGO-only proxy does not) and Windows sends SPNEGO. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- CONNECTION_PARAMETERS.md | 2 +- src/client/gssapi_runtime.rs | 17 ++++++---- src/client/http.rs | 50 +++++++++++++++++++++++----- src/client/http_negotiate_tests.rs | 52 ++++++++++++++++++++++++++++++ src/config.rs | 9 ++++-- 5 files changed, 113 insertions(+), 17 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 2e5a07e6..196393ff 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -204,7 +204,7 @@ userinfo replaced by `***`. | `username` | Proxy basic-auth (SOCKS5: RFC 1929) username. Overrides credentials embedded in `url`. | `None` | | `password` | Proxy basic-auth password. Ignored unless `username` is set. Redacted in `Debug`. | `None` | | `bypass_hosts` | Comma-separated hosts/domains to bypass the proxy, e.g. `localhost,*.internal.corp,.example.com`. | `None` | -| `auth` | `ProxyAuth::Default` (Basic from `username` or the URL, or none), `ProxyAuth::Negotiate { service, host, realm }` (Kerberos with the ambient credential cache / Windows logon; target `service/host[@realm]`, defaults `HTTP`, the proxy host, the default realm) or `ProxyAuth::NegotiateCallback` (tokens from a caller callback). Negotiate sends `Proxy-Authorization: Negotiate` on the proxy `CONNECT` only, creates a token at session open and once more on a proxy 407, and never falls back to Basic, a direct connection or an env proxy. It requires an `http(s)://` `url` and no Basic credentials (`InvalidArgument`); a failed token fails session open before any network I/O (`Unauthenticated`). `Negotiate` needs the non-default cargo feature `proxy-negotiate`; without it, it is rejected as unsupported. On Linux the feature adds no link dependency: MIT Kerberos (`libgssapi_krb5.so.2`) is loaded only when a token is needed, and if it is missing, `Negotiate` fails session open (`Unauthenticated`) with an install hint. macOS uses GSS.framework (building needs libclang) and Windows uses SSPI. C ABI: `kernel_session_config_set_proxy_negotiate`. Python: `proxy_negotiate_token` (a callable returning `bytes`). | `Default` | +| `auth` | `ProxyAuth::Default` (Basic from `username` or the URL, or none), `ProxyAuth::Negotiate { service, host, realm }` (Kerberos with the ambient credential cache / Windows logon; target `service/host[@realm]`, defaults `HTTP`, the proxy host, the default realm) or `ProxyAuth::NegotiateCallback` (tokens from a caller callback). Negotiate sends `Proxy-Authorization: Negotiate` on the proxy `CONNECT` only, creates a token at session open and once more on a proxy 407, and never falls back to Basic, a direct connection or an env proxy. It requires an `http(s)://` `url` and no Basic credentials (`InvalidArgument`); a failed token fails session open before any network I/O (`Unauthenticated`). On Linux and macOS the token is a raw Kerberos token, which MIT and Heimdal acceptors (such as squid's `negotiate_kerberos_auth`) accept; a proxy that accepts only SPNEGO-wrapped tokens rejects it with 407. Windows sends SPNEGO. `Negotiate` needs the non-default cargo feature `proxy-negotiate`; without it, it is rejected as unsupported. On Linux the feature adds no link dependency: MIT Kerberos (`libgssapi_krb5.so.2`) is loaded only when a token is needed, and if it is missing, `Negotiate` fails session open (`Unauthenticated`) with an install hint. macOS uses GSS.framework (building needs libclang) and Windows uses SSPI. C ABI: `kernel_session_config_set_proxy_negotiate`. Python: `proxy_negotiate_token` (a callable returning `bytes`). | `Default` | ## `TlsConfig` — TLS / SSL (optional) diff --git a/src/client/gssapi_runtime.rs b/src/client/gssapi_runtime.rs index 34ca2b5e..1e0deccf 100644 --- a/src/client/gssapi_runtime.rs +++ b/src/client/gssapi_runtime.rs @@ -138,14 +138,19 @@ struct Gss { display_status: DisplayStatus, } -/// The library, opened once per process on first use. A failed load is kept -/// too, so every later Negotiate attempt fails the same way at once. -static GSS: OnceLock> = OnceLock::new(); +/// The library, opened on first use and kept for the life of the process. A +/// failed load is not kept: the next Negotiate attempt tries again, so +/// installing MIT Kerberos takes effect without restarting the host. +static GSS: OnceLock = OnceLock::new(); fn library() -> Result<&'static Gss, String> { - GSS.get_or_init(|| load(LIBRARY)) - .as_ref() - .map_err(String::clone) + if let Some(gss) = GSS.get() { + return Ok(gss); + } + let gss = load(LIBRARY)?; + // If a concurrent first load wins, its functions are kept and this copy + // is dropped; the extra library reference it took is harmless. + Ok(GSS.get_or_init(|| gss)) } /// The text of the last `dlopen` / `dlsym` failure on this thread. diff --git a/src/client/http.rs b/src/client/http.rs index aa4d5230..c0084d88 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -744,7 +744,12 @@ impl DatabricksHttpClient { /// [`Self::with_revocation`] for async callers: with Negotiate the first /// token is created off the async workers (GSSAPI may contact the KDC; a - /// token callback may block). Default proxy auth builds inline. + /// token callback may block), within the request timeout + /// (`read_timeout`), like a token rebuilt after a 407. Default proxy auth + /// builds inline. + /// + /// A token call that times out keeps its blocking thread until it + /// returns: a GSSAPI or callback call cannot be cancelled. pub(crate) async fn with_revocation_async( config: HttpClientConfig, retry_configs: HashMap, @@ -753,11 +758,19 @@ impl DatabricksHttpClient { if matches!(config.proxy.auth, crate::config::ProxyAuth::Default) { return Self::with_revocation(config, retry_configs, revocation); } - tokio::task::spawn_blocking(move || { + let budget = config.read_timeout; + let task = tokio::task::spawn_blocking(move || { Self::with_revocation(config, retry_configs, revocation) - }) - .await - .map_err(|e| Error::internal().message(format!("Negotiate token task failed: {e}")))? + }); + match tokio::time::timeout(budget, task).await { + Ok(joined) => joined.map_err(|e| { + Error::internal().message(format!("Negotiate token task failed: {e}")) + })?, + Err(_) => Err(Error::timeout().message(format!( + "Negotiate proxy authentication timed out: no token within the {budget:?} \ + request timeout" + ))), + } } /// Build a `reqwest::Client` from `config` with the given redirect policy. @@ -1083,7 +1096,9 @@ impl DatabricksHttpClient { /// Build a client with a fresh Negotiate token, off the async workers /// (GSSAPI may contact the KDC; a token callback may block). It reuses - /// the client's TLS setup, so only the token is new. + /// the client's TLS setup, so only the token is new. Callers bound it + /// with a timeout; a timed-out token call keeps its blocking thread until + /// it returns, because a GSSAPI or callback call cannot be cancelled. async fn build_negotiate_client(&self, redirect: reqwest::redirect::Policy) -> Result { let (config, tls) = (self.config.clone(), self.negotiate_tls.clone()); let revocation = self.revocation; @@ -1295,10 +1310,29 @@ impl DatabricksHttpClient { plain-HTTP tenant-discovery probe", )); } - self.build_negotiate_client(redirect).await? + let budget = self.config.read_timeout; + tokio::time::timeout(budget, self.build_negotiate_client(redirect)) + .await + .map_err(|_| { + Error::timeout().message(format!( + "Negotiate proxy authentication timed out: no token within the \ + {budget:?} request timeout" + )) + })?? }; + let negotiate = !matches!(self.config.proxy.auth, crate::config::ProxyAuth::Default); let response = client.get(url).send().await.map_err(|e| { - Error::network_error().message(format!("Redirect-probe request to {url} failed: {e}")) + // The probe's client carries a fresh token, so a 407 fails closed + // as `send_once` does after its retry. + if negotiate && is_proxy_auth_required(&e) { + Error::unauthenticated().message(format!( + "Negotiate proxy authentication failed: the proxy rejected a fresh token \ + (HTTP 407) on the tenant-discovery probe to {url}" + )) + } else { + Error::network_error() + .message(format!("Redirect-probe request to {url} failed: {e}")) + } })?; Ok(response .headers() diff --git a/src/client/http_negotiate_tests.rs b/src/client/http_negotiate_tests.rs index 40353c1d..1a3944a1 100644 --- a/src/client/http_negotiate_tests.rs +++ b/src/client/http_negotiate_tests.rs @@ -404,6 +404,58 @@ async fn negotiate_second_407_fails_closed_without_downgrade() { assert_eq!(direct_hits.load(Ordering::SeqCst), 0); } +/// The tenant-discovery probe fails closed as `send_once` does: a 407 on its +/// fresh token is `Unauthenticated`, not a generic network error. +#[tokio::test] +async fn negotiate_probe_407_is_unauthenticated() { + let proxy = StubProxy::start(true, Duration::ZERO).await; + let calls = Arc::new(AtomicUsize::new(0)); + let client = client(&proxy, &calls, false).unwrap(); + let err = client + .first_redirect_location("https://origin.test/aad/auth") + .await + .unwrap_err(); + assert_eq!(err.code, ErrorCode::Unauthenticated, "{}", err.message); + assert!(err.message.contains("407"), "{}", err.message); + assert!( + !err.message.contains("dG9r"), + "token bytes in error: {}", + err.message + ); + let seen = proxy.seen.lock().unwrap(); + assert_eq!(seen.connects.len(), 1, "one CONNECT with the probe's token"); + assert_negotiate_only(&seen); +} + +/// The first token at session open is bounded by the request timeout: a +/// token call that never returns cannot stall `Session::open`. +#[tokio::test] +async fn negotiate_first_token_times_out() { + let mut config = HttpClientConfig::default(); + config.proxy.url = Some("http://127.0.0.1:9".to_string()); + config.proxy.auth = ProxyAuth::NegotiateCallback(NegotiateTokenCallback::new(|| { + std::thread::sleep(Duration::from_secs(2)); + Ok(b"tok".to_vec()) + })); + config.read_timeout = Duration::from_millis(100); + let retry = crate::client::retry::build_retry_configs( + &RetryConfig::default(), + &std::collections::HashMap::new(), + ); + let started = std::time::Instant::now(); + let err = match DatabricksHttpClient::with_revocation_async(config, retry, None).await { + Ok(_) => panic!("a token slower than the request timeout must fail"), + Err(e) => e, + }; + assert_eq!(err.code, ErrorCode::Timeout, "{}", err.message); + assert!(err.message.contains("no token within"), "{}", err.message); + assert!( + started.elapsed() < Duration::from_secs(1), + "{:?}", + started.elapsed() + ); +} + #[tokio::test] async fn negotiate_token_failure_fails_before_any_io() { let proxy = StubProxy::start(false, Duration::ZERO).await; diff --git a/src/config.rs b/src/config.rs index 9006bb75..8690adf0 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1128,8 +1128,13 @@ pub enum ProxyAuth { /// using the caller's ambient credentials (credential cache or logon /// session). No password, keytab or delegation. The target is /// `/[@]`, by default `HTTP/` in the - /// default realm. Requires the `proxy-negotiate` cargo feature; without - /// it, `Session::open` rejects this variant as unsupported. + /// default realm. On Linux and macOS the token is a raw Kerberos token, + /// which MIT and Heimdal acceptors (such as squid's + /// `negotiate_kerberos_auth`) accept under `Negotiate`; a proxy that + /// accepts only SPNEGO-wrapped tokens rejects it with 407. Windows sends + /// SPNEGO (the SSPI Negotiate package). Requires the `proxy-negotiate` + /// cargo feature; without it, `Session::open` rejects this variant as + /// unsupported. Negotiate { /// Service part of the target name. Default `HTTP`. service: Option, From e297d8d1aac4c39df59e77f0b2c3d973c0a75447 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 3 Dec 2026 03:37:46 +0000 Subject: [PATCH 14/18] fix(proxy): keep a Negotiate token timeout's code at session open - Session::open passes a Timeout from the first Negotiate token through, as it does Unauthenticated, instead of re-wrapping it as NetworkError. - send_once computes its deadline with checked_add, so an extreme request timeout (such as Duration::MAX) cannot overflow Instant. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- src/client/http.rs | 6 ++- src/client/http_negotiate_tests.rs | 67 ++++++++++++++++++++++++++++++ src/session.rs | 7 +++- 3 files changed, 78 insertions(+), 2 deletions(-) diff --git a/src/client/http.rs b/src/client/http.rs index c0084d88..824d34ea 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -1145,7 +1145,11 @@ impl DatabricksHttpClient { .timeout() .copied() .unwrap_or(self.config.read_timeout); - let deadline = tokio::time::Instant::now() + budget; + // An extreme timeout (e.g. `Duration::MAX`) must not overflow `Instant`. + let now = tokio::time::Instant::now(); + let deadline = now + .checked_add(budget) + .unwrap_or_else(|| now + Duration::from_secs(100 * 365 * 24 * 3600)); // An exhausted budget fails the hop with reqwest's own timeout error. let remaining = || deadline.saturating_duration_since(tokio::time::Instant::now()); let mut rebuilt = false; diff --git a/src/client/http_negotiate_tests.rs b/src/client/http_negotiate_tests.rs index 1a3944a1..d4e66ea3 100644 --- a/src/client/http_negotiate_tests.rs +++ b/src/client/http_negotiate_tests.rs @@ -456,6 +456,73 @@ async fn negotiate_first_token_times_out() { ); } +/// `Session::open` keeps the `Timeout` code of a first token slower than the +/// request timeout, instead of reporting a generic network error. +#[tokio::test] +async fn negotiate_session_open_reports_a_token_timeout() { + let proxy_config = crate::config::ProxyConfig { + url: Some("http://127.0.0.1:9".to_string()), + auth: ProxyAuth::NegotiateCallback(NegotiateTokenCallback::new(|| { + std::thread::sleep(Duration::from_secs(2)); + Ok(b"tok".to_vec()) + })), + ..Default::default() + }; + let started = std::time::Instant::now(); + let err = crate::session::Session::builder() + .connection(crate::config::ConnectionConfig::new( + "https://workspace.invalid", + "test_wh", + )) + .auth(crate::config::AuthConfig::Pat { + token: "dapi-test".to_string(), + identity_federation_client_id: None, + }) + .proxy(proxy_config) + .http(crate::config::HttpConfig { + request_timeout: Duration::from_millis(100), + ..Default::default() + }) + .open() + .await + .map(|_| ()) + .unwrap_err(); + assert_eq!(err.code, ErrorCode::Timeout, "{}", err.message); + assert!(err.message.contains("no token within"), "{}", err.message); + assert!( + started.elapsed() < Duration::from_secs(1), + "{:?}", + started.elapsed() + ); +} + +/// An extreme request timeout (`Duration::MAX`) does not overflow the +/// Negotiate deadline: the request still goes through. +#[tokio::test] +async fn negotiate_extreme_timeout_does_not_overflow() { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let calls = Arc::new(AtomicUsize::new(0)); + let callback = { + let calls = calls.clone(); + NegotiateTokenCallback::new(move || { + let n = calls.fetch_add(1, Ordering::SeqCst) + 1; + Ok(format!("tok-{n}").into_bytes()) + }) + }; + let mut config = HttpClientConfig::default(); + config.proxy.url = Some(proxy.url.clone()); + config.proxy.auth = ProxyAuth::NegotiateCallback(callback); + config.tls.allow_self_signed = Some(true); + config.tls.allow_hostname_mismatch = Some(true); + config.read_timeout = Duration::MAX; + let client = DatabricksHttpClient::with_default_retry(config).unwrap(); + client.set_auth_provider(Arc::new(PersonalAccessToken::new("pat".to_string()))); + assert_eq!( + get(&client, "https://origin.test/probe").await.unwrap(), + 200 + ); +} + #[tokio::test] async fn negotiate_token_failure_fails_before_any_io() { let proxy = StubProxy::start(false, Duration::ZERO).await; diff --git a/src/session.rs b/src/session.rs index 0e9daded..5fbe8704 100644 --- a/src/session.rs +++ b/src/session.rs @@ -392,7 +392,12 @@ impl Session { ) .await .map_err(|e| { - if e.code == crate::kernel_error::ErrorCode::Unauthenticated { + // A failed or timed-out Negotiate token keeps its own code. + if matches!( + e.code, + crate::kernel_error::ErrorCode::Unauthenticated + | crate::kernel_error::ErrorCode::Timeout + ) { return e; } Error::network_error().message(format!("Failed to construct HTTP client: {e}")) From d630097e5b8de1788182a2e881d95fa9d42998e5 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 3 Dec 2026 03:47:40 +0000 Subject: [PATCH 15/18] docs(notice): describe how cross-krb5 is linked per platform cross-krb5 is a dependency only on macOS (GSS.framework) and Windows (SSPI); Linux loads MIT libgssapi_krb5.so.2 at run time. NOTICE and adbc/NOTICE stay identical. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- NOTICE | 2 +- adbc/NOTICE | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/NOTICE b/NOTICE index 098df5a8..c211d7e0 100644 --- a/NOTICE +++ b/NOTICE @@ -37,7 +37,7 @@ Project URL: https://github.com/chronotope/chrono-tz Copyright: Copyright (c) 2016-2024 Benjamin Sago & the chronotope maintainers -Package: cross-krb5 (optional, `proxy-negotiate` feature; links the system GSSAPI library, e.g. MIT `libgssapi_krb5`) +Package: cross-krb5 (optional, `proxy-negotiate` feature on macOS and Windows; links GSS.framework or SSPI. Linux loads MIT `libgssapi_krb5.so.2` at run time instead) Project URL: https://github.com/estokes/cross-krb5 Copyright: Copyright cross-krb5 Authors. diff --git a/adbc/NOTICE b/adbc/NOTICE index 098df5a8..c211d7e0 100644 --- a/adbc/NOTICE +++ b/adbc/NOTICE @@ -37,7 +37,7 @@ Project URL: https://github.com/chronotope/chrono-tz Copyright: Copyright (c) 2016-2024 Benjamin Sago & the chronotope maintainers -Package: cross-krb5 (optional, `proxy-negotiate` feature; links the system GSSAPI library, e.g. MIT `libgssapi_krb5`) +Package: cross-krb5 (optional, `proxy-negotiate` feature on macOS and Windows; links GSS.framework or SSPI. Linux loads MIT `libgssapi_krb5.so.2` at run time instead) Project URL: https://github.com/estokes/cross-krb5 Copyright: Copyright cross-krb5 Authors. From 8bb644a2c3e69205024d09a2d1e2538517436a22 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 3 Dec 2026 20:53:07 +0000 Subject: [PATCH 16/18] fix(proxy): retry Volume transfers with a fresh Negotiate token Volume PUT, GET and REMOVE use their own storage client, so they got one Negotiate token at build time, created on an async worker, and no retry when a replay-caching proxy answered a later tunnel's CONNECT with 407. - The storage client's token is created off the async workers within the request timeout, as at session open. - A proxy 407 rebuilds the storage client with a fresh token and resends the request once, recreating its headers and streaming body; later requests use the rebuilt client. A second 407 fails closed as Unauthenticated, not retried, with the URL query left out of the message. - With Negotiate, a plain-HTTP storage URL is refused, as in send_once. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- CONNECTION_PARAMETERS.md | 2 +- src/client/http.rs | 31 ++- src/client/http_negotiate_tests.rs | 47 +++- src/config.rs | 8 +- src/volume.rs | 409 ++++++++++++++++++++++++++--- 5 files changed, 447 insertions(+), 50 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 07c04a67..fd2e5cc8 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -204,7 +204,7 @@ userinfo replaced by `***`. | `username` | Proxy basic-auth (SOCKS5: RFC 1929) username. Overrides credentials embedded in `url`. | `None` | | `password` | Proxy basic-auth password. Ignored unless `username` is set. Redacted in `Debug`. | `None` | | `bypass_hosts` | Comma-separated hosts/domains to bypass the proxy, e.g. `localhost,*.internal.corp,.example.com`. | `None` | -| `auth` | `ProxyAuth::Default` (Basic from `username` or the URL, or none), `ProxyAuth::Negotiate { service, host, realm }` (Kerberos with the ambient credential cache / Windows logon; target `service/host[@realm]`, defaults `HTTP`, the proxy host, the default realm) or `ProxyAuth::NegotiateCallback` (tokens from a caller callback). Negotiate sends `Proxy-Authorization: Negotiate` on the proxy `CONNECT` only, creates a token at session open and once more on a proxy 407, and never falls back to Basic, a direct connection or an env proxy. It requires an `http(s)://` `url` and no Basic credentials (`InvalidArgument`); a failed token fails session open before any network I/O (`Unauthenticated`). On Linux and macOS the token is a raw Kerberos token, which MIT and Heimdal acceptors (such as squid's `negotiate_kerberos_auth`) accept; a proxy that accepts only SPNEGO-wrapped tokens rejects it with 407. Windows sends SPNEGO. `Negotiate` needs the non-default cargo feature `proxy-negotiate`; without it, it is rejected as unsupported. On Linux the feature adds no link dependency: MIT Kerberos (`libgssapi_krb5.so.2`) is loaded only when a token is needed, and if it is missing, `Negotiate` fails session open (`Unauthenticated`) with an install hint. macOS uses GSS.framework (building needs libclang) and Windows uses SSPI. C ABI: `kernel_session_config_set_proxy_negotiate`. Python: `proxy_negotiate_token` (a callable returning `bytes`). | `Default` | +| `auth` | `ProxyAuth::Default` (Basic from `username` or the URL, or none), `ProxyAuth::Negotiate { service, host, realm }` (Kerberos with the ambient credential cache / Windows logon; target `service/host[@realm]`, defaults `HTTP`, the proxy host, the default realm) or `ProxyAuth::NegotiateCallback` (tokens from a caller callback). Negotiate sends `Proxy-Authorization: Negotiate` on the proxy `CONNECT` only, creates a token at session open (and lazily for Volume storage) and retries each request hop once with a fresh token on a proxy 407, including Volume PUT, GET and REMOVE storage requests. A second 407 fails the request; it never falls back to Basic, a direct connection or an env proxy. It requires an `http(s)://` `url` and no Basic credentials (`InvalidArgument`); a failed token fails session open before any network I/O (`Unauthenticated`). On Linux and macOS the token is a raw Kerberos token, which MIT and Heimdal acceptors (such as squid's `negotiate_kerberos_auth`) accept; a proxy that accepts only SPNEGO-wrapped tokens rejects it with 407. Windows sends SPNEGO. `Negotiate` needs the non-default cargo feature `proxy-negotiate`; without it, it is rejected as unsupported. On Linux the feature adds no link dependency: MIT Kerberos (`libgssapi_krb5.so.2`) is loaded only when a token is needed, and if it is missing, `Negotiate` fails session open (`Unauthenticated`) with an install hint. macOS uses GSS.framework (building needs libclang) and Windows uses SSPI. C ABI: `kernel_session_config_set_proxy_negotiate`. Python: `proxy_negotiate_token` (a callable returning `bytes`). | `Default` | ## `TlsConfig` — TLS / SSL (optional) diff --git a/src/client/http.rs b/src/client/http.rs index 42f7ee3c..9ede05ab 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -1069,6 +1069,30 @@ impl DatabricksHttpClient { ) } + /// Storage client construction for async callers. Default proxy auth keeps + /// the inline build; Negotiate token creation runs off the async workers, + /// bounded by the request timeout. A timed-out blocking call cannot be + /// cancelled and keeps its thread until it returns. + pub(crate) async fn storage_client_async( + config: &HttpClientConfig, + revocation: Option, + ) -> Result { + if matches!(config.proxy.auth, crate::config::ProxyAuth::Default) { + return Self::storage_client(config, revocation); + } + let (config, budget) = (config.clone(), config.read_timeout); + let task = tokio::task::spawn_blocking(move || Self::storage_client(&config, revocation)); + match tokio::time::timeout(budget, task).await { + Ok(joined) => joined.map_err(|e| { + Error::internal().message(format!("Negotiate token task failed: {e}")) + })?, + Err(_) => Err(Error::timeout().message(format!( + "Negotiate proxy authentication timed out: no token within the {budget:?} \ + request timeout" + ))), + } + } + /// Returns the client configuration. pub fn config(&self) -> &HttpClientConfig { &self.config @@ -1157,8 +1181,9 @@ impl DatabricksHttpClient { /// Limit: a request whose body cannot be cloned (a streaming body) gets /// one plain attempt. It has no 407 retry, and a redirect on it comes back /// to the caller unfollowed, because the Negotiate client does not follow - /// redirects itself. Every kernel request today has a cloneable body: the - /// callers send JSON bodies (`sea.rs`) or none, so this path is not reached. + /// redirects itself. Kernel callers of this method send cloneable JSON + /// bodies (`sea.rs`) or none. Volume storage requests instead recreate their + /// streaming bodies and handle the proxy 407 retry in `volume.rs`. pub(crate) async fn send_once( &self, request: Request, @@ -1686,7 +1711,7 @@ mod revocation_support_tests { #[cfg(test)] #[path = "http_negotiate_tests.rs"] -mod negotiate_tests; +pub(crate) mod negotiate_tests; #[cfg(test)] #[path = "http_socks_tests.rs"] diff --git a/src/client/http_negotiate_tests.rs b/src/client/http_negotiate_tests.rs index d4e66ea3..1c1ef975 100644 --- a/src/client/http_negotiate_tests.rs +++ b/src/client/http_negotiate_tests.rs @@ -28,23 +28,26 @@ use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; use tokio::net::TcpListener; #[derive(Default)] -struct Seen { +pub(crate) struct Seen { /// (`Proxy-Authorization` of each CONNECT, status the proxy answered). - connects: Vec<(Option, u16)>, + pub(crate) connects: Vec<(Option, u16)>, tokens: HashSet, /// Header names of requests that came through a tunnel. origin_headers: Vec, /// ` ` and header names of each tunnelled request. - requests: Vec<(String, Vec)>, + pub(crate) requests: Vec<(String, Vec)>, + /// Bytes received by the Volume route, which closes each tunnel after replying. + pub(crate) volume_bodies: Vec>, + volume_object: Vec, /// When set, every origin answer waits here until all parties arrive. gate: Option>, /// Gate waits that gave up (a request never arrived, or a tunnel was reused). gate_timeouts: usize, } -struct StubProxy { - url: String, - seen: Arc>, +pub(crate) struct StubProxy { + pub(crate) url: String, + pub(crate) seen: Arc>, } async fn read_head(stream: &mut S) -> Option { @@ -102,6 +105,32 @@ async fn serve_origin( } } tokio::time::sleep(delay).await; + if path.split('?').next() == Some("/volume") { + let payload = { + let mut seen = seen.lock().unwrap(); + if method == "PUT" { + seen.volume_object = body.clone(); + } else if method == "DELETE" { + seen.volume_object.clear(); + } + seen.volume_bodies.push(body); + if method == "GET" { + seen.volume_object.clone() + } else { + Vec::new() + } + }; + let head = format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + payload.len() + ); + if stream.write_all(head.as_bytes()).await.is_ok() { + let _ = stream.write_all(&payload).await; + } + // Every Volume request needs a new tunnel, deterministically + // replaying the current client's token on the next request. + return; + } if path == "/slowbody" { // Headers now, the body one more `delay` later. let head = b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n"; @@ -168,7 +197,7 @@ fn tls_acceptor() -> tokio_rustls::TlsAcceptor { impl StubProxy { /// `reject_all`: answer every CONNECT with 407. `delay`: origin latency. - async fn start(reject_all: bool, delay: Duration) -> Self { + pub(crate) async fn start(reject_all: bool, delay: Duration) -> Self { let acceptor = tls_acceptor(); let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let url = format!("http://{}", listener.local_addr().unwrap()); @@ -214,7 +243,7 @@ impl StubProxy { /// A directly reachable origin that counts connections: any direct /// (non-proxied) attempt would land here. -async fn direct_origin() -> (String, Arc) { +pub(crate) async fn direct_origin() -> (String, Arc) { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let url = format!("https://{}/probe", listener.local_addr().unwrap()); let hits = Arc::new(AtomicUsize::new(0)); @@ -268,7 +297,7 @@ async fn get(client: &DatabricksHttpClient, url: &str) -> Result { Ok(response.status().as_u16()) } -fn assert_negotiate_only(seen: &Seen) { +pub(crate) fn assert_negotiate_only(seen: &Seen) { for (auth, _) in &seen.connects { let auth = auth.as_deref().unwrap_or_default(); assert!( diff --git a/src/config.rs b/src/config.rs index cbc1563b..fdfdf0cb 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1111,9 +1111,11 @@ impl std::fmt::Debug for ProxyConfig { /// /// Both Negotiate variants send `Proxy-Authorization: Negotiate ` on /// the HTTP `CONNECT` to the proxy only, never to the warehouse or storage. -/// A token is created when the HTTP client is built (session open; failure -/// fails the session before any network I/O) and once more when the proxy -/// answers a `CONNECT` with `407`. A second `407` fails the request. Negotiate +/// A token is created when each HTTP client is built (at session open, and +/// lazily for Volume storage); failure stops that operation before network +/// I/O. A proxy `CONNECT` answered with `407` gets one fresh-token retry per +/// request hop, including Volume PUT, GET and REMOVE storage requests. A +/// second `407` fails the request. Negotiate /// never falls back to Basic, a direct connection or an environment proxy. /// It needs an `http://` or `https://` [`ProxyConfig::url`] and no Basic /// credentials. The token is only ever sent on a `CONNECT`, so with diff --git a/src/volume.rs b/src/volume.rs index 49fcf7cd..04af6f87 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -19,7 +19,9 @@ //! module makes the storage request that row describes. use crate::client::http::{DatabricksHttpClient, HttpClientConfig}; +use crate::client::proxy_negotiate::is_proxy_auth_required; use crate::client::retry::{calculate_backoff, RequestType, RetryConfig, RetryStrategy}; +use crate::config::ProxyAuth; use crate::kernel_error::{Error, LocalFileError, Result}; use arrow_array::cast::AsArray; use arrow_array::{Array, ArrayRef, RecordBatch}; @@ -121,6 +123,8 @@ pub(crate) struct Storage { config: HttpClientConfig, revocation: Option, client: OnceCell, + /// The latest client whose fresh Negotiate token established a tunnel. + negotiate_client: std::sync::RwLock>, retry: RetryConfig, idle_limit: Option, cancellation: CancellationToken, @@ -139,6 +143,7 @@ impl Storage { config, revocation, client: OnceCell::new(), + negotiate_client: std::sync::RwLock::new(None), retry, idle_limit: idle_limit.filter(|limit| !limit.is_zero()), cancellation: CancellationToken::new(), @@ -166,12 +171,19 @@ impl Storage { self.cancellation.cancel(); } - async fn client(&self) -> Result<&Client> { - self.client - .get_or_try_init(|| async { - DatabricksHttpClient::storage_client(&self.config, self.revocation) + async fn client(&self) -> Result { + let initial = self + .client + .get_or_try_init(|| { + DatabricksHttpClient::storage_client_async(&self.config, self.revocation) }) - .await + .await?; + Ok(self + .negotiate_client + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .unwrap_or_else(|| initial.clone())) } } @@ -276,19 +288,18 @@ impl VolumeState { input_bytes, ) .await?; - let client = self.storage.client().await?; + // Initial token failures (including timeouts) do not enter storage retries. + self.storage.client().await?; let retry = &self.storage.retry; let strategy = RetryStrategy::for_request(RequestType::CloudFetchDownload, retry); let mut first_failure = None; let mut attempt = 0; loop { - let (error, retry_after) = match self - .attempt(client, &instruction, &local, options, &strategy) - .await - { - Ok(()) => return Ok(local), - Err(failure) => failure, - }; + let (error, retry_after) = + match self.attempt(&instruction, &local, options, &strategy).await { + Ok(()) => return Ok(local), + Err(failure) => failure, + }; let wait = calculate_backoff(retry, attempt, retry_after.as_deref()); // The retry budget runs from the first failure, so a long transfer that // is still making progress keeps the whole budget for a late failure. @@ -310,11 +321,10 @@ impl VolumeState { } } - /// One storage request. A failure carries the response's `Retry-After` - /// value. + /// One storage request, with one fresh-token retry of a rejected proxy + /// CONNECT. A failure carries the response's `Retry-After` value. async fn attempt( &self, - client: &Client, instruction: &Instruction, local: &Local, options: &VolumeOptions, @@ -323,25 +333,82 @@ impl VolumeState { let method = local.method(); let url = Url::parse(&instruction.url) .map_err(|_| (invalid("Invalid Volume storage URL"), None))?; - let (progress, mut progressed) = watch::channel(()); - let mut headers = instruction.headers.clone(); - let mut body = None; - if let Some((chunks, length)) = local.upload() { - headers.insert(CONTENT_LENGTH, length.into()); - body = Some(reqwest::Body::wrap_stream(chunks.inspect_ok(move |_| { - progress.send_replace(()); - }))); + let negotiate = !matches!(self.storage.config.proxy.auth, ProxyAuth::Default); + // A plain-HTTP proxy request would carry the token without a CONNECT. + // As in send_once, refuse it even for hosts on the bypass list. + if negotiate && url.scheme() != "https" { + return Err(( + Error::invalid_argument().message(format!( + "Negotiate proxy authentication needs https:// requests; refusing a \ + plain-HTTP request to {}", + url.host_str().unwrap_or("") + )), + None, + )); } - let mut request = client.request(method.clone(), url).headers(headers); - if let Some(body) = body { - request = request.body(body); + let mut client = self.storage.client().await.map_err(|e| (e, None))?; + let mut fresh_token = false; + let response = loop { + // Recreate everything per send: a streaming PUT body cannot be cloned. + let (progress, mut progressed) = watch::channel(()); + let mut headers = instruction.headers.clone(); + let mut body = None; + if let Some((chunks, length)) = local.upload() { + headers.insert(CONTENT_LENGTH, length.into()); + body = Some(reqwest::Body::wrap_stream(chunks.inspect_ok(move |_| { + progress.send_replace(()); + }))); + } + let mut request = client.request(method.clone(), url.clone()).headers(headers); + if let Some(body) = body { + request = request.body(body); + } + match self + .idle_bounded(&mut progressed, async { Ok(request.send().await) }) + .await + .map_err(|e| (e, None))? + { + Ok(response) => break response, + Err(mut error) if negotiate && is_proxy_auth_required(&error) => { + if fresh_token { + if let Some(url) = error.url_mut() { + url.set_query(None); + } + let mut causes = crate::client::error_chain(&error) + .map(ToString::to_string) + .collect::>(); + causes.dedup(); + return Err(( + Error::unauthenticated() + .message(format!( + "Negotiate proxy authentication failed: the proxy rejected a \ + fresh token (HTTP 407): {}", + causes.join(": ") + )) + .with_retryable(false), + None, + )); + } + client = DatabricksHttpClient::storage_client_async( + &self.storage.config, + self.storage.revocation, + ) + .await + .map_err(|e| (e.with_retryable(false), None))?; + fresh_token = true; + } + Err(error) => return Err((storage_error(error, strategy), None)), + } + }; + if fresh_token { + // Its tunnel is up. Concurrent rebuilds each use their own token; + // the last successful send wins. Never hold the lock over an await. + *self + .storage + .negotiate_client + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(client); } - let response = self - .idle_bounded(&mut progressed, async { - request.send().await.map_err(|e| storage_error(e, strategy)) - }) - .await - .map_err(|e| (e, None))?; let status = response.status(); if status.is_success() || (method == Method::DELETE @@ -1030,14 +1097,25 @@ fn local_error(error: std::io::Error, path: &str) -> Error { #[cfg(test)] mod tests { use super::*; + use crate::client::http::negotiate_tests::{assert_negotiate_only, direct_origin, StubProxy}; + use crate::config::NegotiateTokenCallback; use crate::ErrorCode; use arrow_array::builder::{MapBuilder, StringBuilder}; use arrow_array::StringArray; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use tokio::io::AsyncReadExt; use wiremock::matchers::{body_bytes, header, method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; fn storage(max_retries: u32, idle_limit: Option) -> Arc { + storage_with_config(HttpClientConfig::default(), max_retries, idle_limit) + } + + fn storage_with_config( + config: HttpClientConfig, + max_retries: u32, + idle_limit: Option, + ) -> Arc { let retry = RetryConfig { max_retries, min_wait: Duration::ZERO, @@ -1045,7 +1123,7 @@ mod tests { ..Default::default() }; Arc::new(Storage::new( - HttpClientConfig::default(), + config, None, retry, idle_limit, @@ -1120,6 +1198,269 @@ mod tests { unsafe { libc::geteuid() == 0 } } + fn negotiate_config(proxy: &StubProxy, calls: &Arc) -> HttpClientConfig { + let calls = calls.clone(); + let mut config = HttpClientConfig::default(); + config.proxy.url = Some(proxy.url.clone()); + config.proxy.auth = ProxyAuth::NegotiateCallback(NegotiateTokenCallback::new(move || { + let n = calls.fetch_add(1, Ordering::SeqCst) + 1; + Ok(format!("tok-{n}").into_bytes()) + })); + config.tls.allow_self_signed = Some(true); + config.tls.allow_hostname_mismatch = Some(true); + config + } + + #[tokio::test] + async fn negotiate_storage_get_put_and_remove_survive_replayed_tokens() { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let (origin, direct_hits) = direct_origin().await; + let mut url = Url::parse(&origin).unwrap(); + url.set_path("/volume"); + url.set_query(Some("signature=presigned-secret")); + let calls = Arc::new(AtomicUsize::new(0)); + // No generic retries: every replay must be handled by the 407 retry. + let storage = storage_with_config(negotiate_config(&proxy, &calls), 0, None); + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source"); + let destination = dir.path().join("destination"); + let payload = b"\0\xffvolume bytes".repeat(UPLOAD_CHUNK / 7 + 1); + std::fs::write(&source, &payload).unwrap(); + + // Spend the first token. The stub closes each Volume tunnel, so both + // GET and PUT below must recover from a replay on their next CONNECT. + run(&storage, remove(url.as_str()), dir.path()) + .await + .unwrap(); + run( + &storage, + instruction("PUT", url.as_str(), &source), + dir.path(), + ) + .await + .unwrap(); + run( + &storage, + instruction("GET", url.as_str(), &destination), + dir.path(), + ) + .await + .unwrap(); + assert_eq!(std::fs::read(&destination).unwrap(), payload); + + // Byte-backed uploads must also recreate their stream on the retry. + let bytes = Bytes::from_static(b"\xff\0stream payload"); + let state = storage.transfer_state(Some( + VolumeOptions::new(vec![dir.path().to_owned()], false).with_input_bytes(bytes.clone()), + )); + state + .complete( + Ok(Some(instruction( + "PUT", + url.as_str(), + Path::new("__input_stream__"), + ))), + true, + ) + .await + .unwrap(); + run( + &storage, + instruction("GET", url.as_str(), &destination), + dir.path(), + ) + .await + .unwrap(); + assert_eq!(std::fs::read(&destination).unwrap(), bytes); + run(&storage, remove(url.as_str()), dir.path()) + .await + .unwrap(); + + let seen = proxy.seen.lock().unwrap(); + assert_eq!(calls.load(Ordering::SeqCst), 6); + assert_eq!(seen.connects.len(), 11); + assert_eq!(seen.connects[0].1, 200); + for (i, pair) in seen.connects[1..].as_chunks::<2>().0.iter().enumerate() { + // Later requests use the promoted client, not the cached first one. + assert_eq!(pair[0].0, seen.connects[2 * i].0); + assert_eq!(pair[0].1, 407); + assert_eq!(pair[1].1, 200); + assert_ne!(pair[0].0, pair[1].0); + } + assert_eq!(seen.requests.len(), 6, "no origin operation is resent"); + assert!(seen.requests[1..5] + .iter() + .all(|(_, headers)| { headers.iter().any(|h| h == "x-test") })); + for i in [1, 3] { + assert!(seen.requests[i].1.iter().any(|h| h == "content-length")); + } + assert_eq!( + seen.volume_bodies, + vec![ + Vec::new(), + payload, + Vec::new(), + bytes.to_vec(), + Vec::new(), + Vec::new() + ] + ); + assert_negotiate_only(&seen); + assert_eq!(direct_hits.load(Ordering::SeqCst), 0); + assert!(storage.negotiate_client.read().unwrap().is_some()); + } + + #[tokio::test] + async fn negotiate_storage_second_407_fails_closed_and_redacts_secrets() { + for operation in ["GET", "PUT", "REMOVE"] { + let proxy = StubProxy::start(true, Duration::ZERO).await; + let (origin, direct_hits) = direct_origin().await; + let url = format!("{origin}?signature=presigned-secret&token=query-secret"); + let calls = Arc::new(AtomicUsize::new(0)); + // A second 407 must stop even when ordinary storage retries remain. + let storage = storage_with_config(negotiate_config(&proxy, &calls), 5, None); + let dir = tempfile::tempdir().unwrap(); + let local = dir.path().join("local"); + if operation == "PUT" { + std::fs::write(&local, b"payload").unwrap(); + } + let batch = if operation == "REMOVE" { + remove(&url) + } else { + instruction(operation, &url, &local) + }; + let error = run(&storage, batch, dir.path()).await.unwrap_err(); + assert_eq!(error.code, ErrorCode::Unauthenticated, "{}", error.message); + assert!(!error.retryable); + assert!(error.message.starts_with( + "Negotiate proxy authentication failed: the proxy rejected a fresh token (HTTP 407): " + ), "{}", error.message); + for secret in [ + "?", + "signature", + "presigned-secret", + "query-secret", + "tok-", + "dG9r", + ] { + assert!(!error.message.contains(secret), "{}", error.message); + } + let seen = proxy.seen.lock().unwrap(); + assert_eq!(seen.connects.len(), 2); + assert_eq!(calls.load(Ordering::SeqCst), 2); + assert!(seen.requests.is_empty()); + assert_negotiate_only(&seen); + assert_eq!(direct_hits.load(Ordering::SeqCst), 0); + assert!(!local.exists() || operation == "PUT"); + } + } + + #[tokio::test(flavor = "current_thread")] + async fn negotiate_storage_slow_first_token_does_not_block_async_workers() { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let calls = Arc::new(AtomicUsize::new(0)); + let signalled = Arc::new(AtomicBool::new(false)); + let (entered_tx, mut entered_rx) = tokio::sync::mpsc::unbounded_channel::<()>(); + let (signal_tx, signal_rx) = std::sync::mpsc::channel::<()>(); + let signal_rx = std::sync::Mutex::new(signal_rx); + let mut config = negotiate_config(&proxy, &calls); + config.proxy.auth = ProxyAuth::NegotiateCallback(NegotiateTokenCallback::new({ + let (calls, signalled) = (calls.clone(), signalled.clone()); + move || { + calls.fetch_add(1, Ordering::SeqCst); + let _ = entered_tx.send(()); + let arrived = signal_rx + .lock() + .unwrap() + .recv_timeout(Duration::from_secs(10)) + .is_ok(); + signalled.store(arrived, Ordering::SeqCst); + Err("no Kerberos credentials".to_string()) + } + })); + let signaller = tokio::spawn(async move { + if entered_rx.recv().await.is_some() { + let _ = signal_tx.send(()); + } + }); + let storage = storage_with_config(config, 5, None); + let dir = tempfile::tempdir().unwrap(); + let error = run(&storage, remove("https://origin.test/volume"), dir.path()) + .await + .unwrap_err(); + signaller.abort(); + assert!( + signalled.load(Ordering::SeqCst), + "the async worker was blocked" + ); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert_eq!(error.code, ErrorCode::Unauthenticated); + assert!(error.message.contains("no Kerberos credentials")); + assert!(proxy.seen.lock().unwrap().connects.is_empty()); + } + + #[tokio::test(flavor = "current_thread")] + async fn negotiate_storage_first_and_fresh_tokens_time_out() { + for slow_call in [1, 2] { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let calls = Arc::new(AtomicUsize::new(0)); + let mut config = negotiate_config(&proxy, &calls); + config.read_timeout = Duration::from_millis(100); + config.proxy.auth = ProxyAuth::NegotiateCallback(NegotiateTokenCallback::new({ + let calls = calls.clone(); + move || { + let n = calls.fetch_add(1, Ordering::SeqCst) + 1; + if n == slow_call { + std::thread::sleep(Duration::from_secs(2)); + } + Ok(format!("tok-{n}").into_bytes()) + } + })); + let storage = storage_with_config(config, 5, None); + let dir = tempfile::tempdir().unwrap(); + if slow_call == 2 { + run(&storage, remove("https://origin.test/volume"), dir.path()) + .await + .unwrap(); + } + let started = Instant::now(); + let error = run(&storage, remove("https://origin.test/volume"), dir.path()) + .await + .unwrap_err(); + assert_eq!(error.code, ErrorCode::Timeout, "{}", error.message); + assert_eq!(error.message, + "Negotiate proxy authentication timed out: no token within the 100ms request timeout"); + assert!( + started.elapsed() < Duration::from_secs(1), + "{:?}", + started.elapsed() + ); + assert_eq!(calls.load(Ordering::SeqCst), slow_call); + assert_eq!( + proxy.seen.lock().unwrap().connects.len(), + if slow_call == 1 { 0 } else { 2 } + ); + } + } + + #[tokio::test] + async fn negotiate_storage_refuses_plain_http_without_io() { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let (origin, direct_hits) = direct_origin().await; + let calls = Arc::new(AtomicUsize::new(0)); + let mut config = negotiate_config(&proxy, &calls); + config.proxy.bypass_hosts = Some("127.0.0.1".to_string()); + let storage = storage_with_config(config, 5, None); + let dir = tempfile::tempdir().unwrap(); + let url = origin.replacen("https://", "http://", 1) + "?signature=secret"; + let error = run(&storage, remove(&url), dir.path()).await.unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidArgument); + assert!(error.message.contains("needs https://")); + assert!(!error.message.contains("signature")); + assert!(proxy.seen.lock().unwrap().connects.is_empty()); + assert_eq!(direct_hits.load(Ordering::SeqCst), 0); + } + #[tokio::test] async fn put_get_and_remove_move_exact_bytes() { let payload = b"\0\xffvolume bytes".to_vec(); From f72ffa81cba8a136d01d440a7b9ae30b5e838d85 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:22:11 +0000 Subject: [PATCH 17/18] fix(proxy): harden Negotiate token creation and add feature CI checks From an independent review of the runtime GSSAPI loader: - The tenant-discovery probe uses one deadline for its token and its request, as send_once does, instead of up to twice the request timeout. - Token-creation timeouts are not retryable: a hung GSSAPI or callback call keeps its blocking thread, so automatic retries would pile them up. - Only Linux loads MIT GSSAPI at run time; other Unix (BSDs, illumos, Android) keep linking the system GSSAPI through cross-krb5, as before. - A NUL byte in the Kerberos service, host or realm is rejected with InvalidArgument instead of silently truncating the principal. - A hermetic test creates a real token from a synthesized credential cache in a child process, with no KDC. - The synchronous client constructors document that they create the first token on the caller's thread with no deadline. - PR checks run clippy and the unit tests with proxy-negotiate on Linux, and clippy with it on Windows. No KDC or fixture is needed. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- .github/workflows/pr-checks.yml | 10 ++ CONNECTION_PARAMETERS.md | 2 +- Cargo.toml | 11 +- NOTICE | 2 +- adbc/NOTICE | 2 +- src/client/gssapi_runtime.rs | 266 ++++++++++++++++++++++++++++- src/client/http.rs | 94 ++++++---- src/client/http_negotiate_tests.rs | 69 ++++++++ src/client/mod.rs | 2 +- src/client/proxy_negotiate.rs | 53 ++++-- src/config.rs | 8 +- src/volume.rs | 4 + 12 files changed, 466 insertions(+), 57 deletions(-) diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml index 2e6848a6..75a3443d 100644 --- a/.github/workflows/pr-checks.yml +++ b/.github/workflows/pr-checks.yml @@ -102,6 +102,9 @@ jobs: - name: cargo clippy run: cargo clippy --all-targets -- -D warnings + - name: cargo clippy (proxy-negotiate) + run: cargo clippy --all-targets --features proxy-negotiate -- -D warnings + test: name: Unit + doc tests runs-on: @@ -131,6 +134,9 @@ jobs: # a live workspace; `rust-e2e.yml` runs them separately. run: cargo test --workspace + - name: cargo test (proxy-negotiate) + run: cargo test --lib --features proxy-negotiate + c-abi: name: C ABI smoke test runs-on: @@ -270,6 +276,10 @@ jobs: shell: pwsh run: cargo clippy -p databricks-sql-kernel --no-default-features --features tls-rustls --all-targets -- -D warnings + - name: cargo clippy (tls-rustls, proxy-negotiate, Windows) + shell: pwsh + run: cargo clippy -p databricks-sql-kernel --no-default-features --features tls-rustls,proxy-negotiate --all-targets -- -D warnings + - name: Test client behavior (tls-rustls, Windows) shell: pwsh # Two runs: the client:: suite, then the C ABI revocation open test, which is not under client::. diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index fd2e5cc8..734e65f8 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -204,7 +204,7 @@ userinfo replaced by `***`. | `username` | Proxy basic-auth (SOCKS5: RFC 1929) username. Overrides credentials embedded in `url`. | `None` | | `password` | Proxy basic-auth password. Ignored unless `username` is set. Redacted in `Debug`. | `None` | | `bypass_hosts` | Comma-separated hosts/domains to bypass the proxy, e.g. `localhost,*.internal.corp,.example.com`. | `None` | -| `auth` | `ProxyAuth::Default` (Basic from `username` or the URL, or none), `ProxyAuth::Negotiate { service, host, realm }` (Kerberos with the ambient credential cache / Windows logon; target `service/host[@realm]`, defaults `HTTP`, the proxy host, the default realm) or `ProxyAuth::NegotiateCallback` (tokens from a caller callback). Negotiate sends `Proxy-Authorization: Negotiate` on the proxy `CONNECT` only, creates a token at session open (and lazily for Volume storage) and retries each request hop once with a fresh token on a proxy 407, including Volume PUT, GET and REMOVE storage requests. A second 407 fails the request; it never falls back to Basic, a direct connection or an env proxy. It requires an `http(s)://` `url` and no Basic credentials (`InvalidArgument`); a failed token fails session open before any network I/O (`Unauthenticated`). On Linux and macOS the token is a raw Kerberos token, which MIT and Heimdal acceptors (such as squid's `negotiate_kerberos_auth`) accept; a proxy that accepts only SPNEGO-wrapped tokens rejects it with 407. Windows sends SPNEGO. `Negotiate` needs the non-default cargo feature `proxy-negotiate`; without it, it is rejected as unsupported. On Linux the feature adds no link dependency: MIT Kerberos (`libgssapi_krb5.so.2`) is loaded only when a token is needed, and if it is missing, `Negotiate` fails session open (`Unauthenticated`) with an install hint. macOS uses GSS.framework (building needs libclang) and Windows uses SSPI. C ABI: `kernel_session_config_set_proxy_negotiate`. Python: `proxy_negotiate_token` (a callable returning `bytes`). | `Default` | +| `auth` | `ProxyAuth::Default` (Basic from `username` or the URL, or none), `ProxyAuth::Negotiate { service, host, realm }` (Kerberos with the ambient credential cache / Windows logon; target `service/host[@realm]`, defaults `HTTP`, the proxy host, the default realm) or `ProxyAuth::NegotiateCallback` (tokens from a caller callback). Negotiate sends `Proxy-Authorization: Negotiate` on the proxy `CONNECT` only, creates a token at session open (and lazily for Volume storage) and retries each request hop once with a fresh token on a proxy 407, including Volume PUT, GET and REMOVE storage requests. A second 407 fails the request; it never falls back to Basic, a direct connection or an env proxy. It requires an `http(s)://` `url` and no Basic credentials (`InvalidArgument`); a failed token fails session open before any network I/O (`Unauthenticated`). On Unix the token is a raw Kerberos token, which MIT and Heimdal acceptors (such as squid's `negotiate_kerberos_auth`) accept; a proxy that accepts only SPNEGO-wrapped tokens rejects it with 407. Windows sends SPNEGO. `Negotiate` needs the non-default cargo feature `proxy-negotiate`; without it, it is rejected as unsupported. On Linux the feature adds no link dependency: MIT Kerberos (`libgssapi_krb5.so.2`) is loaded only when a token is needed, and if it is missing, `Negotiate` fails session open (`Unauthenticated`) with an install hint. Non-Linux platforms link through cross-krb5: GSS.framework on macOS (building needs libclang), SSPI on Windows, and system GSSAPI on other Unix (including BSDs, illumos and Android). C ABI: `kernel_session_config_set_proxy_negotiate`. Python: `proxy_negotiate_token` (a callable returning `bytes`). | `Default` | ## `TlsConfig` — TLS / SSL (optional) diff --git a/Cargo.toml b/Cargo.toml index 21635eea..4796e89b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -173,12 +173,13 @@ jsonwebtoken = { version = "9", default-features = false, features = ["use_pem"] pkcs8 = { version = "0.10", features = ["encryption", "pem", "std"] } # PKCS#8 PEM parsing + PBES2 passphrase decryption # Kerberos/SPNEGO (`Proxy-Authorization: Negotiate`) proxy auth, behind the -# non-default `proxy-negotiate` feature, on macOS (GSS.framework; building -# needs libclang) and Windows (SSPI), whose libraries ship with the OS. Linux -# and other Unix load MIT GSSAPI (`libgssapi_krb5.so.2`) at run time instead -# (`src/client/gssapi_runtime.rs`), so they link no GSSAPI library and need +# non-default `proxy-negotiate` feature. Non-Linux platforms use cross-krb5: +# GSS.framework on macOS (building needs libclang), SSPI on Windows, and +# system GSSAPI on other Unix, including BSDs, illumos and Android. Only Linux +# loads MIT GSSAPI (`libgssapi_krb5.so.2`) at run time instead +# (`src/client/gssapi_runtime.rs`), so Linux links no GSSAPI library and needs # no GSSAPI headers to build. MIT. -[target.'cfg(any(windows, target_vendor = "apple"))'.dependencies] +[target.'cfg(not(target_os = "linux"))'.dependencies] cross-krb5 = { version = "0.5", optional = true, default-features = false } # Windows CryptoAPI for TLS certificate revocation (`src/client/tls_revocation.rs`). diff --git a/NOTICE b/NOTICE index a246c047..97455f89 100644 --- a/NOTICE +++ b/NOTICE @@ -37,7 +37,7 @@ Project URL: https://github.com/chronotope/chrono-tz Copyright: Copyright (c) 2016-2024 Benjamin Sago & the chronotope maintainers -Package: cross-krb5 (optional, `proxy-negotiate` feature on macOS and Windows; links GSS.framework or SSPI. Linux loads MIT `libgssapi_krb5.so.2` at run time instead) +Package: cross-krb5 (optional, `proxy-negotiate` feature on non-Linux platforms; links GSS.framework on macOS, SSPI on Windows, or system GSSAPI on other Unix. Linux loads MIT `libgssapi_krb5.so.2` at run time instead) Project URL: https://github.com/estokes/cross-krb5 Copyright: Copyright cross-krb5 Authors. diff --git a/adbc/NOTICE b/adbc/NOTICE index a246c047..97455f89 100644 --- a/adbc/NOTICE +++ b/adbc/NOTICE @@ -37,7 +37,7 @@ Project URL: https://github.com/chronotope/chrono-tz Copyright: Copyright (c) 2016-2024 Benjamin Sago & the chronotope maintainers -Package: cross-krb5 (optional, `proxy-negotiate` feature on macOS and Windows; links GSS.framework or SSPI. Linux loads MIT `libgssapi_krb5.so.2` at run time instead) +Package: cross-krb5 (optional, `proxy-negotiate` feature on non-Linux platforms; links GSS.framework on macOS, SSPI on Windows, or system GSSAPI on other Unix. Linux loads MIT `libgssapi_krb5.so.2` at run time instead) Project URL: https://github.com/estokes/cross-krb5 Copyright: Copyright cross-krb5 Authors. diff --git a/src/client/gssapi_runtime.rs b/src/client/gssapi_runtime.rs index 1e0deccf..14b74ed9 100644 --- a/src/client/gssapi_runtime.rs +++ b/src/client/gssapi_runtime.rs @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! MIT Kerberos GSSAPI loaded at run time (Linux and other non-Apple Unix). +//! MIT Kerberos GSSAPI loaded at run time on Linux only. //! //! `libgssapi_krb5.so.2` is opened with `dlopen` the first time a Negotiate //! token is needed, never at load time. A binary built with the @@ -25,8 +25,9 @@ //! name and canonicalized, and the first `gss_init_sec_context` token (raw //! krb5, with integrity, mutual authentication and confidentiality //! requested). Errors read like libgssapi's: the major status text, then the -//! minor status in parentheses. macOS (GSS.framework) and Windows (SSPI) ship -//! their libraries with the OS and keep linking them through `cross-krb5`. +//! minor status in parentheses. Non-Linux platforms keep linking through +//! `cross-krb5`: GSS.framework on macOS, SSPI on Windows, and system GSSAPI on +//! other Unix (including BSDs, illumos and Android). use std::ffi::{c_int, c_void, CStr}; use std::ptr; @@ -499,6 +500,265 @@ mod tests { assert!(!err.contains("unknown GSSAPI status code"), "{err}"); } + const TEST_REALM: &str = "KERNEL-TEST.INVALID"; + const CACHE_TEST_CHILD: &str = "DATABRICKS_KERNEL_GSSAPI_CACHE_TEST_CHILD"; + + /// DER with lengths sufficient for these small, synthetic tickets. + fn der(tag: u8, bytes: &[u8]) -> Vec { + let mut result = vec![tag]; + if bytes.len() < 128 { + result.push(bytes.len() as u8); + } else if bytes.len() < 256 { + result.extend([0x81, bytes.len() as u8]); + } else { + let length = u16::try_from(bytes.len()).expect("small test ticket"); + result.push(0x82); + result.extend(length.to_be_bytes()); + } + result.extend(bytes); + result + } + + fn der_integer(value: u8) -> Vec { + der(0x02, &[value]) + } + + fn fake_ticket(components: &[&[u8]]) -> Vec { + let names = components + .iter() + .flat_map(|name| der(0x1b, name)) + .collect::>(); + let principal = der( + 0x30, + &[der(0xa0, &der_integer(2)), der(0xa1, &der(0x30, &names))].concat(), + ); + // AES256 ciphertext is deliberately fake: an initiator copies the + // ticket into its AP-REQ without decrypting it. No real credentials. + let encrypted = der( + 0x30, + &[ + der(0xa0, &der_integer(18)), + der(0xa1, &der_integer(1)), + der(0xa2, &der(0x04, &[0x55; 96])), + ] + .concat(), + ); + der( + 0x61, + &der( + 0x30, + &[ + der(0xa0, &der_integer(5)), + der(0xa1, &der(0x1b, TEST_REALM.as_bytes())), + der(0xa2, &principal), + der(0xa3, &encrypted), + ] + .concat(), + ), + ) + } + + fn counted(bytes: &[u8]) -> Vec { + let mut result = u32::try_from(bytes.len()).unwrap().to_be_bytes().to_vec(); + result.extend(bytes); + result + } + + fn cache_principal(kind: u32, components: &[&[u8]]) -> Vec { + let mut result = kind.to_be_bytes().to_vec(); + result.extend(u32::try_from(components.len()).unwrap().to_be_bytes()); + result.extend(counted(TEST_REALM.as_bytes())); + for name in components { + result.extend(counted(name)); + } + result + } + + fn cached_credential(now: u32, server_kind: u32, server: &[&[u8]]) -> Vec { + let mut result = cache_principal(1, &[b"kernel-test"]); + result.extend(cache_principal(server_kind, server)); + result.extend(18_u16.to_be_bytes()); // AES256 session key type. + result.extend(counted(&[0x42; 32])); // Synthetic session key. + for time in [now - 60, now - 60, now + 36_000, 0] { + result.extend(time.to_be_bytes()); + } + result.push(0); // Not an SKEY ticket. + result.extend(0x40e1_0000_u32.to_be_bytes()); // Ticket flags. + result.extend(0_u32.to_be_bytes()); // No addresses. + result.extend(0_u32.to_be_bytes()); // No authdata. + result.extend(counted(&fake_ticket(server))); + result.extend(counted(&[])); // No second ticket. + result + } + + /// FILE v4 cache: a default client, a fake TGT and a cached HTTP ticket. + /// MIT can create an AP-REQ locally; the fake ticket needs no KDC or keytab. + fn write_test_cache(path: &std::path::Path) { + let now = u32::try_from( + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs(), + ) + .unwrap(); + let mut cache = Vec::new(); + cache.extend(0x0504_u16.to_be_bytes()); + cache.extend(12_u16.to_be_bytes()); // Header length. + cache.extend(1_u16.to_be_bytes()); // Time-offset header tag. + cache.extend(8_u16.to_be_bytes()); + cache.extend([0; 8]); // No clock offset. + cache.extend(cache_principal(1, &[b"kernel-test"])); + cache.extend(cached_credential( + now, + 2, + &[b"krbtgt", TEST_REALM.as_bytes()], + )); + cache.extend(cached_credential(now, 1, &[b"HTTP", b"proxy.test"])); + std::fs::write(path, cache).unwrap(); + } + + fn assert_ap_req(token: &[u8]) { + // RFC 2743 InitialContextToken: 0x60, DER length, krb5 OID, + // RFC 4121 TOK_ID 01 00, then the AP-REQ application tag (0x6e). + assert!(token.len() > 2, "missing GSSAPI token framing"); + assert!(token[0] == 0x60, "expected InitialContextToken"); + let (length, offset) = if token[1] < 128 { + (usize::from(token[1]), 2) + } else { + let count = usize::from(token[1] & 0x7f); + assert!(count > 0 && count <= std::mem::size_of::()); + let end = 2 + count; + assert!(token.len() >= end, "truncated DER length"); + let length = token[2..end] + .iter() + .fold(0_usize, |n, byte| (n << 8) | usize::from(*byte)); + (length, end) + }; + assert!( + token.len() - offset == length, + "incorrect GSSAPI token length" + ); + let prefix = [&[0x06, 0x09], KRB5_MECH, &[0x01, 0x00, 0x6e]].concat(); + assert!( + token[offset..].starts_with(&prefix), + "expected krb5 OID and AP-REQ TOK_ID" + ); + } + + fn check_cached_token_and_header() { + use crate::client::proxy_negotiate::NegotiateSource; + use crate::config::ProxyAuth; + use crate::kernel_error::ErrorCode; + use base64::Engine; + + let token = initial_token(&format!("HTTP/proxy.test@{TEST_REALM}")) + .expect("the cached service ticket must create a token without a KDC"); + assert_ap_req(&token); + let auth = ProxyAuth::Negotiate { + service: None, + host: None, + realm: Some(TEST_REALM.to_string()), + }; + let source = NegotiateSource::resolve(Some("http://proxy.test:3128"), None, None, &auth) + .unwrap() + .unwrap(); + let header = source + .header() + .expect("the cached service ticket must create a header"); + assert!(header.is_sensitive(), "Negotiate header must be sensitive"); + assert!( + format!("{header:?}") == "Sensitive", + "header Debug must hide the token" + ); + let encoded = header + .to_str() + .unwrap() + .strip_prefix("Negotiate ") + .expect("the header must use the Negotiate scheme"); + let header_token = base64::engine::general_purpose::STANDARD + .decode(encoded) + .unwrap(); + assert_ap_req(&header_token); + + // A missing service ticket fails against the unreachable local KDC. + // Check both the native error and the public wrapper, without ever + // printing tokens (even a failing assertion must not dump their bytes). + let missing_target = format!("HTTP/missing.test@{TEST_REALM}"); + let native_error = match initial_token(&missing_target) { + Ok(_) => panic!("a service ticket absent from the cache must fail"), + Err(error) => error, + }; + let error = NegotiateSource::Kerberos { + target: missing_target, + } + .header() + .unwrap_err(); + assert_eq!(error.code, ErrorCode::Unauthenticated); + assert!(!error.retryable); + for message in [ + native_error, + error.message.clone(), + error.to_string(), + format!("{error:?}"), + ] { + for token in [&token, &header_token] { + let encoded = base64::engine::general_purpose::STANDARD.encode(token); + assert!( + !message.contains(&encoded), + "base64 token leaked in an error" + ); + assert!( + !message.contains(String::from_utf8_lossy(token).as_ref()), + "raw token leaked in an error" + ); + } + } + } + + #[test] + fn cached_service_ticket_creates_sensitive_negotiate_header() { + if let Err(error) = library() { + eprintln!("skipped: {error}"); + return; + } + if std::env::var_os(CACHE_TEST_CHILD).is_some() { + check_cached_token_and_header(); + return; + } + let dir = tempfile::tempdir().unwrap(); + let cache = dir.path().join("ccache"); + let config = dir.path().join("krb5.conf"); + write_test_cache(&cache); + std::fs::write( + &config, + format!( + "[libdefaults]\n default_realm = {TEST_REALM}\n dns_lookup_kdc = false\n \ + dns_lookup_realm = false\n rdns = false\n dns_canonicalize_hostname = false\n \ + udp_preference_limit = 1\n[realms]\n {TEST_REALM} = {{\n kdc = 127.0.0.1:1\n }}\n" + ), + ) + .unwrap(); + // Only the child sees these environment settings. Other tests in the + // parent may create GSSAPI contexts concurrently using their own env. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "client::gssapi_runtime::tests::cached_service_ticket_creates_sensitive_negotiate_header", "--nocapture", "--test-threads=1"]) + .env(CACHE_TEST_CHILD, "1") + .env("KRB5CCNAME", format!("FILE:{}", cache.display())) + .env("KRB5_CONFIG", &config) + .output() + .expect("run the GSSAPI cache test in a child process"); + assert!( + output.status.success(), + "child GSSAPI test failed:\n{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + assert!( + String::from_utf8_lossy(&output.stdout).contains("test result: ok. 1 passed;"), + "the child must run exactly one test, not silently match an empty filter" + ); + } + #[test] fn oids_match_rfc_1964() { // 1.2.840.113554.1.2.2 and 1.2.840.113554.1.2.2.1, DER-encoded. diff --git a/src/client/http.rs b/src/client/http.rs index 9ede05ab..045e3a5d 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -607,6 +607,10 @@ impl DatabricksHttpClient { /// Auth provider must be set separately via `set_auth_provider()` before /// calling `execute()`. Use `execute_without_auth()` for requests that /// don't need authentication (e.g., OAuth token endpoint calls). + /// + /// With Negotiate, this creates the first token on the caller's thread + /// with no deadline. Async callers should use [`Session::open`](crate::Session::open), + /// which creates it off the async workers within the request timeout. pub fn new( config: HttpClientConfig, retry_configs: HashMap, @@ -617,6 +621,10 @@ impl DatabricksHttpClient { /// Like [`Self::new`], with a revocation policy applied to every connection this client /// makes. The policy is kept outside [`TlsConfig`], so that struct keeps its published /// shape. + /// + /// With Negotiate, this creates the first token on the caller's thread + /// with no deadline. Async callers should use [`Session::open`](crate::Session::open), + /// which bounds token creation by the request timeout. pub(crate) fn with_revocation( mut config: HttpClientConfig, retry_configs: HashMap, @@ -769,10 +777,12 @@ impl DatabricksHttpClient { Ok(joined) => joined.map_err(|e| { Error::internal().message(format!("Negotiate token task failed: {e}")) })?, - Err(_) => Err(Error::timeout().message(format!( - "Negotiate proxy authentication timed out: no token within the {budget:?} \ - request timeout" - ))), + Err(_) => Err(Error::timeout() + .message(format!( + "Negotiate proxy authentication timed out: no token within the {budget:?} \ + request timeout" + )) + .with_retryable(false)), } } @@ -1037,6 +1047,10 @@ impl DatabricksHttpClient { /// /// Convenience method for tests and simple use cases where custom retry /// configuration is not needed. + /// + /// With Negotiate, this creates the first token on the caller's thread + /// with no deadline. Async callers should use [`Session::open`](crate::Session::open), + /// which bounds token creation by the request timeout. pub fn with_default_retry(config: HttpClientConfig) -> Result { use crate::client::retry::build_retry_configs; let retry_configs = @@ -1086,10 +1100,12 @@ impl DatabricksHttpClient { Ok(joined) => joined.map_err(|e| { Error::internal().message(format!("Negotiate token task failed: {e}")) })?, - Err(_) => Err(Error::timeout().message(format!( - "Negotiate proxy authentication timed out: no token within the {budget:?} \ - request timeout" - ))), + Err(_) => Err(Error::timeout() + .message(format!( + "Negotiate proxy authentication timed out: no token within the {budget:?} \ + request timeout" + )) + .with_retryable(false)), } } @@ -1254,10 +1270,12 @@ impl DatabricksHttpClient { client = tokio::time::timeout(remaining(), self.rebuild_negotiate_client()) .await .map_err(|_| { - Error::timeout().message(format!( - "Negotiate proxy authentication timed out: no fresh token \ - within the {budget:?} request timeout" - )) + Error::timeout() + .message(format!( + "Negotiate proxy authentication timed out: no fresh token \ + within the {budget:?} request timeout" + )) + .with_retryable(false) })??; (rebuilt, fresh_token) = (true, true); } @@ -1351,8 +1369,14 @@ impl DatabricksHttpClient { /// discovery is fatal to `Session::open` for a zero-config-tenant /// `azure-sp-m2m` caller; the recourse is to re-run with an explicit /// `azure_tenant_id` (which skips discovery entirely). A single hop is - /// sufficient for discovery, so no retry is attempted here. + /// sufficient for discovery, so no retry is attempted here. One request + /// timeout covers both token creation and the GET. pub async fn first_redirect_location(&self, url: &str) -> Result> { + let budget = self.config.read_timeout; + let now = tokio::time::Instant::now(); + let deadline = now + .checked_add(budget) + .unwrap_or_else(|| now + Duration::from_secs(100 * 365 * 24 * 3600)); let redirect = reqwest::redirect::Policy::none(); let client = if matches!(self.config.proxy.auth, crate::config::ProxyAuth::Default) { Self::build_reqwest_client( @@ -1371,30 +1395,38 @@ impl DatabricksHttpClient { plain-HTTP tenant-discovery probe", )); } - let budget = self.config.read_timeout; - tokio::time::timeout(budget, self.build_negotiate_client(redirect)) + tokio::time::timeout_at(deadline, self.build_negotiate_client(redirect)) .await .map_err(|_| { - Error::timeout().message(format!( - "Negotiate proxy authentication timed out: no token within the \ - {budget:?} request timeout" - )) + Error::timeout() + .message(format!( + "Negotiate proxy authentication timed out: no token within the \ + {budget:?} request timeout" + )) + .with_retryable(false) })?? }; let negotiate = !matches!(self.config.proxy.auth, crate::config::ProxyAuth::Default); - let response = client.get(url).send().await.map_err(|e| { - // The probe's client carries a fresh token, so a 407 fails closed - // as `send_once` does after its retry. - if negotiate && is_proxy_auth_required(&e) { - Error::unauthenticated().message(format!( - "Negotiate proxy authentication failed: the proxy rejected a fresh token \ + // Token creation and the probe share one budget, just as send_once's + // token rebuild and request hops do. + let response = client + .get(url) + .timeout(deadline.saturating_duration_since(tokio::time::Instant::now())) + .send() + .await + .map_err(|e| { + // The probe's client carries a fresh token, so a 407 fails closed + // as `send_once` does after its retry. + if negotiate && is_proxy_auth_required(&e) { + Error::unauthenticated().message(format!( + "Negotiate proxy authentication failed: the proxy rejected a fresh token \ (HTTP 407) on the tenant-discovery probe to {url}" - )) - } else { - Error::network_error() - .message(format!("Redirect-probe request to {url} failed: {e}")) - } - })?; + )) + } else { + Error::network_error() + .message(format!("Redirect-probe request to {url} failed: {e}")) + } + })?; Ok(response .headers() .get(reqwest::header::LOCATION) diff --git a/src/client/http_negotiate_tests.rs b/src/client/http_negotiate_tests.rs index 1c1ef975..5628a27a 100644 --- a/src/client/http_negotiate_tests.rs +++ b/src/client/http_negotiate_tests.rs @@ -477,6 +477,10 @@ async fn negotiate_first_token_times_out() { Err(e) => e, }; assert_eq!(err.code, ErrorCode::Timeout, "{}", err.message); + assert!( + !err.retryable, + "token timeouts must not start more blocking calls" + ); assert!(err.message.contains("no token within"), "{}", err.message); assert!( started.elapsed() < Duration::from_secs(1), @@ -517,6 +521,10 @@ async fn negotiate_session_open_reports_a_token_timeout() { .map(|_| ()) .unwrap_err(); assert_eq!(err.code, ErrorCode::Timeout, "{}", err.message); + assert!( + !err.retryable, + "token timeouts must not start more blocking calls" + ); assert!(err.message.contains("no token within"), "{}", err.message); assert!( started.elapsed() < Duration::from_secs(1), @@ -525,6 +533,61 @@ async fn negotiate_session_open_reports_a_token_timeout() { ); } +/// The probe shares its timeout between a new token and the GET rather than +/// letting each spend a full request timeout. +#[tokio::test] +async fn negotiate_probe_deadline_spans_token_and_request() { + let proxy = StubProxy::start(false, Duration::from_millis(1500)).await; + let calls = Arc::new(AtomicUsize::new(0)); + let mut client = slow_token_client(&proxy, &calls, false, Duration::from_secs(1)).unwrap(); + let budget = Duration::from_secs(2); + client.config.read_timeout = budget; + let started = tokio::time::Instant::now(); + let err = client + .first_redirect_location("https://origin.test/aad/auth") + .await + .expect_err("the token and origin delays together exceed the request timeout"); + assert_eq!(err.code, ErrorCode::NetworkError, "{}", err.message); + assert!( + err.message + .starts_with("Redirect-probe request to https://origin.test/aad/auth failed:"), + "{}", + err.message + ); + assert!(started.elapsed() < budget + Duration::from_millis(1500)); + assert_eq!(calls.load(Ordering::SeqCst), 2); + let seen = proxy.seen.lock().unwrap(); + assert_eq!(seen.connects.len(), 1); + assert_eq!( + seen.requests.len(), + 1, + "the token was ready before the deadline" + ); + assert_negotiate_only(&seen); +} + +#[tokio::test] +async fn negotiate_probe_token_timeout_is_not_retryable() { + let proxy = StubProxy::start(false, Duration::ZERO).await; + let calls = Arc::new(AtomicUsize::new(0)); + let mut client = slow_token_client(&proxy, &calls, false, Duration::from_secs(2)).unwrap(); + client.config.read_timeout = Duration::from_millis(100); + let started = tokio::time::Instant::now(); + let err = client + .first_redirect_location("https://origin.test/aad/auth") + .await + .unwrap_err(); + assert_eq!(err.code, ErrorCode::Timeout); + assert!(!err.retryable); + assert_eq!( + err.message, + "Negotiate proxy authentication timed out: no token within the 100ms request timeout" + ); + assert!(started.elapsed() < Duration::from_secs(1)); + assert_eq!(calls.load(Ordering::SeqCst), 2); + assert!(proxy.seen.lock().unwrap().connects.is_empty()); +} + /// An extreme request timeout (`Duration::MAX`) does not overflow the /// Negotiate deadline: the request still goes through. #[tokio::test] @@ -550,6 +613,11 @@ async fn negotiate_extreme_timeout_does_not_overflow() { get(&client, "https://origin.test/probe").await.unwrap(), 200 ); + assert!(client + .first_redirect_location("https://origin.test/aad/auth") + .await + .unwrap() + .is_none()); } #[tokio::test] @@ -824,6 +892,7 @@ async fn negotiate_deadline_spans_redirects_token_and_body() { } Err(e) => { assert_eq!(e.code, ErrorCode::Timeout, "{name}: {}", e.message); + assert!(!e.retryable, "{name}: token timeouts must not be retried"); assert!(e.message.contains("fresh token"), "{name}: {}", e.message); Err("token timed out".to_string()) } diff --git a/src/client/mod.rs b/src/client/mod.rs index 5ec13a22..4c366362 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -31,7 +31,7 @@ //! [`transport`]: self::transport //! [`sea`]: self::sea -#[cfg(all(feature = "proxy-negotiate", unix, not(target_vendor = "apple")))] +#[cfg(all(feature = "proxy-negotiate", target_os = "linux"))] mod gssapi_runtime; pub mod http; pub(crate) mod proxy_negotiate; diff --git a/src/client/proxy_negotiate.rs b/src/client/proxy_negotiate.rs index c655fb40..638835bf 100644 --- a/src/client/proxy_negotiate.rs +++ b/src/client/proxy_negotiate.rs @@ -87,7 +87,7 @@ impl NegotiateSource { }; // IPv6 literals keep their URL brackets in `host_str`. let proxy_host = proxy_host.trim_start_matches('[').trim_end_matches(']'); - let target = target_name(service, host, realm, proxy_host); + let target = target_name(service, host, realm, proxy_host)?; #[cfg(feature = "proxy-negotiate")] { Ok(Some(NegotiateSource::Kerberos { target })) @@ -134,7 +134,14 @@ fn target_name( host: &Option, realm: &Option, proxy_host: &str, -) -> String { +) -> Result { + for (field, value) in [("service", service), ("host", host), ("realm", realm)] { + if value.as_deref().is_some_and(|v| v.contains('\0')) { + return Err(Error::invalid_argument().message(format!( + "Negotiate proxy authentication {field} must not contain NUL bytes" + ))); + } + } let pick = |v: &Option| { v.as_deref() .map(str::trim) @@ -150,7 +157,7 @@ fn target_name( target.push('@'); target.push_str(&realm); } - target + Ok(target) } #[cfg(feature = "proxy-negotiate")] @@ -162,18 +169,23 @@ fn kerberos_token(target: &str) -> Result> { }) } -/// Linux and other non-Apple Unix: MIT GSSAPI, loaded at run time only when -/// a token is needed, so the binary does not depend on it. A raw Kerberos -/// token, accepted under `Negotiate` by MIT and Heimdal acceptors. -#[cfg(all(feature = "proxy-negotiate", unix, not(target_vendor = "apple")))] +/// Linux: MIT GSSAPI, loaded at run time only when a token is needed, so the +/// binary does not depend on it. A raw Kerberos token, accepted under +/// `Negotiate` by MIT and Heimdal acceptors. +#[cfg(all(feature = "proxy-negotiate", target_os = "linux"))] fn platform_token(target: &str) -> std::result::Result, String> { super::gssapi_runtime::initial_token(target) } -/// macOS (GSS.framework, a raw Kerberos token) and Windows (the SSPI -/// Negotiate package), linked through cross-krb5; both ship with the OS. +/// Non-Linux platforms, linked through cross-krb5: macOS (GSS.framework), +/// Windows (the SSPI Negotiate package), and system GSSAPI on other Unix +/// (including BSDs, illumos and Android). Unix sends a raw Kerberos token. /// Ambient credentials (`None` principal); no delegation. -#[cfg(all(feature = "proxy-negotiate", any(windows, target_vendor = "apple")))] +#[cfg(all( + feature = "proxy-negotiate", + not(target_os = "linux"), + any(unix, windows) +))] fn platform_token(target: &str) -> std::result::Result, String> { #[cfg(windows)] let flags = cross_krb5::InitiateFlags::NEGOTIATE_TOKEN; @@ -393,11 +405,30 @@ mod tests { &to_owned(host), &to_owned(realm), "proxy.corp", - ); + ) + .unwrap(); assert_eq!(target, expected); } } + #[test] + fn nul_in_kerberos_target_components_is_invalid_before_io() { + for (field, auth) in [ + ("service", kerberos(Some("HTTP\0suffix"), None, None)), + ("host", kerberos(None, Some("proxy.test\0suffix"), None)), + ("realm", kerberos(None, None, Some("REALM\0suffix"))), + ] { + let error = NegotiateSource::resolve(Some("http://proxy.test:3128"), None, None, &auth) + .unwrap_err(); + assert_eq!(error.code, ErrorCode::InvalidArgument); + assert!(!error.retryable); + assert_eq!( + error.message, + format!("Negotiate proxy authentication {field} must not contain NUL bytes") + ); + } + } + #[cfg(not(feature = "proxy-negotiate"))] #[test] fn kerberos_without_feature_is_unsupported() { diff --git a/src/config.rs b/src/config.rs index fdfdf0cb..6c31009f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1128,11 +1128,13 @@ pub enum ProxyAuth { #[default] Default, /// Kerberos via MIT GSSAPI on Linux (`libgssapi_krb5.so.2`, loaded only - /// when a token is needed), GSS.framework on macOS or SSPI on Windows, - /// using the caller's ambient credentials (credential cache or logon + /// when a token is needed). Non-Linux platforms link through cross-krb5: + /// GSS.framework on macOS, SSPI on Windows, and system GSSAPI on other + /// Unix (including BSDs, illumos and Android). Uses the caller's ambient + /// credentials (credential cache or logon /// session). No password, keytab or delegation. The target is /// `/[@]`, by default `HTTP/` in the - /// default realm. On Linux and macOS the token is a raw Kerberos token, + /// default realm. On Unix the token is a raw Kerberos token, /// which MIT and Heimdal acceptors (such as squid's /// `negotiate_kerberos_auth`) accept under `Negotiate`; a proxy that /// accepts only SPNEGO-wrapped tokens rejects it with 407. Windows sends diff --git a/src/volume.rs b/src/volume.rs index 04af6f87..5b359609 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -1428,6 +1428,10 @@ mod tests { .await .unwrap_err(); assert_eq!(error.code, ErrorCode::Timeout, "{}", error.message); + assert!( + !error.retryable, + "token timeouts must not start more blocking calls" + ); assert_eq!(error.message, "Negotiate proxy authentication timed out: no token within the 100ms request timeout"); assert!( From 39e39fb2c60bfc434c4f830dac4ab71786374cb6 Mon Sep 17 00:00:00 2001 From: cat23123 <58714163+cat23123@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:43:12 +0000 Subject: [PATCH 18/18] test(proxy): give the Volume token-timeout test headroom on slow runners negotiate_storage_first_and_fresh_tokens_time_out ran a normal transfer, whose fast first token had to fit a 100 ms budget that also covers building the storage client and scheduling the blocking call. A loaded CI runner went over it. The budget is now 1 s and the slow token takes 3 s, so the fast path has headroom and the slow one still clearly times out. Signed-off-by: cat23123 <58714163+cat23123@users.noreply.github.com> Co-authored-by: Isaac --- src/volume.rs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/volume.rs b/src/volume.rs index 5b359609..61897296 100644 --- a/src/volume.rs +++ b/src/volume.rs @@ -1405,13 +1405,16 @@ mod tests { let proxy = StubProxy::start(false, Duration::ZERO).await; let calls = Arc::new(AtomicUsize::new(0)); let mut config = negotiate_config(&proxy, &calls); - config.read_timeout = Duration::from_millis(100); + // The budget also covers building the storage client and scheduling the + // blocking call, so the fast token (and its client build) needs headroom on a + // loaded CI runner; the slow token still outlasts it by a wide margin. + config.read_timeout = Duration::from_secs(1); config.proxy.auth = ProxyAuth::NegotiateCallback(NegotiateTokenCallback::new({ let calls = calls.clone(); move || { let n = calls.fetch_add(1, Ordering::SeqCst) + 1; if n == slow_call { - std::thread::sleep(Duration::from_secs(2)); + std::thread::sleep(Duration::from_secs(3)); } Ok(format!("tok-{n}").into_bytes()) } @@ -1432,10 +1435,12 @@ mod tests { !error.retryable, "token timeouts must not start more blocking calls" ); - assert_eq!(error.message, - "Negotiate proxy authentication timed out: no token within the 100ms request timeout"); + assert_eq!( + error.message, + "Negotiate proxy authentication timed out: no token within the 1s request timeout" + ); assert!( - started.elapsed() < Duration::from_secs(1), + started.elapsed() < Duration::from_millis(2500), "{:?}", started.elapsed() );