Skip to content

feat(napi): expose mTLS client identity and custom HTTP headers - #127

Merged
msrathore-db merged 1 commit into
mainfrom
msrathore/krn-napi-mtls-headers
Jun 6, 2026
Merged

msrathore-db merged 1 commit into
mainfrom
msrathore/krn-napi-mtls-headers

Conversation

@msrathore-db

@msrathore-db msrathore-db commented Jun 5, 2026 •

Copy link
Copy Markdown
Collaborator

What

Extends the napi ConnectionOptions to surface the TLS- and HTTP-adjacent knobs the kernel core supports but the napi binding did not expose:

  • clientCertPem / clientKeyPem — mutual-TLS client identity → TlsConfig::client_cert_pem / client_key_pem. Bytes thread through verbatim; the kernel enforces both-or-neither and validates at Session::open (InvalidArgument).
  • customHeaders — an ordered Array<HeaderEntry> ({ name, value }) → HttpConfig::custom_headers, mirroring the kernel core's Vec<(String,String)> and the pyo3 binding's http_headers (order + duplicate names preserved; a struct is used because napi-rs can't marshal raw tuples). Reserved-name skip (Authorization / x-databricks-org-id) and last-User-Agent-appended-to-base-UA behaviour are unchanged.
  • checkServerCertificateHostname — independent hostname-vs-SNI toggle (TlsConfig::skip_hostname_verification) for full parity with the pyo3 tls_skip_hostname_verify / Python tls_verify_hostname. The master checkServerCertificate=false still subsumes it.

HTTP-config construction extracted into a testable build_http_config, mirroring build_tls_config.

Why

Unblocks the NodeJS SEA driver's mTLS / custom-headers / user-agent / hostname-verify support with the same shape and semantics as the Python connector's use_kernel path. checkServerCertificate + customCaCert were already exposed.

Testing

cargo test -p databricks-sql-kernel-napi — 18 database unit tests (mTLS pass-through incl. partial-set, ordered/duplicate header pass-through, independent + subsumed hostname toggle, pool defaults). cargo clippy --all-targets -D warnings clean. index.d.ts regenerated via @napi-rs/cli; the rebuilt .node was exercised from the NodeJS driver (FFI smoke test) to confirm every new field marshals and a wrong header shape is rejected.

This pull request and its description were written by Isaac.

Comment thread napi/src/database.rs Outdated
/// Always sets `pool_max_idle_per_host` — to the JS-supplied
/// `max_connections` when present, otherwise the NodeJS-driver-appropriate
/// [`NAPI_DEFAULT_POOL_MAX_IDLE_PER_HOST`] (100), which is larger than the
/// kernel core's conservative default (10). `custom_headers` is forwarded

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[code-review-squad · low / doc-accuracy] Stale pool-default docstring: the kernel default is 100, not 10.

This docstring — and two other sites in this file: the NAPI_DEFAULT_POOL_MAX_IDLE_PER_HOST constant doc (~line 49) and the max_connections field doc (~lines 162–163) — state the kernel core's HttpConfig::pool_max_idle_per_host default is "the conservative kernel value (10)". As of this PR's head, the kernel default is actually 100 (src/config.rs:458; the kernel's own field doc at config.rs:393 reads "Defaults to 100, matching the JDBC driver's HttpConnectionPoolSize").

Behavior is unaffected — build_http_config always sets the field explicitly — but the "larger than the kernel core's conservative default (10)" / "closes the throughput gap" rationale no longer holds (napi's 100 now equals the kernel's 100). Suggest correcting all three sites to "100 (matches the kernel/JDBC default)", or reframing the constant as pinning napi's default against future kernel drift.

Flagged independently by 4 of 6 reviewers (security, test, devil's-advocate, architecture) and verified against src/config.rs at head 7f8353f.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b5e26f3. Valid — verified real: kernel HttpConfig::pool_max_idle_per_host default is 100 (src/config.rs:458), not 10. Corrected all three sites; the constant doc now frames NAPI_DEFAULT_POOL_MAX_IDLE_PER_HOST as pinning napi's default against future kernel drift (it equals the kernel/JDBC 100 today). Behavior unchanged (build_http_config always sets it explicitly).

Comment thread napi/src/database.rs Outdated
/// kernel core's conservative default (10). `custom_headers` is forwarded
/// when supplied; the kernel handles the reserved/`User-Agent` special
/// cases. `HttpConfig` is `#[non_exhaustive]` — construct via `default()`
/// then mutate. Consumes the `custom_headers` map out of `options` (pure

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[code-review-squad · low / cosmetic] custom_headers is a Vec, not a "map".

This docstring ("Consumes the custom_headers map out of options"), the inline comment at ~line 357 ("no map flattening that would drop either"), and the comment at ~line 395 ("moves the custom_headers map out of options") all call custom_headers a "map" — but its type is Option<Vec<HeaderEntry>>. The intent (a HashMap would have collapsed duplicate names) is correct; only the noun is wrong. The sibling test comment at ~line 769 already phrases it correctly. Suggest "list" / "(a HashMap would have collapsed duplicates)".

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b5e26f3. Valid (cosmetic) — custom_headers is Option<Vec<HeaderEntry>>. Reworded the three sites from "map" to "list" and kept the rationale ("a HashMap would have collapsed duplicate names").

Comment thread napi/src/database.rs
let http = build_http_config(&mut o);
assert_eq!(
http.pool_max_idle_per_host,
NAPI_DEFAULT_POOL_MAX_IDLE_PER_HOST

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[code-review-squad · low / test-quality] This assertion isn't discriminating — it can't catch a regression.

http_defaults_pool_and_no_headers asserts the result equals NAPI_DEFAULT_POOL_MAX_IDLE_PER_HOST (100) when max_connections is unset. But the kernel's HttpConfig::default() is also 100 (src/config.rs:458), so this test passes whether or not build_http_config ever sets pool_max_idle_per_host — deleting the override line would not fail it, which defeats the point of pinning a napi-specific default. Consider asserting the constant's value directly, or guarding that the result is the napi constant and not silently inherited from the kernel default. (http_max_connections_overrides_pool with =7 does discriminate and is fine.)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b5e26f3. Valid — since the kernel HttpConfig::default() is also 100, the assertion couldn't catch deletion of the override line. Added assert_eq!(NAPI_DEFAULT_POOL_MAX_IDLE_PER_HOST, 100) to pin the constant, and a comment noting the discriminating test for the override is http_max_connections_overrides_pool (which sets a value the kernel default is not).

@msrathore-db

Copy link
Copy Markdown
Collaborator Author

F3 · [code-review-squad · low / coverage — optional] No explicit test for the strict-master + hostname-off combination.

The headline new capability — check_server_certificate=Some(true) + check_server_certificate_hostname=Some(false) (chain validated, hostname skipped) — isn't asserted with both flags explicit. It's marginal: tls_hostname_check_can_be_disabled_independently already covers it with the master flag left at its None→true default, which is behaviorally identical. A one-line test with the explicit Some(true)/Some(false) pair (optionally combined with a custom CA — the realistic "IP behind a corporate CA" case) would close the security-sensitive matrix cell. Optional. (devil's-advocate, test)

Add to the napi `ConnectionOptions`, wiring onto the kernel `TlsConfig` /
`HttpConfig`:

- `clientCertPem` / `clientKeyPem` (mutual-TLS client identity →
  `TlsConfig::client_cert_pem` / `client_key_pem`). Bytes thread through
  verbatim; the kernel enforces the both-or-neither pairing rule and
  validates the PEM/key at `Session::open` (`InvalidArgument`).
- `customHeaders` — an ordered `Vec<HeaderEntry>` (`{ name, value }`),
  mirroring the kernel core's `Vec<(String, String)>` and the pyo3
  binding's `http_headers`: order and duplicate names preserved (a struct
  is used because napi-rs can't marshal raw Rust tuples). The kernel keeps
  its reserved-name skip (`Authorization` / `x-databricks-org-id`) and
  appends the last `User-Agent` to its base UA.
- `checkServerCertificateHostname` — independent hostname-vs-SNI toggle
  for full parity with the Python connector's `tls_verify_hostname`
  (kernel `skip_hostname_verification`). The master
  `checkServerCertificate=false` still subsumes it (disables everything).

HTTP-config construction is extracted into a testable `build_http_config`
(pool sizing + headers), mirroring `build_tls_config`. Adds unit coverage
for mTLS pass-through (incl. partial-set), ordered/duplicate header
pass-through, the independent hostname toggle, and pool defaults.

Co-authored-by: Isaac
Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
@msrathore-db
msrathore-db force-pushed the msrathore/krn-napi-mtls-headers branch from 7f8353f to b5e26f3 Compare June 5, 2026 09:48
@msrathore-db

Copy link
Copy Markdown
Collaborator Author

F3 addressed in b5e26f3: added tls_strict_master_explicit_with_hostname_off_and_custom_ca — asserts check_server_certificate=Some(true) + check_server_certificate_hostname=Some(false) + a custom CA → chain validated, hostname skipped, CA threaded through (the "IP behind a corporate CA" cell).

Validated end-to-end with real credentials (e2-dogfood staging warehouse): openSession with customHeaders + checkServerCertificateHostname:false connected successfully and SELECT 1 → 1. mTLS itself can't be exercised here (no mTLS-configured server), but the napi marshaling of clientCertPem/clientKeyPem is covered by the binding FFI smoke test.

@msrathore-db
msrathore-db added this pull request to the merge queue Jun 6, 2026
Merged via the queue into main with commit 80b68e1 Jun 6, 2026
14 checks passed
gopalldb added a commit that referenced this pull request Jun 8, 2026
PR #146 review feedback (logical_claude_agent, critical/3-of-3): the
committed loader was stale. `napi/index.js` line 313 destructured only
8 symbols `{ AsyncStatement, AsyncResultHandle, CancellableExecution,
Connection, AuthMode, openSession, Statement, version }` but the
current Rust `#[napi]` surface defines 11. Three exports were missing:
- `initKernelLogging` (`napi/src/logger.rs:352`)
- `kernelLoggingStats` (`napi/src/logger.rs:428`)
- `setKernelLogLevel` (`napi/src/logger.rs:440`)

Result before this fix:
`require('@databricks/databricks-sql-kernel').initKernelLogging`
returned `undefined` even though the function existed in the compiled
.node binary. Same for `kernelLoggingStats` and `setKernelLogLevel`.
Defeated the PR's stated purpose of making the umbrella usable.

`napi/index.d.ts` was equally stale — missing the function
declarations plus the `LogRecord` and `KernelLoggingStats` interface
types they reference, plus `HeaderEntry` (introduced by the mTLS
work in PR #127). Downstream TypeScript callers would have hit
compile errors trying to use the logger API.

Regenerated both files from the current `#[napi]` surface using
`@napi-rs/cli@2.18.4`, the CLI version that emits the multi-platform
loader. Build command (from the napi/ directory):
  npx --yes @napi-rs/cli@2.18.4 build --platform \
      --js-package-name @databricks/databricks-sql-kernel --release

Verified post-regeneration:
- `index.js` destructures all 11 `#[napi]` symbols and re-exports
  each via `module.exports.<name> = <name>`.
- `index.d.ts` declares all 3 logger functions, the 5 object types
  they reference (LogRecord, KernelLoggingStats, HeaderEntry,
  ExecuteOptions, NamedTypedValueInput), and all 5 classes
  (AsyncStatement, AsyncResultHandle, CancellableExecution,
  Connection, Statement).

Also added `node_modules/` to `napi/.gitignore` — `npm exec @napi-rs/cli`
creates a transient node_modules tree that should not be committed.
The existing committed-loader note now points back to the same regen
incantation used here.

Co-authored-by: Isaac
Signed-off-by: Gopal Lal <gopal.lal@databricks.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants