diff --git a/include/databricks_kernel.h b/include/databricks_kernel.h index 8e9cc8d3..969bedda 100644 --- a/include/databricks_kernel.h +++ b/include/databricks_kernel.h @@ -202,8 +202,8 @@ typedef struct kernel_result_stream_t kernel_result_stream_t; * * Build a config, set exactly one connection form and exactly one auth * form, then hand it to `kernel_session_open` (which consumes it). Only - * PAT and OAuth M2M auth are exposed over the C ABI in v0; OAuth U2M - * (interactive browser flow) is Rust-crate-only. + * PAT, OAuth M2M, and OAuth U2M (interactive browser flow) auth are + * exposed over the C ABI. */ KernelStatusCode kernel_session_config_new(KernelSessionConfig** out); void kernel_session_config_free(KernelSessionConfig* config); @@ -222,12 +222,41 @@ KernelStatusCode kernel_session_config_set_auth_pat(KernelSessionConfig* config, KernelStatusCode kernel_session_config_set_auth_m2m(KernelSessionConfig* config, const char* client_id, const char* client_secret); +/* OAuth U2M (user-to-machine: authorization code + PKCE, browser flow). + * All args optional: `client_id` NULL → public `databricks-cli` client; + * `redirect_port` 0 → kernel default (8020); `scopes` (comma-separated) + * NULL → kernel default (`all-apis`,`offline_access`; `offline_access` + * yields a cached, auto-refreshed refresh token). INTERACTIVE: opening the + * session starts a localhost listener and opens the user's browser. */ +KernelStatusCode kernel_session_config_set_auth_u2m(KernelSessionConfig* config, + const char* client_id, + uint16_t redirect_port, + const char* scopes); /* Add (or overwrite) one server-bound session-conf entry. */ KernelStatusCode kernel_session_config_set_session_conf(KernelSessionConfig* config, const char* key, const char* value); +/* Append one HTTP header sent on every request. Call once per header + * (order preserved); `name` and `value` are both required. */ +KernelStatusCode kernel_session_config_set_custom_header(KernelSessionConfig* config, + const char* name, const char* value); + +/* Initialize kernel logging, process-wide and ONCE (first call wins; + * later calls are no-ops). `level` is OFF/ERROR/WARN/INFO/DEBUG/TRACE + * (NULL → RUST_LOG, default warn); `file_path` NULL → stderr. Not tied to + * a session — lets a host route kernel logs into its own log file. + * + * A non-UTF-8 `file_path` returns InvalidArgument. Otherwise the result + * reflects the FIRST call's outcome (a later call's level/file have no + * effect and are not described by its return): Success when logging was + * installed against the request (or skipped for level OFF); Internal (with + * a stored last-error) when that install did not fully honour the request + * — the file could not be opened (falls back to stderr) or a global + * subscriber was already installed (no kernel subscriber installed). */ +KernelStatusCode kernel_init_logging(const char* level, const char* file_path); + /* ─── Proxy / TLS (optional) ────────────────────────────────────────── * * All optional; defaults are: no explicit proxy (reqwest honours @@ -268,6 +297,14 @@ KernelStatusCode kernel_session_config_set_tls_skip_hostname_verification(Kernel KernelStatusCode kernel_session_open(KernelSessionConfig* config, kernel_session_t** out); KernelStatusCode kernel_session_close(kernel_session_t* session); +/* Report whether a session is still OPEN (its delete has not been + * initiated). Writes true/false to `*out`. LOCAL check only — no server + * round-trip, so it does NOT detect a server idle-timeout or dropped + * link; it reports only whether the handle has been closed/superseded. + * A host backing SQL_ATTR_CONNECTION_DEAD should read `true` as + * "not known-dead", not a positive liveness guarantee. No ownership. */ +KernelStatusCode kernel_session_is_open(const kernel_session_t* session, bool* out); + /* Construct a new mutable statement bound to this session. */ KernelStatusCode kernel_session_new_statement(kernel_session_t* session, kernel_statement_t** out); diff --git a/src/c_abi/session.rs b/src/c_abi/session.rs index 005261d5..24a18ef1 100644 --- a/src/c_abi/session.rs +++ b/src/c_abi/session.rs @@ -14,17 +14,16 @@ //! Session FFI — config marshalling, open / close / new_statement. //! -//! Auth in the v0 C ABI is **PAT + OAuth M2M** only; OAuth U2M -//! (interactive browser flow) is Rust-crate-only per the migration -//! plan §6 ("OAuth U2M and the C ABI"). ODBC / Go consumers use PAT or -//! M2M, or drive their own token flow and inject it (not yet exposed -//! over the C ABI in v0). +//! Auth over the C ABI: **PAT, OAuth M2M, and OAuth U2M** (interactive +//! browser flow) are all exposed (`set_auth_pat` / `set_auth_m2m` / +//! `set_auth_u2m`). A host may also drive its own token flow and inject +//! it via PAT. //! //! Transaction methods (autocommit / commit / rollback) are deferred to //! v0.1 per `docs/spec-v0.md` addendum A5. use super::{block_on_ffi, KernelStatusCode}; -use crate::config::{AuthConfig, ConnectionConfig, ProxyConfig, TlsConfig}; +use crate::config::{AuthConfig, ConnectionConfig, HttpConfig, ProxyConfig, TlsConfig}; use crate::kernel_error::Error; use crate::session::Session; use std::collections::HashMap; @@ -60,6 +59,16 @@ enum AuthSpec { client_id: String, client_secret: String, }, + /// OAuth user-to-machine (authorization code + PKCE, browser flow). + /// All fields optional — the kernel fills `databricks-cli` / + /// port 8020 / default scopes when omitted. + OAuthU2M { + client_id: Option, + redirect_port: Option, + /// Comma-separated scopes (split at build time). `None` ⇒ kernel + /// default (`all-apis`, `offline_access`). + scopes: Option, + }, } /// C-side session config builder state. @@ -83,6 +92,9 @@ pub struct KernelSessionConfig { /// TLS relaxations / custom trust (populated by the `..._set_tls_*` /// setters). Defaults to the kernel's strict validation. tls: TlsSpec, + /// Extra HTTP headers sent on every request (accumulated by + /// `..._set_custom_header`, one `(name, value)` pair per call). + custom_headers: Vec<(String, String)>, } /// C-side proxy config captured from `kernel_session_config_set_proxy`. @@ -143,6 +155,7 @@ pub unsafe extern "C" fn kernel_session_config_new( session_conf: HashMap::new(), proxy: None, tls: TlsSpec::default(), + custom_headers: Vec::new(), }); std::ptr::write(out, Box::into_raw(config)); KernelStatusCode::Success @@ -249,6 +262,116 @@ pub unsafe extern "C" fn kernel_session_config_set_auth_m2m( }) } +/// Set OAuth U2M (user-to-machine: authorization code + PKCE, browser +/// flow) authentication. Mutually exclusive with the other `set_auth_*` +/// setters — the last one called wins. +/// +/// All args are optional (pass NULL to omit): `client_id` defaults to the +/// public `databricks-cli` client, `redirect_port` to 8020, and `scopes` +/// (a comma-separated list) to the kernel default (`all-apis`, +/// `offline_access`). `offline_access` yields a refresh token, which the +/// kernel caches and refreshes transparently. +/// +/// **Behaviour:** opening a session with U2M is interactive — at +/// `kernel_session_open` the kernel starts a localhost listener on the +/// redirect port and opens the user's browser to the workspace authorize +/// endpoint. Only use from an interactive context. +/// +/// # Safety +/// `config` must be a live config handle; the optional args, if non-null, +/// must be NUL-terminated C strings. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_auth_u2m( + config: *mut KernelSessionConfig, + client_id: *const c_char, + redirect_port: u16, + scopes: *const c_char, +) -> KernelStatusCode { + set_on_config(config, |c| { + c.auth = Some(AuthSpec::OAuthU2M { + client_id: optional_str(client_id, "client_id")?, + // 0 is the "unset" sentinel → kernel default (8020). + redirect_port: (redirect_port != 0).then_some(redirect_port), + scopes: optional_str(scopes, "scopes")?, + }); + Ok(()) + }) +} + +/// Append one HTTP header sent on every request (e.g. a partner-supplied +/// `X-…` header). Call once per header; order is preserved. Both `name` +/// and `value` are required. Maps to the kernel's `custom_headers`. +/// +/// # Safety +/// `config` must be a live config handle; `name` / `value` must be +/// NUL-terminated C strings. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_config_set_custom_header( + config: *mut KernelSessionConfig, + name: *const c_char, + value: *const c_char, +) -> KernelStatusCode { + set_on_config(config, |c| { + let name = required_str(name, "header name")?; + let value = required_str(value, "header value")?; + c.custom_headers.push((name, value)); + Ok(()) + }) +} + +/// Initialize kernel logging, **process-wide and once**. `level` is one +/// of "OFF"/"ERROR"/"WARN"/"INFO"/"DEBUG"/"TRACE" (NULL ⇒ honour +/// `RUST_LOG`, default `warn`); `file_path` is a log file (NULL ⇒ stderr). +/// +/// Idempotent: the underlying `tracing` subscriber can only be installed +/// once per process, so the **first** call wins and later calls are +/// no-ops (a driver that opens many connections calls this each time with +/// the same target — only the first takes effect). Not tied to a session; +/// call it before/around `kernel_session_open`. Lets an ODBC/Go host route +/// the kernel's logs into the same file it writes its own logs to. +/// +/// A non-UTF-8 `file_path` returns `InvalidArgument` (the requested path +/// can't be honoured). Otherwise returns `Success` when the FIRST call +/// installed logging against the requested destination (or was skipped for +/// level `OFF`), or `Internal` (with a stored last-error) when that first +/// install did not fully honour the request — the log file couldn't be +/// opened (logging fell back to stderr) or a global subscriber was already +/// installed (no kernel subscriber installed). Because init is +/// once-per-process, the Success/Internal result reflects the **first** +/// call's outcome, NOT a later call's `level`/`file_path` (which have no +/// effect). A caller that can't see stderr can use `Internal` to surface +/// the degradation. +/// +/// # Safety +/// `level` / `file_path`, if non-null, must be NUL-terminated C strings. +#[no_mangle] +pub unsafe extern "C" fn kernel_init_logging( + level: *const c_char, + file_path: *const c_char, +) -> KernelStatusCode { + crate::c_abi::error::clear_error(); + // `level` is best-effort: a non-UTF-8 or unrecognized value falls back + // to RUST_LOG / the default, so treat a bad level as absent. + let level = optional_str(level, "log level").ok().flatten(); + // `file_path` is NOT best-effort: a non-UTF-8 path is a real error (the + // caller asked us to write there and we can't), so surface it rather + // than silently dropping the path and reporting Success. + let file = match optional_str(file_path, "log file path") { + Ok(f) => f, + Err(e) => return crate::c_abi::error::store_and_code(e), + }; + if crate::logging::init_logging(&crate::logging::LogConfig { level, file }) { + KernelStatusCode::Success + } else { + crate::c_abi::error::store_and_code(Error::new( + crate::kernel_error::ErrorCode::Internal, + "kernel_init_logging: logging was not fully initialized as requested (the log file \ + could not be opened, or a global subscriber was already installed); kernel logs may \ + go to stderr or not flow", + )) + } +} + /// Add (or overwrite) one server-bound session-conf entry. Unknown keys /// are filtered against the kernel allowlist at `open()` time, matching /// the Rust-crate path. @@ -443,6 +566,19 @@ pub unsafe extern "C" fn kernel_session_open( KernelStatusCode::Success } +/// Split a comma-separated OAuth scope string into a scope list. Trims +/// each entry and drops empties; an all-empty / blank input yields `None` +/// so the kernel applies its default scopes. E.g. `"a, ,b,"` → `["a","b"]`. +fn parse_scopes(s: &str) -> Option> { + let v: Vec = s + .split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned) + .collect(); + (!v.is_empty()).then_some(v) +} + /// 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 @@ -454,6 +590,7 @@ fn build_session(config: KernelSessionConfig) -> Result Result Result AuthConfig::oauth_m2m(Some(client_id), Some(client_secret), None, None)?, + AuthSpec::OAuthU2M { + client_id, + redirect_port, + scopes, + } => AuthConfig::oauth_u2m( + client_id, + redirect_port, + scopes.and_then(|s| parse_scopes(&s)), + None, + None, + ), }; let mut builder = Session::builder() @@ -491,6 +640,15 @@ fn build_session(config: KernelSessionConfig) -> Result KernelStatusCode::Success } +/// Report whether a session is still **open** (its server-side delete has +/// not been initiated). Writes `true`/`false` to `*out`. +/// +/// This is a **local** check — it does NOT round-trip to the server, so it +/// will NOT detect a server-side idle timeout or a dropped network link. +/// It answers only "has this handle been closed/superseded". A host using +/// it to back `SQLGetConnectAttr(SQL_ATTR_CONNECTION_DEAD)` should treat a +/// `true` result as "not known-dead" rather than a positive liveness +/// guarantee. Does not borrow ownership; the caller still owns `session`. +/// +/// # Safety +/// `session` must be a live handle from [`kernel_session_open`] (not yet +/// closed via [`kernel_session_close`]); `out` must be a writable `bool*`. +#[no_mangle] +pub unsafe extern "C" fn kernel_session_is_open( + session: *const kernel_session_t, + out: *mut bool, +) -> KernelStatusCode { + crate::c_abi::error::clear_error(); + let Some(session) = (session as *const Session).as_ref() else { + crate::c_abi::error::store_error( + Error::invalid_argument().message("kernel_session_is_open: session must not be null"), + ); + return KernelStatusCode::InvalidArgument; + }; + if out.is_null() { + crate::c_abi::error::store_error( + Error::invalid_argument().message("kernel_session_is_open: out must not be null"), + ); + return KernelStatusCode::InvalidArgument; + } + std::ptr::write(out, session.is_open()); + KernelStatusCode::Success +} + /// Construct a new mutable statement bound to this session. On success, /// `*out` holds an owned `kernel_statement_t` the caller releases with /// `kernel_statement_close`. @@ -594,3 +787,58 @@ pub unsafe extern "C" fn kernel_session_new_statement( // pub unsafe extern "C" fn kernel_session_set_autocommit(...) -> KernelStatusCode; // pub unsafe extern "C" fn kernel_session_commit(...) -> KernelStatusCode; // pub unsafe extern "C" fn kernel_session_rollback(...) -> KernelStatusCode; + +#[cfg(test)] +mod tests { + use super::*; + use std::ffi::CString; + + #[test] + fn parse_scopes_trims_and_drops_empties() { + assert_eq!( + parse_scopes("a, ,b,"), + Some(vec!["a".to_string(), "b".to_string()]) + ); + assert_eq!( + parse_scopes("all-apis,offline_access"), + Some(vec!["all-apis".to_string(), "offline_access".to_string()]) + ); + // All-empty / blank → None so the kernel applies its defaults. + assert_eq!(parse_scopes(""), None); + assert_eq!(parse_scopes(" , , "), None); + } + + /// Custom headers accumulate in call order and are NOT deduped (the + /// contract is append/ordered, unlike session_conf's overwrite map). + /// Guards against a refactor to a dedup'ing map silently dropping + /// repeated header names. + #[test] + fn custom_headers_accumulate_in_order_with_duplicates() { + unsafe { + let mut config: *mut KernelSessionConfig = std::ptr::null_mut(); + assert_eq!( + kernel_session_config_new(&mut config), + KernelStatusCode::Success + ); + let pairs = [("X-A", "1"), ("X-B", "2"), ("X-A", "3")]; + for (n, v) in pairs { + let name = CString::new(n).unwrap(); + let value = CString::new(v).unwrap(); + assert_eq!( + kernel_session_config_set_custom_header(config, name.as_ptr(), value.as_ptr()), + KernelStatusCode::Success + ); + } + let got = &config.as_ref().unwrap().custom_headers; + let expected: Vec<(String, String)> = pairs + .iter() + .map(|(n, v)| (n.to_string(), v.to_string())) + .collect(); + assert_eq!( + *got, expected, + "headers must be appended in order, duplicates kept" + ); + kernel_session_config_free(config); + } + } +} diff --git a/src/logging.rs b/src/logging.rs index 15e9ee37..24fd61e8 100644 --- a/src/logging.rs +++ b/src/logging.rs @@ -57,7 +57,12 @@ use tracing_subscriber::{ EnvFilter, }; -static LOGGING_INITIALIZED: OnceLock<()> = OnceLock::new(); +/// Records the outcome of the first `init_logging` call: `true` if the +/// subscriber was installed (or intentionally skipped for level=OFF), +/// `false` if it could not be installed (e.g. the log file failed to +/// open). Later calls return this same first-call outcome ("first call +/// wins"). +static LOGGING_INITIALIZED: OnceLock = OnceLock::new(); /// Logging configuration passed via ADBC database options. #[derive(Debug, Clone, Default)] @@ -70,42 +75,64 @@ pub(crate) struct LogConfig { /// Initialize the tracing subscriber. /// -/// Uses `OnceLock` to ensure this is called at most once per process. -/// The first `Database::new_connection()` call configures logging; -/// subsequent calls are no-ops. -pub(crate) fn init_logging(config: &LogConfig) { - LOGGING_INITIALIZED.get_or_init(|| { - // Check if the configured level is "OFF" — skip initialization entirely +/// Uses `OnceLock` to ensure this runs at most once per process — the +/// **first** call configures logging and installs the subscriber; every +/// later call is a no-op that returns that **first call's** outcome (the +/// subscriber can only be installed once, so a later call's `config` — its +/// level / file — has no effect and its return does not describe its own +/// arguments). +/// +/// Returns `true` if the first call installed the subscriber against the +/// requested destination (or was intentionally skipped for level `OFF`). +/// Returns `false` if that install did not fully honour the request — +/// either the requested log file could not be opened (logging fell back to +/// stderr) or the global subscriber was already installed by another +/// component (so no kernel subscriber was installed). Callers that cannot +/// see stderr (GUI / BI hosts) can use `false` to surface the degradation. +pub(crate) fn init_logging(config: &LogConfig) -> bool { + *LOGGING_INITIALIZED.get_or_init(|| { + // Check if the configured level is "OFF" — skip initialization + // entirely, but treat it as a successful (intentional) outcome. if let Some(ref level) = config.level { if level.eq_ignore_ascii_case("off") { - return; + return true; } } + // The filter directive MUST target the same string the kernel's + // log macros emit with — `KERNEL_LOG_TARGET` ("databricks::sql::kernel"). + // `EnvFilter` matches by `::`-delimited segment prefix, so a + // single token like "databricks_sql_kernel" would match NOTHING + // and silently drop every kernel event. let filter = if let Some(ref level) = config.level { - EnvFilter::new(format!("databricks_sql_kernel={}", level.to_lowercase())) + EnvFilter::new(format!("{}={}", crate::klog::KERNEL_LOG_TARGET, level.to_lowercase())) } else { // Fall back to RUST_LOG env var, default to warn - EnvFilter::try_from_default_env() - .unwrap_or_else(|_| EnvFilter::new("databricks_sql_kernel=warn")) + EnvFilter::try_from_default_env().unwrap_or_else(|_| { + EnvFilter::new(format!("{}=warn", crate::klog::KERNEL_LOG_TARGET)) + }) }; - if let Some(ref path) = config.file { - let file = match std::fs::OpenOptions::new() - .create(true) - .append(true) - .open(path) - { - Ok(f) => f, + // Try the requested file; on failure fall back to stderr WITHIN + // this same call so logging still works (rather than committing the + // OnceLock with no subscriber and locking out all later attempts). + // Return `false` only to signal the requested file wasn't honoured. + let file = config.file.as_ref().and_then(|path| { + match std::fs::OpenOptions::new().create(true).append(true).open(path) { + Ok(f) => Some(f), Err(e) => { - eprintln!( - "databricks-sql-kernel: failed to open log file {}: {}", - path, e - ); - return; + eprintln!("databricks-sql-kernel: failed to open log file {path}: {e}; falling back to stderr"); + None } - }; + } + }); + let file_requested_ok = config.file.is_none() || file.is_some(); + // `try_init` returns Err if a global subscriber was already + // installed by another component — in which case NO kernel + // subscriber is installed and logs won't flow, so that must fold + // into the outcome (not be swallowed with `.ok()`). + let installed = if let Some(file) = file { tracing_subscriber::registry() .with(filter) .with( @@ -116,7 +143,7 @@ pub(crate) fn init_logging(config: &LogConfig) { .with_timer(SystemTime), ) .try_init() - .ok(); + .is_ok() } else { tracing_subscriber::registry() .with(filter) @@ -127,9 +154,12 @@ pub(crate) fn init_logging(config: &LogConfig) { .with_timer(SystemTime), ) .try_init() - .ok(); - } - }); + .is_ok() + }; + // Success only if the subscriber installed AND the requested file + // (if any) was honoured. + installed && file_requested_ok + }) } #[cfg(test)] @@ -152,4 +182,46 @@ mod tests { assert_eq!(config.level.as_deref(), Some("DEBUG")); assert_eq!(config.file.as_deref(), Some("/tmp/test.log")); } + + /// The filter directive must be built from `KERNEL_LOG_TARGET` so it + /// actually matches the target the kernel's log macros emit with. + /// A single-token filter like "databricks_sql_kernel" would match + /// nothing (EnvFilter uses `::`-delimited prefix matching), silently + /// dropping every kernel event. This pins the target string the + /// filter is derived from so a regression to the wrong token is caught + /// without depending on installing the process-global subscriber. + #[test] + fn log_target_is_double_colon_delimited() { + assert_eq!(crate::klog::KERNEL_LOG_TARGET, "databricks::sql::kernel"); + // The directive we build (see init_logging) must use this exact + // target, not an underscore-joined token. + let directive = format!("{}=debug", crate::klog::KERNEL_LOG_TARGET); + assert!(directive.starts_with("databricks::sql::kernel=")); + // EnvFilter must accept the directive we construct. + let _filter = EnvFilter::new(directive); + } + + /// `init_logging` is idempotent in its return value: because the + /// subscriber installs once per process, every call returns the SAME + /// (first-call) outcome. We assert only that invariant — not a + /// specific true/false — because the absolute value depends on whether + /// some other test in the shared binary installed the global + /// subscriber first (which would make this call's try_init fail). The + /// first-call-installs-cleanly case is exercised end-to-end by the + /// wiremock session tests. + #[test] + fn init_logging_return_is_idempotent() { + let cfg = LogConfig { + level: Some("warn".to_string()), + file: None, + }; + let first = init_logging(&cfg); + // A later call with a different config must still return the first + // outcome (its own args have no effect). + let second = init_logging(&LogConfig { + level: Some("debug".to_string()), + file: Some("/nonexistent/dir/should-not-matter.log".to_string()), + }); + assert_eq!(first, second, "later calls return the first-call outcome"); + } } diff --git a/src/session.rs b/src/session.rs index ce6ac4e0..09e49cd0 100644 --- a/src/session.rs +++ b/src/session.rs @@ -374,6 +374,17 @@ impl Session { self.inner.initiate_delete(); } + /// Whether this session is still open — i.e. its server-side delete + /// has not been initiated (via [`Session::close`] or + /// [`Session::initiate_delete`]). This is a **local** check, not a + /// server round-trip: it reports whether the handle has been + /// closed/superseded, so a caller doesn't drive an already-deleted + /// session. It does **not** detect a server-side idle timeout or a + /// dropped network link. Backs the C ABI's `kernel_session_is_open`. + pub(crate) fn is_open(&self) -> bool { + !self.inner.closed.load(std::sync::atomic::Ordering::Acquire) + } + /// Adopt an already-submitted server statement by its id, producing /// an [`ExecutedAsyncStatement`] that can poll [`status`] / await /// results / cancel — without having been the handle that submitted @@ -998,3 +1009,58 @@ mod retry_config_tests { assert_eq!(hcc.read_timeout, Duration::from_millis(4500)); } } + +#[cfg(test)] +mod is_open_tests { + use super::*; + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + /// `Session::is_open` reports true for a freshly-opened session and + /// false once its server-side delete has been initiated. This is the + /// only place the false path is reachable — over the C ABI + /// `kernel_session_close` frees the handle in the same call, so the C + /// wrapper can't observe it; `is_open`/`initiate_delete` are + /// `pub(crate)`, so this must live in-crate. Guards against an + /// inverted / hardcoded-true regression (hosts back + /// `SQL_ATTR_CONNECTION_DEAD` on this). + #[tokio::test] + async fn is_open_flips_true_to_false_on_delete() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/2.0/sql/sessions")) + .respond_with( + ResponseTemplate::new(200) + .set_body_string(r#"{"session_id":"sess-is-open","warehouse_id":"test_wh"}"#), + ) + .mount(&server) + .await; + Mock::given(method("DELETE")) + .and(path("/api/2.0/sql/sessions/sess-is-open")) + .respond_with(ResponseTemplate::new(200)) + .mount(&server) + .await; + + let session = Session::builder() + .connection( + ConnectionConfig::from_http_path(server.uri(), "/sql/1.0/warehouses/test_wh") + .expect("valid http_path"), + ) + .auth(AuthConfig::Pat { + token: "dapi_test_token".into(), + }) + .open() + .await + .expect("session must open"); + + assert!( + session.is_open(), + "a freshly-opened session must report open" + ); + session.initiate_delete(); + assert!( + !session.is_open(), + "after initiate_delete the session must report not-open" + ); + } +} diff --git a/tests/c/session_smoke.c b/tests/c/session_smoke.c index e1f0b588..b96dfdef 100644 --- a/tests/c/session_smoke.c +++ b/tests/c/session_smoke.c @@ -167,6 +167,53 @@ static void test_proxy_and_tls_setters(void) { kernel_session_config_free(config); } +/* U2M + custom-header setters accept valid input; header requires args. */ +static void test_u2m_and_header_setters(void) { + KernelSessionConfig* config = NULL; + (void)kernel_session_config_new(&config); + + /* All U2M args optional — NULL client_id / 0 port / NULL scopes → kernel + * defaults. This only populates the config; it does not open a session, + * so no browser is launched. */ + KernelStatusCode rc = kernel_session_config_set_auth_u2m(config, NULL, 0, NULL); + CHECK(rc == KernelStatusCode_Success, "set_auth_u2m (all defaults) succeeds"); + rc = kernel_session_config_set_auth_u2m(config, "my-client", 8020, "all-apis,offline_access"); + CHECK(rc == KernelStatusCode_Success, "set_auth_u2m (explicit) succeeds"); + + rc = kernel_session_config_set_custom_header(config, "X-Trace-Id", "abc123"); + CHECK(rc == KernelStatusCode_Success, "set_custom_header succeeds"); + rc = kernel_session_config_set_custom_header(config, NULL, "v"); + CHECK(rc == KernelStatusCode_InvalidArgument, "set_custom_header(NULL name) → InvalidArgument"); + rc = kernel_session_config_set_custom_header(config, "X-Foo", NULL); + CHECK(rc == KernelStatusCode_InvalidArgument, "set_custom_header(NULL value) → InvalidArgument"); + + kernel_session_config_free(config); +} + +/* kernel_init_logging is idempotent and null-tolerant. */ +static void test_init_logging(void) { + KernelStatusCode rc = kernel_init_logging("WARN", NULL); + CHECK(rc == KernelStatusCode_Success, "init_logging(level, NULL file) succeeds"); + /* Second call is a no-op (subscriber already installed) but still Success. */ + rc = kernel_init_logging(NULL, NULL); + CHECK(rc == KernelStatusCode_Success, "init_logging twice is safe"); +} + +/* is_open null-guards its args. (The true→false behavior is covered by the + * in-crate Rust test + * `session::is_open_tests::is_open_flips_true_to_false_on_delete`, which can + * reach the pub(crate) Session::is_open / initiate_delete the C ABI can't + * observe after close.) */ +static void test_is_open_null_guards(void) { + bool open = true; + KernelStatusCode rc = kernel_session_is_open(NULL, &open); + CHECK(rc == KernelStatusCode_InvalidArgument, "is_open(NULL session) → InvalidArgument"); + /* A non-null-but-bogus session pointer is UB per the contract, so we only + * exercise the null-out guard against a null session (checked first). */ + rc = kernel_session_is_open(NULL, NULL); + CHECK(rc == KernelStatusCode_InvalidArgument, "is_open(NULL, NULL) → InvalidArgument"); +} + /* The async submit path is a deferred stub → InvalidArgument, no network. */ static void test_submit_stub_rejects(void) { kernel_executed_async_statement_t* out = NULL; @@ -193,6 +240,9 @@ int main(void) { test_http_path_and_m2m_setters(); test_setter_null_arg_rejected(); test_proxy_and_tls_setters(); + test_u2m_and_header_setters(); + test_init_logging(); + test_is_open_null_guards(); test_submit_stub_rejects(); test_bind_null_handle_rejected(); diff --git a/tests/v0_c_abi_session_close_wiremock.rs b/tests/v0_c_abi_session_close_wiremock.rs index 8559d8cf..a06ab437 100644 --- a/tests/v0_c_abi_session_close_wiremock.rs +++ b/tests/v0_c_abi_session_close_wiremock.rs @@ -31,8 +31,8 @@ use std::time::Duration; use databricks_sql_kernel::c_abi::session::{ kernel_session_close, kernel_session_config_new, kernel_session_config_set_auth_pat, - kernel_session_config_set_http_path, kernel_session_new_statement, kernel_session_open, - kernel_session_t, KernelSessionConfig, + kernel_session_config_set_http_path, kernel_session_is_open, kernel_session_new_statement, + kernel_session_open, kernel_session_t, KernelSessionConfig, }; use databricks_sql_kernel::c_abi::statement::{kernel_statement_close, kernel_statement_t}; use databricks_sql_kernel::c_abi::KernelStatusCode; @@ -90,6 +90,18 @@ fn session_close_initiates_delete_with_statement_still_open() { ); assert!(!session.is_null()); + // A freshly-opened session reports open (guards against an inverted + // or hardcoded-false is_open). The false case can't be probed over + // the C ABI — kernel_session_close frees the handle in the same + // call — so it's covered by the crate-internal + // `session::is_open_tests::is_open_flips_true_to_false_on_delete`. + let mut is_open = false; + assert_eq!( + kernel_session_is_open(session, &mut is_open), + KernelStatusCode::Success + ); + assert!(is_open, "a freshly-opened session must report open"); + // Mint a statement — it holds an Arc clone, so the // session's inner won't drop when we close the session below. let mut stmt: *mut kernel_statement_t = std::ptr::null_mut();