Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 23 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,17 @@ thiserror = "2"
# Strip defaults and re-enable just the `reqwest` integration here; the
# kernel's own `tls-native` / `tls-rustls` feature controls the TLS
# backend for reqwest, and oauth2 inherits whichever the consumer picks.
oauth2 = { version = "5", default-features = false, features = ["reqwest"] } # OAuth 2.0 protocol operations (PKCE, token exchange, client credentials)
sha2 = "0.10" # SHA-256 for token cache key generation
open = "5" # Browser launch for interactive OAuth flows
dirs = "5" # Cross-platform config directory (~/.config/)
# OAuth surface is gated behind the `oauth` Cargo feature (default on, so
# existing consumers — pyo3, napi, kernel CI — see no behavior change). The
# `databricks-sql-kernel` perf benchmark in `databricks-eng/universe` opts
# out via `--no-default-features --features tls-native`, because it only
# authenticates with PAT and shipping ~12k lines of unused `oauth2` / `open`
# / `dirs` / `sha2` source through universe's Rust-crate vendoring is wasted
# review surface.
oauth2 = { version = "5", default-features = false, features = ["reqwest"], optional = true } # OAuth 2.0 protocol operations (PKCE, token exchange, client credentials)
sha2 = { version = "0.10", optional = true } # SHA-256 for token cache key generation
open = { version = "5", optional = true } # Browser launch for interactive OAuth flows
dirs = { version = "5", optional = true } # Cross-platform config directory (~/.config/)

[dev-dependencies]
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
Expand Down Expand Up @@ -127,9 +134,20 @@ tempfile = "3"
# but that separation is no longer load-bearing for the TLS feature
# guarantee — items 1 and 2 above are.
[features]
default = ["tls-native"]
# Default keeps `oauth` enabled so existing consumers (pyo3, napi, kernel CI,
# any direct-Rust caller using `AuthConfig::OAuthM2M` / `OAuthU2M`) build
# identically to before this feature gate was added. The `oauth`-off build
# is exercised by the universe-side perf benchmark and is also a useful
# build-time sanity check for any future consumer that only uses PAT.
default = ["tls-native", "oauth"]
tls-native = ["reqwest/native-tls"]
tls-rustls = ["reqwest/rustls-tls"]
# Pulls in oauth2 + the helper crates used only by OAuth flows (token cache
# hashing, config-dir resolution, browser launch). `auth/oauth/*` modules and
# the `OAuthM2M` / `OAuthU2M` / `OAuthFederation` variants of `AuthConfig`
# are `#[cfg(feature = "oauth")]`-gated; turning the feature off leaves
# `AuthConfig::Pat` and a clean `build_auth_provider` with one match arm.
oauth = ["dep:oauth2", "dep:sha2", "dep:open", "dep:dirs"]

[lib]
name = "databricks_sql_kernel"
Expand Down
1 change: 1 addition & 0 deletions deny.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ allow = [
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause",
"CC0-1.0",
"CDLA-Permissive-2.0",
"ISC",
"MIT",
Expand Down
2 changes: 2 additions & 0 deletions src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,12 @@
//! Authentication mechanisms for the Databricks ADBC driver.

pub mod config;
#[cfg(feature = "oauth")]
pub mod oauth;
pub mod pat;

pub use config::{AuthConfig, AuthType};
#[cfg(feature = "oauth")]
pub use oauth::{AuthorizationCodeProvider, ClientCredentialsProvider};
pub use pat::PersonalAccessToken;

Expand Down
20 changes: 12 additions & 8 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@ pub enum AuthConfig {

/// OAuth 2.0 machine-to-machine (client credentials grant).
/// Used for service-principal authentication.
#[cfg(feature = "oauth")]
OAuthM2M {
client_id: String,
client_secret: String,
Expand All @@ -215,6 +216,7 @@ pub enum AuthConfig {
/// `redirect_port`, opens the user's browser to the workspace's
/// authorize endpoint, and exchanges the returned code for a
/// token.
#[cfg(feature = "oauth")]
OAuthU2M {
/// OAuth client ID. `None` → `"databricks-cli"` (the public
/// CLI client registered on every workspace).
Expand Down Expand Up @@ -243,6 +245,7 @@ pub enum AuthConfig {
/// [`Session::open`](crate::Session::open) with this variant
/// returns `ErrorCode::InvalidArgument` until the implementation
/// lands.
#[cfg(feature = "oauth")]
OAuthFederation {
subject_token: String,
subject_token_type: String,
Expand Down Expand Up @@ -277,6 +280,7 @@ impl std::fmt::Debug for AuthConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Pat { .. } => f.write_str("Pat { token: <redacted> }"),
#[cfg(feature = "oauth")]
Self::OAuthM2M {
client_id, scopes, ..
} => f
Expand All @@ -285,6 +289,7 @@ impl std::fmt::Debug for AuthConfig {
.field("client_secret", &"<redacted>")
.field("scopes", scopes)
.finish(),
#[cfg(feature = "oauth")]
Self::OAuthU2M {
client_id,
redirect_port,
Expand All @@ -296,6 +301,7 @@ impl std::fmt::Debug for AuthConfig {
.field("redirect_port", redirect_port)
.field("scopes", scopes)
.finish(),
#[cfg(feature = "oauth")]
Self::OAuthFederation {
subject_token_type,
audience,
Expand Down Expand Up @@ -359,18 +365,14 @@ pub struct ProxyConfig {}
/// ```no_run
/// # use databricks_sql_kernel::TlsConfig;
/// // From a file path:
/// let from_file = TlsConfig {
/// custom_ca_cert: Some(std::fs::read("/etc/ssl/corp-ca.pem").unwrap()),
/// ..TlsConfig::default()
/// };
/// let mut from_file = TlsConfig::default();
/// from_file.custom_ca_cert = Some(std::fs::read("/etc/ssl/corp-ca.pem").unwrap());
///
/// // From an in-memory buffer (the napi-rs `Buffer` / pyo3 `bytes`
/// // path — no tempfile shim needed):
/// let pem_bytes: Vec<u8> = b"-----BEGIN CERTIFICATE-----\n...".to_vec();
/// let from_bytes = TlsConfig {
/// custom_ca_cert: Some(pem_bytes),
/// ..TlsConfig::default()
/// };
/// let mut from_bytes = TlsConfig::default();
/// from_bytes.custom_ca_cert = Some(pem_bytes);
/// # let _ = (from_file, from_bytes);
/// ```
//
Expand Down Expand Up @@ -862,6 +864,7 @@ mod tests {
assert!(s.contains("<redacted>"));
}

#[cfg(feature = "oauth")]
#[test]
fn debug_oauth_m2m_redacts_secret() {
let c = AuthConfig::OAuthM2M {
Expand All @@ -876,6 +879,7 @@ mod tests {
assert!(s.contains("<redacted>"));
}

#[cfg(feature = "oauth")]
#[test]
fn debug_oauth_federation_redacts_subject_token() {
let c = AuthConfig::OAuthFederation {
Expand Down
9 changes: 4 additions & 5 deletions src/reader/cloudfetch/arrow_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,9 @@ pub fn parse_arrow_ipc(data: &[u8], compression: CompressionCodec) -> Result<Vec
while !remaining.is_empty() {
let mut decoder = FrameDecoder::new(Cursor::new(remaining));
let before = buf.len();
decoder.read_to_end(&mut buf).map_err(|e| {
Error::io().message(format!("LZ4 decompression failed: {}", e))
})?;
decoder
.read_to_end(&mut buf)
.map_err(|e| Error::io().message(format!("LZ4 decompression failed: {}", e)))?;
let consumed = decoder.into_inner().position() as usize;
if consumed == 0 {
// Defensive: avoid infinite loop if decoder makes no progress.
Expand Down Expand Up @@ -225,8 +225,7 @@ mod tests {
// truncated). We treat any non-success outcome as the
// sanity-check passing — the exact error/empty shape from
// arrow_ipc on a truncated stream isn't part of our contract.
let only_first =
parse_arrow_ipc(&encode(&ipc_data[..mid]), CompressionCodec::Lz4Frame);
let only_first = parse_arrow_ipc(&encode(&ipc_data[..mid]), CompressionCodec::Lz4Frame);
let truncated_yields_batch = matches!(&only_first, Ok(batches) if !batches.is_empty());
assert!(
!truncated_yields_batch,
Expand Down
22 changes: 15 additions & 7 deletions src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,10 @@
//! signature we may need to reshape. The methods will be added once
//! the server contract stabilises.

use crate::auth::{
AuthProvider, AuthorizationCodeProvider, ClientCredentialsProvider, PersonalAccessToken,
};
use crate::auth::AuthProvider;
use crate::auth::PersonalAccessToken;
#[cfg(feature = "oauth")]
use crate::auth::{AuthorizationCodeProvider, ClientCredentialsProvider};
use crate::client::http::TlsConfig as HttpTlsConfig;
use crate::client::retry::{
build_retry_configs, RequestCategory, RetryConfig, RetryConfigOverrides,
Expand Down Expand Up @@ -487,10 +488,8 @@ impl SessionBuilder {
/// ```no_run
/// # use databricks_sql_kernel::{TlsConfig, Session};
/// # fn build() -> Result<(), Box<dyn std::error::Error>> {
/// let tls = TlsConfig {
/// custom_ca_cert: Some(std::fs::read("/etc/ssl/corp-ca.pem")?),
/// ..TlsConfig::default()
/// };
/// let mut tls = TlsConfig::default();
/// tls.custom_ca_cert = Some(std::fs::read("/etc/ssl/corp-ca.pem")?);
/// let _builder = Session::builder().tls(tls);
/// # Ok(()) }
/// ```
Expand Down Expand Up @@ -653,6 +652,12 @@ fn result_to_post_process_options(

/// Build the auth provider for a given [`AuthConfig`]. `host` is the
/// workspace URL — used for OIDC discovery on M2M / U2M flows.
//
// `host` and `http_client` are only consumed by the OAuth match arms;
// under `--no-default-features` they look unused, which would trip
// clippy's `-D warnings`. Conditional `#[allow]` keeps the parameter
// names readable when the feature is on.
#[cfg_attr(not(feature = "oauth"), allow(unused_variables))]
async fn build_auth_provider(
auth: &AuthConfig,
host: &str,
Expand All @@ -667,6 +672,7 @@ async fn build_auth_provider(
}
Ok(Arc::new(PersonalAccessToken::new(token.clone())))
}
#[cfg(feature = "oauth")]
AuthConfig::OAuthM2M {
client_id,
client_secret,
Expand All @@ -692,6 +698,7 @@ async fn build_auth_provider(
.await?;
Ok(Arc::new(provider))
}
#[cfg(feature = "oauth")]
AuthConfig::OAuthU2M {
client_id,
redirect_port,
Expand All @@ -717,6 +724,7 @@ async fn build_auth_provider(
.await?;
Ok(Arc::new(provider))
}
#[cfg(feature = "oauth")]
AuthConfig::OAuthFederation { .. } => Err(Error::invalid_argument()
.message("AuthConfig::OAuthFederation is reserved for v0.1; not yet wired")),
AuthConfig::External(_) => Err(Error::invalid_argument()
Expand Down
6 changes: 6 additions & 0 deletions src/util/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@
/// issue #19), and any caller driving the kernel from a runtime
/// context should also be on multi-thread for the same concurrent-IO
/// reasons.
///
/// **`#[cfg(feature = "oauth")]`** — the only callsites are the
/// OAuth providers' sync `AuthProvider::get_auth_header` impls
/// (`auth/oauth/m2m.rs` + `auth/oauth/u2m.rs`). PAT auth is fully
/// synchronous and doesn't need the runtime bridge.
#[cfg(feature = "oauth")]
pub(crate) fn block_on_in_runtime<F>(runtime_handle: &tokio::runtime::Handle, fut: F) -> F::Output
where
F: std::future::Future,
Expand Down
5 changes: 5 additions & 0 deletions tests/oauth_u2m_integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@
// See the License for the specific language governing permissions and
// limitations under the License.

// Whole-file gate: every test here exercises `crate::auth::oauth`, which
// is only compiled when the `oauth` feature is on. Under `--no-default-features`
// the module is absent and these tests can't link.
#![cfg(feature = "oauth")]

//! Wiremock integration tests for OAuth U2M refresh token flow.
//!
//! These tests use the wiremock crate to simulate OIDC discovery and token endpoints,
Expand Down
2 changes: 2 additions & 0 deletions tests/v0_session_e2e.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ async fn open_with_pat_against_live_warehouse() {
.expect("explicit close() should succeed");
}

#[cfg(feature = "oauth")]
#[tokio::test]
#[ignore]
async fn open_with_oauth_m2m_against_live_warehouse() {
Expand Down Expand Up @@ -98,6 +99,7 @@ async fn open_with_oauth_m2m_against_live_warehouse() {
session.close().await.expect("close()");
}

#[cfg(feature = "oauth")]
#[tokio::test]
#[ignore]
async fn open_with_oauth_u2m_against_live_warehouse() {
Expand Down
Loading