diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index d4f1aadb..ba0abae5 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -28,6 +28,15 @@ changes go in their respective binding's NEXT_CHANGELOG. value is ignored (default preserved) with a warning rather than failing session creation. The key is client-only — it is consumed before session creation and never reaches the SEA wire. Benefits ODBC too. +- C ABI: `kernel_abi_version()` + the `DATABRICKS_KERNEL_ABI_VERSION` header + macro — a consumer that links a prebuilt library can compare the two once at + load time and refuse to run on a mismatch, guarding against a stale + header/`.a` layout drift. Bumped in lockstep on any layout/meaning change. +- C ABI: `kernel_session_config_set_tls_client_certificate()` — expose the + crate's existing mTLS client cert/key (`TlsConfig::client_cert_pem` / + `client_key_pem`) over the C ABI as a single paired setter. Both halves + required together (cert-without-key is unrepresentable); the private key is + never logged. ### Updated diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index c235cd14..e45cf6d0 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -46,6 +46,20 @@ * out exactly as declared here; copy its fields out before the next * `kernel_*` call on the thread. * + * Because there is no promise through v0.x, a consumer that links a + * prebuilt library can drift from the header it compiled against (a stale + * header vs a newer `.a`, or vice versa). The `DATABRICKS_KERNEL_ABI_VERSION` + * macro below is the version this header describes; `kernel_abi_version()` + * returns the version compiled into the linked library. A consumer should + * compare the two once at load time and refuse to run on a mismatch — + * otherwise a layout change (e.g. a reordered `KernelStatusCode`) would be + * misread as valid data rather than surfaced as a clean error. The macro is + * bumped in lockstep with the Rust `KERNEL_ABI_VERSION`. It is a COARSE + * pre-1.0 handshake, not bumped per PR: while the surface is still being + * built out, additive symbols land without a bump, and it moves only at a + * deliberate checkpoint (a layout / semantic change, or a stabilisation + * milestone). + * * ## Lifecycle & threading notes * * - **Re-execution invalidates prior handles.** `kernel_statement_execute` @@ -90,6 +104,19 @@ extern "C" { #endif +/* ─── ABI version ───────────────────────────────────────────────────── + * + * The C-ABI version this header describes. `kernel_abi_version()` returns + * the version compiled into the linked library; compare the two once at + * load time and refuse to run on a mismatch (see "ABI versioning" above). + * Bumped in lockstep with the Rust `KERNEL_ABI_VERSION`. + */ +#define DATABRICKS_KERNEL_ABI_VERSION 1 + +/* Version of the C ABI compiled into the linked library. Infallible and + * side-effect-free. */ +uint32_t kernel_abi_version(void); + /* ─── Arrow C Data Interface ────────────────────────────────────────── * * Mirrors the canonical `ArrowArray` / `ArrowSchema` from the Arrow C @@ -338,6 +365,19 @@ KernelStatusCode kernel_session_config_set_retry_config(KernelSessionConfig* con uint32_t max_retries, uint64_t overall_timeout_ms); +/* Configure a client certificate + private key for mutual TLS (mTLS). + * BOTH halves are required and passed together: `cert_pem`/`cert_len` is a + * PEM leaf cert optionally followed by its intermediate chain; `key_pem`/ + * `key_len` is the matching PEM private key (use PKCS#8 for portability + * across the tls-native and tls-rustls backends). Taking both at once makes + * cert-without-key unrepresentable. A null buffer or zero length for either + * half returns InvalidArgument. The private key is never rendered in logs. */ +KernelStatusCode kernel_session_config_set_tls_client_certificate(KernelSessionConfig* config, + const uint8_t* cert_pem, + size_t cert_len, + const uint8_t* key_pem, + size_t key_len); + /* ─── Session lifecycle ───────────────────────────────────────────────*/ /* diff --git a/src/c_abi/mod.rs b/src/c_abi/mod.rs index bdb54a4c..799c747a 100644 --- a/src/c_abi/mod.rs +++ b/src/c_abi/mod.rs @@ -269,10 +269,44 @@ impl From for KernelStatusCode { } } +/// Current C-ABI version. A coarse pre-1.0 handshake, NOT bumped per PR: +/// while the surface is still being built out, additive symbols land without +/// a bump (a consumer that doesn't reference a new symbol is unaffected, and +/// one that does rebuilds against the matching header anyway). Bump it only at +/// a deliberate checkpoint — a struct-layout change ([`KernelStatusCode`], +/// `KernelError`), a change to the meaning of an existing symbol, or a +/// stabilisation milestone — so a consumer compiled against one header can +/// detect a library built against a different one. Kept in lockstep with the +/// `DATABRICKS_KERNEL_ABI_VERSION` macro in `include/databricks_kernel.h` (the +/// C smoke test asserts the two agree). Pure v0.x aid — there is no ABI +/// stability promise until v1.0. +pub const KERNEL_ABI_VERSION: u32 = 1; + +/// Report the C-ABI version compiled into this library. A consumer that +/// linked a header declaring `DATABRICKS_KERNEL_ABI_VERSION` should refuse +/// to run against a library whose `kernel_abi_version()` differs, since a +/// mismatch means the `KernelStatusCode` enum / `KernelError` layout it +/// reads may not match what this library writes. Infallible and +/// side-effect-free, so it takes no config and returns the value directly +/// (no `KernelStatusCode` / last-error dance). +#[no_mangle] +pub extern "C" fn kernel_abi_version() -> u32 { + KERNEL_ABI_VERSION +} + #[cfg(test)] mod tests { use super::*; + /// The exported `kernel_abi_version()` returns the crate-level + /// `KERNEL_ABI_VERSION` constant, so the two can't drift. (The C side's + /// `DATABRICKS_KERNEL_ABI_VERSION` macro is checked against this in the + /// C-smoke test, closing the Rust↔header loop.) + #[test] + fn abi_version_is_current() { + assert_eq!(kernel_abi_version(), KERNEL_ABI_VERSION); + } + /// `block_on_ffi` must reject a reentrant call (one made from a thread /// already inside a Tokio runtime) with a typed `Internal` error and a /// populated last-error, rather than letting `Runtime::block_on` panic diff --git a/src/c_abi/result.rs b/src/c_abi/result.rs index eec29de0..cdad7d27 100644 --- a/src/c_abi/result.rs +++ b/src/c_abi/result.rs @@ -212,8 +212,8 @@ pub unsafe extern "C" fn kernel_result_stream_next_batch( // Owned (metadata): drive the owned ResultStream lazily on the // runtime, one batch at a time, so an unbounded result streams // with bounded memory. Running through block_on_ffi keeps the - // (possibly CloudFetch-backed) reader on the tokio reactor - // rather than off a plain C thread. + // (possibly CloudFetch-backed) reader on the tokio reactor rather + // than off a plain C thread. ResultStreamInner::Owned { stream, .. } => { match super::block_on_ffi(move || { let stream: &mut crate::result_stream::ResultStream = stream; diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 573bbf29..8da30968 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -132,6 +132,12 @@ struct TlsSpec { custom_ca_cert: Option>, accept_self_signed: bool, skip_hostname_verification: bool, + /// PEM-encoded client leaf cert (+ optional chain) for mTLS. Always + /// set together with `client_key_pem` — the paired setter takes both + /// at once, so one-without-the-other is unrepresentable here. + client_cert_pem: Option>, + /// PEM-encoded private key for the mTLS client cert. Never logged. + client_key_pem: Option>, } /// Read a required C string argument into an owned `String`, mapping a @@ -590,6 +596,48 @@ pub unsafe extern "C" fn kernel_session_config_set_tls_skip_hostname_verificatio }) } +/// Configure a client certificate + private key for mutual TLS (mTLS). +/// Both halves are REQUIRED and passed together: `cert_pem`/`cert_len` is +/// a PEM leaf certificate optionally followed by its intermediate chain, +/// and `key_pem`/`key_len` is the matching PEM private key (PKCS#8 for +/// cross-backend portability — see [`TlsConfig::client_key_pem`]). Taking +/// both in one call makes cert-without-key unrepresentable at the ABI, so +/// the crate's both-or-neither pairing rule can't be tripped from here. +/// Maps to `TlsConfig::client_cert_pem` / `client_key_pem`. +/// +/// Any of a null `cert_pem`/`key_pem` or a zero `cert_len`/`key_len` +/// returns `InvalidArgument` — mTLS needs real bytes for both halves. +/// +/// The private key bytes are copied into owned Rust memory and are NEVER +/// rendered in logs (the kernel's `TlsConfig` `Debug` redacts the key). +/// +/// # Safety +/// `config` must be a live config handle; `cert_pem` must point to +/// `cert_len` readable bytes and `key_pem` to `key_len` readable bytes. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_tls_client_certificate( + config: *mut KernelSessionConfig, + cert_pem: *const u8, + cert_len: usize, + key_pem: *const u8, + key_len: usize, +) -> KernelStatusCode { + set_on_config(config, |c| { + if cert_pem.is_null() || cert_len == 0 { + return Err(Error::invalid_argument() + .message("mTLS client cert must be a non-empty PEM buffer")); + } + if key_pem.is_null() || key_len == 0 { + return Err( + Error::invalid_argument().message("mTLS client key must be a non-empty PEM buffer") + ); + } + c.tls.client_cert_pem = Some(std::slice::from_raw_parts(cert_pem, cert_len).to_vec()); + c.tls.client_key_pem = Some(std::slice::from_raw_parts(key_pem, key_len).to_vec()); + Ok(()) + }) +} + /// Shared body for the config setters: null-check the handle, clear the /// thread-local error, run `f` against the borrowed config, and store /// any error. @@ -711,8 +759,7 @@ fn merge_http_config( /// Translate the C-side config into a [`Session`], driving the async /// `Session::open` on the process-wide runtime. Errors are stored in the -/// thread-local buffer; the returned `KernelStatusCode` is the mapped -/// code. +/// thread-local buffer; the returned `KernelStatusCode` is the mapped code. fn build_session(config: KernelSessionConfig) -> Result { let KernelSessionConfig { connection, @@ -788,17 +835,22 @@ fn build_session(config: KernelSessionConfig) -> Result::uninit(); + let present = crate::c_abi::error::kernel_get_last_error(out.as_mut_ptr()); + assert!(present, "a failed open must populate the last-error buffer"); + let err = out.assume_init(); + let msg = std::ffi::CStr::from_ptr(err.message).to_str().unwrap(); + assert!( + msg.contains("Invalid mTLS client certificate/key"), + "the failure must be the mTLS identity parse (both halves forwarded), \ + not a missing-half or unrelated error; got: {msg}" + ); + assert!( + !msg.contains("without client_key_pem") && !msg.contains("without client_cert_pem"), + "neither half may be dropped on the forwarding path; got: {msg}" + ); + // No kernel_session_config_free: kernel_session_open already consumed + // and released `config` on its failure path. + } + } + /// End-to-end: a **retry-only** config (no custom headers) must actually /// reach the HTTP client through `build_session`'s /// `!custom_headers.is_empty() || retry.is_some()` gate + the diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index fbb87540..72463196 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -44,6 +44,17 @@ static int failures = 0; } \ } while (0) +/* The library's compiled-in ABI version must match the macro this header + * declares. This is the C half of the Rust↔header lockstep: the in-crate + * `abi_version_is_current` test pins kernel_abi_version() to the Rust + * KERNEL_ABI_VERSION constant, and this check pins it to the header's + * DATABRICKS_KERNEL_ABI_VERSION — together they catch header/library drift. */ +static void test_abi_version_matches_header(void) { + uint32_t lib = kernel_abi_version(); + CHECK(lib == DATABRICKS_KERNEL_ABI_VERSION, + "kernel_abi_version() matches DATABRICKS_KERNEL_ABI_VERSION"); +} + /* Config new → set warehouse + PAT → free, with no open. */ static void test_config_lifecycle(void) { KernelSessionConfig* config = NULL; @@ -177,6 +188,21 @@ static void test_proxy_and_tls_setters(void) { rc = kernel_session_config_set_retry_config(config, 5000, 1000, 3, 0); CHECK(rc == KernelStatusCode_InvalidArgument, "set_retry_config(max