Skip to content

Commit 2e626e2

Browse files
committed
krn-tls-public-api: expose TlsConfig fields + stop discarding in session.rs
The kernel has had working reqwest plumbing for custom CA certs, self-signed acceptance, and hostname-verification skip at client/http.rs since the original TLS migration. That implementation has been unreachable from any public wrapper because (a) the public TlsConfig struct in config.rs was empty and (b) session.rs explicitly discarded any caller-supplied TlsConfig and replaced with default. This commit: - Adds custom_ca_cert / accept_self_signed / skip_hostname_verification fields to public TlsConfig - Adds a trusted_certificate_pem field to the internal HttpTlsConfig so the public custom_ca_cert (Vec<u8>) can flow through without a tempfile shim — foreign-language wrappers (napi-rs Buffer / pyo3 bytes) get a direct path - Adds HttpTlsConfig::from_public / From<&public::TlsConfig> to project the public surface onto the internal layer - Wires session.rs::build_http_client_config to call HttpTlsConfig::from_public(&config.tls) instead of discarding - Adds a custom Debug impl on the public TlsConfig that summarises the cert bytes ("<N bytes>") instead of dumping the whole PEM into log lines - Adds builder-introspection tests that construct a DatabricksHttpClient via the public -> internal mapping with each flag in turn and verify the reqwest builder succeeds Public TlsConfig defaults remain strict: accept_self_signed=false, skip_hostname_verification=false, custom_ca_cert=None. The default projection produces an internal config with `None` everywhere on the permissive switches so RUST_LOG output stays free of no-op overrides. Unblocks NodeJS-side TLS Buffer->tempfile shim row (kernel now accepts Vec<u8> directly; no tempfile needed) and is a prereq for future mTLS work (client_cert / client_key remain unwired — that's a separate follow-up). The pre-existing lib-test failure in client::http::tests:: test_http_client_with_invalid_pem (D-016: reqwest::Certificate:: from_pem accepts garbage strings under the rustls-tls backend) is unrelated to this commit and reproduces on the krn-napi-binding base. Signed-off-by: Madhavendra Rathore <madhavendra.rathore@databricks.com>
1 parent f7bcc87 commit 2e626e2

3 files changed

Lines changed: 224 additions & 13 deletions

File tree

‎src/client/http.rs‎

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,42 @@ pub struct TlsConfig {
9393
pub allow_hostname_mismatch: Option<bool>,
9494
/// Path to a PEM-encoded CA certificate file to add to the trust store.
9595
pub trusted_certificate_path: Option<String>,
96+
/// PEM-encoded CA certificate bytes to add to the trust store.
97+
/// Alternative to `trusted_certificate_path` for callers that
98+
/// have the cert in-memory (e.g. foreign-language wrappers
99+
/// passing `Buffer` / `bytes` without a tempfile shim). When
100+
/// both are set, the path is read first, then the in-memory PEM
101+
/// is added as an additional root.
102+
pub trusted_certificate_pem: Option<Vec<u8>>,
103+
}
104+
105+
impl TlsConfig {
106+
/// Project the public [`crate::config::TlsConfig`] onto the internal
107+
/// HTTP-client TLS struct. Public fields land on their internal
108+
/// counterparts; internal-only fields (`enabled`,
109+
/// `trusted_certificate_path`) stay at their defaults.
110+
///
111+
/// `accept_self_signed` / `skip_hostname_verification` are booleans
112+
/// on the public surface (default: stricter); the internal layer
113+
/// uses `Option<bool>` so the existing `None == default` semantics
114+
/// are preserved. We map a `false` to `None` rather than
115+
/// `Some(false)` to keep `Debug` output / RUST_LOG noise free of
116+
/// no-op overrides.
117+
pub fn from_public(cfg: &crate::config::TlsConfig) -> Self {
118+
Self {
119+
enabled: None,
120+
allow_self_signed: cfg.accept_self_signed.then_some(true),
121+
allow_hostname_mismatch: cfg.skip_hostname_verification.then_some(true),
122+
trusted_certificate_path: None,
123+
trusted_certificate_pem: cfg.custom_ca_cert.clone(),
124+
}
125+
}
126+
}
127+
128+
impl From<&crate::config::TlsConfig> for TlsConfig {
129+
fn from(cfg: &crate::config::TlsConfig) -> Self {
130+
Self::from_public(cfg)
131+
}
96132
}
97133

98134
/// Configuration for the HTTP client.
@@ -213,6 +249,18 @@ impl DatabricksHttpClient {
213249
debug!("Added custom CA certificate from: {}", cert_path);
214250
}
215251

252+
if let Some(ref pem) = config.tls.trusted_certificate_pem {
253+
let cert = reqwest::Certificate::from_pem(pem).map_err(|e| {
254+
Error::invalid_argument()
255+
.message(format!("Invalid in-memory PEM certificate: {}", e))
256+
})?;
257+
builder = builder.add_root_certificate(cert);
258+
debug!(
259+
"Added custom CA certificate from in-memory bytes ({} bytes)",
260+
pem.len()
261+
);
262+
}
263+
216264
// Apply proxy configuration
217265
if let Some(ref proxy_url) = config.proxy.url {
218266
// Validate proxy URL scheme
@@ -811,6 +859,91 @@ lGrv15pBcePj
811859
assert!(err_msg.contains("Invalid PEM certificate"));
812860
}
813861

862+
#[test]
863+
fn test_http_client_with_in_memory_pem_bytes() {
864+
// Public-API path: PEM bytes pass through the internal
865+
// `trusted_certificate_pem` field directly (no tempfile shim
866+
// required by foreign-language wrappers).
867+
let mut config = HttpClientConfig::default();
868+
config.tls.trusted_certificate_pem = Some(TEST_CA_CERT_PEM.as_bytes().to_vec());
869+
let client = DatabricksHttpClient::new(config, default_retry_configs());
870+
assert!(client.is_ok());
871+
}
872+
873+
#[test]
874+
fn test_tls_config_from_public_maps_all_fields() {
875+
// accept_self_signed=true maps to Some(true);
876+
// skip_hostname_verification=true maps to Some(true);
877+
// custom_ca_cert maps to trusted_certificate_pem.
878+
let public = crate::config::TlsConfig {
879+
custom_ca_cert: Some(b"pem-bytes".to_vec()),
880+
accept_self_signed: true,
881+
skip_hostname_verification: true,
882+
};
883+
let internal = TlsConfig::from_public(&public);
884+
assert_eq!(internal.allow_self_signed, Some(true));
885+
assert_eq!(internal.allow_hostname_mismatch, Some(true));
886+
assert_eq!(
887+
internal.trusted_certificate_pem,
888+
Some(b"pem-bytes".to_vec())
889+
);
890+
// `enabled` and `trusted_certificate_path` stay at internal
891+
// defaults — the public surface doesn't expose them.
892+
assert!(internal.enabled.is_none());
893+
assert!(internal.trusted_certificate_path.is_none());
894+
}
895+
896+
#[test]
897+
fn test_tls_config_from_public_default_is_strict() {
898+
// A default public TlsConfig produces an internal config that
899+
// does NOT relax any default — `None` everywhere on the
900+
// permissive switches so log output stays clean.
901+
let internal = TlsConfig::from_public(&crate::config::TlsConfig::default());
902+
assert!(internal.allow_self_signed.is_none());
903+
assert!(internal.allow_hostname_mismatch.is_none());
904+
assert!(internal.trusted_certificate_pem.is_none());
905+
assert!(internal.trusted_certificate_path.is_none());
906+
}
907+
908+
#[test]
909+
fn test_http_client_via_public_tls_config_with_self_signed_accepts_build() {
910+
// End-to-end builder check: a Session-style construction
911+
// (public TlsConfig -> from_public -> HttpClientConfig ->
912+
// reqwest builder) succeeds when accept_self_signed is set.
913+
let public = crate::config::TlsConfig {
914+
custom_ca_cert: None,
915+
accept_self_signed: true,
916+
skip_hostname_verification: false,
917+
};
918+
let config = HttpClientConfig {
919+
tls: TlsConfig::from_public(&public),
920+
..HttpClientConfig::default()
921+
};
922+
let client = DatabricksHttpClient::new(config, default_retry_configs());
923+
assert!(
924+
client.is_ok(),
925+
"reqwest client construction should succeed when accept_self_signed=true is set"
926+
);
927+
}
928+
929+
#[test]
930+
fn test_http_client_via_public_tls_config_with_custom_ca_accepts_build() {
931+
let public = crate::config::TlsConfig {
932+
custom_ca_cert: Some(TEST_CA_CERT_PEM.as_bytes().to_vec()),
933+
accept_self_signed: false,
934+
skip_hostname_verification: false,
935+
};
936+
let config = HttpClientConfig {
937+
tls: TlsConfig::from_public(&public),
938+
..HttpClientConfig::default()
939+
};
940+
let client = DatabricksHttpClient::new(config, default_retry_configs());
941+
assert!(
942+
client.is_ok(),
943+
"reqwest client construction should succeed when custom_ca_cert is set with a valid PEM"
944+
);
945+
}
946+
814947
#[test]
815948
fn test_proxy_config_debug_redacts_password() {
816949
let config = ProxyConfig {

‎src/config.rs‎

Lines changed: 84 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -349,13 +349,64 @@ impl Default for HttpConfig {
349349
#[derive(Debug, Clone, Default)]
350350
pub struct ProxyConfig {}
351351

352-
// ─── TLS (reserved) ─────────────────────────────────────────────────────────
352+
// ─── TLS ────────────────────────────────────────────────────────────────────
353353

354-
/// Reserved for v0.1. Fields land once the TLS story (custom CA bundles,
355-
/// cert pinning, FIPS mode) is settled.
354+
/// TLS settings for the HTTP client.
355+
///
356+
/// All defaults match the most secure stance: validate the system trust
357+
/// store, require a valid certificate chain, and verify hostnames. Any
358+
/// non-default field is a *relaxation* — flip these for dev / on-prem
359+
/// boxes with self-signed certs, never against production.
360+
///
361+
/// The kernel exposes only fields that the internal rustls plumbing
362+
/// already supports — cert pinning and FIPS mode are *not* in scope.
356363
#[non_exhaustive]
357-
#[derive(Debug, Clone, Default)]
358-
pub struct TlsConfig {}
364+
#[derive(Clone, Default)]
365+
pub struct TlsConfig {
366+
/// PEM-encoded CA certificate bytes to add to the trust store on
367+
/// top of the system roots. Use this when connecting through a
368+
/// corporate proxy that re-signs TLS or to an on-prem Databricks
369+
/// deployment using an internal CA.
370+
///
371+
/// Carrying bytes (rather than a path) keeps the surface friendly
372+
/// for foreign-language wrappers — napi-rs / pyo3 callers pass a
373+
/// `Buffer` / `bytes` directly without needing to materialise a
374+
/// tempfile.
375+
pub custom_ca_cert: Option<Vec<u8>>,
376+
377+
/// Accept self-signed server certificates.
378+
///
379+
/// Note: the underlying reqwest backend does not distinguish
380+
/// "self-signed only" from "fully unvalidated" — setting this to
381+
/// `true` disables ALL chain validation (CA trust, expiration,
382+
/// etc.) via `danger_accept_invalid_certs(true)`. Use only in
383+
/// development.
384+
pub accept_self_signed: bool,
385+
386+
/// Skip the certificate-hostname-vs-SNI match check. Use only
387+
/// when connecting via an IP literal or a hostname the cert
388+
/// wasn't issued for in a development / lab environment.
389+
pub skip_hostname_verification: bool,
390+
}
391+
392+
impl std::fmt::Debug for TlsConfig {
393+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
394+
f.debug_struct("TlsConfig")
395+
.field(
396+
"custom_ca_cert",
397+
&self
398+
.custom_ca_cert
399+
.as_ref()
400+
.map(|b| format!("<{} bytes>", b.len())),
401+
)
402+
.field("accept_self_signed", &self.accept_self_signed)
403+
.field(
404+
"skip_hostname_verification",
405+
&self.skip_hostname_verification,
406+
)
407+
.finish()
408+
}
409+
}
359410

360411
// ─── Result management (CloudFetch + future result knobs) ───────────────────
361412

@@ -621,4 +672,32 @@ mod tests {
621672
// `sea-workflow/specs/07-errors-retries/connection-pool-default-mismatch.md`.
622673
assert_eq!(HttpConfig::default().pool_max_idle_per_host, 100);
623674
}
675+
676+
// ─── TlsConfig ─────────────────────────────────────────────────
677+
678+
#[test]
679+
fn tls_config_default_is_strict() {
680+
let tls = TlsConfig::default();
681+
assert!(tls.custom_ca_cert.is_none());
682+
assert!(!tls.accept_self_signed);
683+
assert!(!tls.skip_hostname_verification);
684+
}
685+
686+
#[test]
687+
fn tls_config_debug_redacts_ca_cert_bytes() {
688+
// The PEM bytes themselves aren't secret, but a multi-kB blob
689+
// in every log line is unhelpful — Debug should summarise.
690+
let tls = TlsConfig {
691+
custom_ca_cert: Some(b"-----BEGIN CERTIFICATE-----...".to_vec()),
692+
accept_self_signed: false,
693+
skip_hostname_verification: false,
694+
};
695+
let s = format!("{tls:?}");
696+
assert!(s.contains("<"), "expected byte-count summary, got: {s}");
697+
assert!(
698+
s.contains("bytes>"),
699+
"expected byte-count summary, got: {s}"
700+
);
701+
assert!(!s.contains("BEGIN CERTIFICATE"), "raw bytes leaked: {s}");
702+
}
624703
}

‎src/session.rs‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -517,11 +517,11 @@ impl SessionBuilder {
517517
/// Translate the public [`HttpConfig`] (+ proxy / TLS / org_id) into
518518
/// the internal [`HttpClientConfig`] the HTTP client expects.
519519
///
520-
/// v0's [`ProxyConfig`] and [`TlsConfig`] are empty `#[non_exhaustive]`
521-
/// reservation structs — they don't carry fields yet. We pass through
522-
/// the internal [`HttpProxyConfig::default`] / [`HttpTlsConfig::default`]
523-
/// for now; PR follow-ups will wire the real fields when the v0
524-
/// proxy/TLS shape lands.
520+
/// The public [`ProxyConfig`] is still a reserved `#[non_exhaustive]`
521+
/// struct (no fields wired yet); the public [`TlsConfig`] now carries
522+
/// `custom_ca_cert` / `accept_self_signed` /
523+
/// `skip_hostname_verification` and is projected onto the internal
524+
/// [`HttpTlsConfig`] via [`HttpTlsConfig::from_public`].
525525
fn build_http_client_config(config: &SessionConfig, org_id: Option<String>) -> HttpClientConfig {
526526
let mut hcc = HttpClientConfig {
527527
connect_timeout: Duration::from_secs(30),
@@ -530,15 +530,14 @@ fn build_http_client_config(config: &SessionConfig, org_id: Option<String>) -> H
530530
read_timeout: config.http.request_timeout,
531531
max_connections_per_host: config.http.pool_max_idle_per_host,
532532
proxy: HttpProxyConfig::default(),
533-
tls: HttpTlsConfig::default(),
533+
tls: HttpTlsConfig::from_public(&config.tls),
534534
org_id,
535535
..HttpClientConfig::default()
536536
};
537-
// Touch the v0 reserved configs so a future field addition
537+
// Touch the still-reserved proxy config so a future field addition
538538
// (without setting it through here) shows up as a compile error
539539
// rather than a silently-dropped option.
540540
let ProxyConfig { .. } = config.proxy.clone().unwrap_or_default();
541-
let TlsConfig { .. } = config.tls.clone();
542541
let _ = &mut hcc;
543542
hcc
544543
}

0 commit comments

Comments
 (0)