canton_core/config.rs
1//! Shared client connection configuration (the Option-B connection kernel).
2//!
3//! Endpoint, authentication, TLS, and retry live here so every gRPC client in
4//! the SDK (`canton-ledger`, `canton-admin`) builds its channel the same way.
5//! Authentication is decoupled from any concrete provider via the
6//! [`TokenSource`] trait — `canton-auth`'s token provider implements it, which
7//! keeps `canton-core` free of a `canton-auth` dependency (that would be a
8//! cycle) while letting [`Config`] carry any token source.
9
10use std::fmt;
11use std::future::Future;
12use std::pin::Pin;
13use std::sync::Arc;
14use std::time::Duration;
15
16use tonic::transport::{Certificate, Channel, ClientTlsConfig, Endpoint, Identity};
17
18use crate::retry::RetryConfig;
19use crate::{Error, Result};
20
21/// A source of bearer tokens for request authentication.
22///
23/// Implemented by `canton_auth::TokenProvider` (OIDC client-credentials with
24/// caching + refresh). Object-safe by design: [`Auth::Dynamic`] stores it as an
25/// `Arc<dyn TokenSource>`.
26pub trait TokenSource: Send + Sync + fmt::Debug {
27 /// Resolve the current bearer token (fetching/refreshing as needed), or
28 /// `None` for an unauthenticated call.
29 fn fetch_bearer(&self) -> Pin<Box<dyn Future<Output = Result<Option<String>>> + Send + '_>>;
30}
31
32/// How the client authenticates each request.
33///
34/// `#[non_exhaustive]` so new auth modes can be added without a breaking change;
35/// construct via [`Config::with_token`] / [`Config::with_oidc`] (or match with a
36/// wildcard arm).
37#[derive(Clone)]
38#[non_exhaustive]
39pub enum Auth {
40 /// No authentication (unauthenticated endpoints, or shared-secret off).
41 None,
42 /// A fixed bearer token supplied by the caller.
43 Static(String),
44 /// A dynamic token source (e.g. OIDC client-credentials with auto-refresh).
45 Dynamic(Arc<dyn TokenSource>),
46}
47
48impl Auth {
49 /// Resolve the current bearer token, if any.
50 ///
51 /// # Errors
52 /// Propagates any error from the underlying [`TokenSource`].
53 pub async fn bearer(&self) -> Result<Option<String>> {
54 match self {
55 Auth::None => Ok(None),
56 Auth::Static(token) => Ok(Some(token.clone())),
57 Auth::Dynamic(source) => source.fetch_bearer().await,
58 }
59 }
60}
61
62impl fmt::Debug for Auth {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 match self {
65 Auth::None => f.write_str("None"),
66 Auth::Static(_) => f.write_str("Static(<redacted>)"),
67 Auth::Dynamic(source) => write!(f, "Dynamic({source:?})"),
68 }
69 }
70}
71
72/// TLS settings for the gRPC channel.
73///
74/// An empty `TlsConfig` (from [`TlsConfig::new`]) enables server-side TLS using
75/// the platform's native root certificates. Add a custom CA for private/self-
76/// signed servers, a domain-name override for SNI/verification, and a client
77/// identity for mutual TLS. `#[non_exhaustive]`.
78#[derive(Clone, Default)]
79#[non_exhaustive]
80pub struct TlsConfig {
81 /// Custom CA certificate chain (PEM). When set, replaces the native roots
82 /// (use for self-signed / private CAs).
83 pub ca_certificate_pem: Option<Vec<u8>>,
84 /// Domain name to verify the server certificate against (SNI). Defaults to
85 /// the endpoint host.
86 pub domain_name: Option<String>,
87 /// Client identity `(certificate_pem, private_key_pem)` for mutual TLS.
88 pub client_identity_pem: Option<(Vec<u8>, Vec<u8>)>,
89}
90
91/// Hand-written so PEM bytes never reach a log. The derived `Debug` printed
92/// `client_identity_pem` in full, which is the mutual-TLS **private key** — one
93/// `tracing` field capturing a `Config` was enough to put it in a log
94/// aggregator. Presence and length are what a reader debugging a handshake
95/// actually needs.
96impl std::fmt::Debug for TlsConfig {
97 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 fn pem(bytes: Option<&Vec<u8>>) -> String {
99 bytes.map_or_else(|| "None".to_string(), |b| format!("<{} bytes>", b.len()))
100 }
101 f.debug_struct("TlsConfig")
102 .field("ca_certificate_pem", &pem(self.ca_certificate_pem.as_ref()))
103 .field("domain_name", &self.domain_name)
104 .field(
105 "client_identity_pem",
106 &self.client_identity_pem.as_ref().map_or_else(
107 || "None".to_string(),
108 |(cert, key)| {
109 format!(
110 "Some((<{} bytes>, <{} bytes, redacted>))",
111 cert.len(),
112 key.len()
113 )
114 },
115 ),
116 )
117 .finish()
118 }
119}
120
121impl TlsConfig {
122 /// Server-side TLS using the platform's native root certificates.
123 #[must_use]
124 pub fn new() -> Self {
125 Self::default()
126 }
127
128 /// Trust this PEM CA certificate (chain) instead of the native roots.
129 #[must_use]
130 pub fn with_ca_certificate(mut self, ca_pem: impl Into<Vec<u8>>) -> Self {
131 self.ca_certificate_pem = Some(ca_pem.into());
132 self
133 }
134
135 /// Override the domain name the server certificate is verified against.
136 #[must_use]
137 pub fn with_domain_name(mut self, domain: impl Into<String>) -> Self {
138 self.domain_name = Some(domain.into());
139 self
140 }
141
142 /// Present a client identity (mutual TLS): `(certificate_pem, key_pem)`.
143 #[must_use]
144 pub fn with_client_identity(
145 mut self,
146 certificate_pem: impl Into<Vec<u8>>,
147 private_key_pem: impl Into<Vec<u8>>,
148 ) -> Self {
149 self.client_identity_pem = Some((certificate_pem.into(), private_key_pem.into()));
150 self
151 }
152}
153
154/// Build a `ClientTlsConfig` from a [`TlsConfig`] (or native roots when TLS is
155/// implicit for an `https` endpoint).
156fn build_tls(tls: Option<&TlsConfig>) -> ClientTlsConfig {
157 let mut config = ClientTlsConfig::new();
158 match tls.and_then(|t| t.ca_certificate_pem.as_ref()) {
159 Some(ca) => config = config.ca_certificate(Certificate::from_pem(ca.clone())),
160 None => config = config.with_native_roots(),
161 }
162 if let Some(domain) = tls.and_then(|t| t.domain_name.as_ref()) {
163 config = config.domain_name(domain.clone());
164 }
165 if let Some((cert, key)) = tls.and_then(|t| t.client_identity_pem.as_ref()) {
166 config = config.identity(Identity::from_pem(cert.clone(), key.clone()));
167 }
168 config
169}
170
171/// Replace the userinfo of a URL with `***`, so a connection string can be put
172/// in an error message or a log line without carrying credentials with it.
173///
174/// `https://alice:s3cret@host:3901/x` becomes `https://***@host:3901/x`; a URL
175/// without userinfo is returned untouched, and so is anything that does not
176/// parse as one. Deliberately not a real URL parse: this is used on the failure
177/// path of *invalid* URIs, where a parser would have nothing to work with.
178#[must_use]
179pub fn redact_url(url: &str) -> std::borrow::Cow<'_, str> {
180 let Some((scheme, rest)) = url.split_once("://") else {
181 return std::borrow::Cow::Borrowed(url);
182 };
183 // The authority ends at the first of these, or runs to the end.
184 let (authority, tail) = match rest.find(['/', '?', '#']) {
185 Some(end) => rest.split_at_checked(end).unwrap_or((rest, "")),
186 None => (rest, ""),
187 };
188 let Some((_userinfo, host)) = authority.rsplit_once('@') else {
189 return std::borrow::Cow::Borrowed(url);
190 };
191 std::borrow::Cow::Owned(format!("{scheme}://***@{host}{tail}"))
192}
193
194/// Configuration for an SDK gRPC client (shared by `canton-ledger` and
195/// `canton-admin`).
196#[derive(Clone)]
197pub struct Config {
198 endpoint: String,
199 auth: Auth,
200 retry: Option<RetryConfig>,
201 tls: Option<TlsConfig>,
202 timeout: Option<Duration>,
203 max_decoding_message_size: usize,
204}
205
206/// The largest gRPC response this SDK will decode, unless configured otherwise.
207///
208/// `tonic` defaults to 4 MiB, which a Ledger API client meets in ordinary use:
209/// one `GetActiveContractsPageResponse` carries a whole page, the participant
210/// permits page sizes up to 10 000, and a page of that size on a modest ledger
211/// is several times over the limit. It surfaces as a client-side
212/// `OUT_OF_RANGE` — "decoded message length too large" — which reads like a
213/// server fault and is not retriable, so the caller has nothing useful to do
214/// with it.
215///
216/// 128 MiB is a bound that a real page, transaction or created-event blob
217/// stays under while still refusing a response large enough to be a memory
218/// problem.
219pub const DEFAULT_MAX_DECODING_MESSAGE_SIZE: usize = 128 * 1024 * 1024;
220
221/// The most pages a paginated listing (`list_known_parties` on either
222/// transport) will follow before it is reported as not ending. At the
223/// participant's default page size that is far more parties than any
224/// participant hosts; a server that keeps minting page tokens is either
225/// broken or hostile, and either way the caller must not wait on it forever.
226pub const MAX_LIST_PAGES: usize = 10_000;
227
228/// Hand-written so the endpoint's userinfo is redacted. `auth` and `tls` redact
229/// themselves; the endpoint was the remaining way a credential reached a log
230/// through a `Config`, and a `Config` is exactly the thing an application
231/// attaches to a tracing span while debugging a connection.
232impl std::fmt::Debug for Config {
233 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
234 f.debug_struct("Config")
235 .field("endpoint", &redact_url(&self.endpoint))
236 .field("auth", &self.auth)
237 .field("retry", &self.retry)
238 .field("tls", &self.tls)
239 .field("timeout", &self.timeout)
240 .field("max_decoding_message_size", &self.max_decoding_message_size)
241 .finish()
242 }
243}
244
245impl Config {
246 /// Create a configuration targeting `endpoint`, with no authentication and
247 /// no retrying.
248 #[must_use]
249 pub fn new(endpoint: impl Into<String>) -> Self {
250 Self {
251 endpoint: endpoint.into(),
252 auth: Auth::None,
253 retry: None,
254 tls: None,
255 timeout: None,
256 max_decoding_message_size: DEFAULT_MAX_DECODING_MESSAGE_SIZE,
257 }
258 }
259
260 /// Authenticate with a fixed bearer token.
261 #[must_use]
262 pub fn with_token(mut self, token: impl Into<String>) -> Self {
263 self.auth = Auth::Static(token.into());
264 self
265 }
266
267 /// Authenticate with a dynamic token source (e.g. an OIDC provider with
268 /// client-credentials and auto-refresh).
269 #[must_use]
270 pub fn with_oidc<T: TokenSource + 'static>(mut self, provider: T) -> Self {
271 self.auth = Auth::Dynamic(Arc::new(provider));
272 self
273 }
274
275 /// Enable retrying of unary calls on retriable errors, per `retry`.
276 #[must_use]
277 pub fn with_retry(mut self, retry: RetryConfig) -> Self {
278 self.retry = Some(retry);
279 self
280 }
281
282 /// Use TLS for the gRPC channel (server-side and, if configured, mutual).
283 #[must_use]
284 pub fn with_tls(mut self, tls: TlsConfig) -> Self {
285 self.tls = Some(tls);
286 self
287 }
288
289 /// Set the per-request timeout on the gRPC channel (default 30s). Long
290 /// `submitAndWait` calls under load may need a higher bound.
291 #[must_use]
292 pub fn with_timeout(mut self, timeout: Duration) -> Self {
293 self.timeout = Some(timeout);
294 self
295 }
296
297 /// The largest gRPC response to decode, in bytes
298 /// (default [`DEFAULT_MAX_DECODING_MESSAGE_SIZE`], 128 MiB).
299 ///
300 /// Raise it for a participant that returns very large ACS pages or
301 /// transactions; lower it to bound the memory a single response can claim.
302 #[must_use]
303 pub fn with_max_decoding_message_size(mut self, bytes: usize) -> Self {
304 self.max_decoding_message_size = bytes;
305 self
306 }
307
308 /// The largest gRPC response this configuration will decode, in bytes.
309 #[must_use]
310 pub fn max_decoding_message_size(&self) -> usize {
311 self.max_decoding_message_size
312 }
313
314 /// The gRPC endpoint of the target service, e.g. `http://localhost:3901`.
315 #[must_use]
316 pub fn endpoint(&self) -> &str {
317 &self.endpoint
318 }
319
320 /// The configured authentication mode.
321 #[must_use]
322 pub fn auth(&self) -> &Auth {
323 &self.auth
324 }
325
326 /// The configured retry policy, if any.
327 #[must_use]
328 pub fn retry(&self) -> Option<&RetryConfig> {
329 self.retry.as_ref()
330 }
331
332 /// Build a lazily-connected gRPC [`Channel`] for this configuration.
333 ///
334 /// Returns immediately; the TCP/TLS handshake happens on the first RPC. TLS
335 /// is applied when [`Config::with_tls`] was set or the endpoint is `https`
336 /// or `grpcs`; a `with_tls` endpoint given as `http://` is normalised to
337 /// `https://` so TLS is never silently downgraded (see the private
338 /// `resolve_endpoint`).
339 ///
340 /// # Errors
341 /// Returns [`Error::InvalidRequest`] if the endpoint URI or the TLS
342 /// configuration is invalid, or TLS is configured and the endpoint's
343 /// scheme is one other than `http`, `https` or `grpcs`.
344 pub fn connect_channel(&self) -> Result<Channel> {
345 let (uri, want_tls) = resolve_endpoint(&self.endpoint, self.tls.is_some())?;
346 let mut endpoint = Endpoint::from_shared(uri.clone())
347 .map_err(|e| {
348 Error::InvalidRequest(format!("invalid endpoint uri {}: {e}", redact_url(&uri)))
349 })?
350 .timeout(self.timeout.unwrap_or(Duration::from_secs(30)))
351 .connect_timeout(Duration::from_secs(10))
352 .http2_keep_alive_interval(Duration::from_secs(30))
353 .keep_alive_timeout(Duration::from_secs(20))
354 .keep_alive_while_idle(true)
355 .tcp_keepalive(Some(Duration::from_secs(60)))
356 .tcp_nodelay(true);
357
358 if want_tls {
359 endpoint = endpoint
360 .tls_config(build_tls(self.tls.as_ref()))
361 .map_err(|e| {
362 Error::InvalidRequest(format!("invalid TLS config: {}", crate::chain(&e)))
363 })?;
364 }
365
366 Ok(endpoint.connect_lazy())
367 }
368}
369
370/// Resolve the effective endpoint URI and whether TLS should be attached.
371///
372/// `tonic` gates the TLS handshake on the URI **scheme**, not on the presence of
373/// a `tls_config` — so attaching TLS to an `http://` endpoint is silently ignored
374/// and the connection runs in plaintext (no encryption, no server-cert
375/// verification, no client cert). When TLS is configured — or the endpoint is
376/// already `https` — the scheme is normalised to `https` so TLS is actually
377/// applied. Scheme detection is case-insensitive (tonic lowercases the parsed
378/// scheme, so `HTTPS://…` must be treated as `https`).
379///
380/// `grpcs://` asks for TLS as `https://` does. Any other scheme cannot carry
381/// it: with TLS configured, `grpc://`, `dns://` or `ws://` went out as
382/// plaintext HTTP/2 with the bearer token, so it is refused.
383fn resolve_endpoint(endpoint: &str, tls_configured: bool) -> Result<(String, bool)> {
384 // A bare `host:port` is what a gRPC client dials, so it is what tooling
385 // hands out — canton-devkit's `CANTON_GRPC_LEDGER_API_URL` is exactly this
386 // shape. `Endpoint::from_shared` needs a scheme, and without one the
387 // failure arrives at connect time as an unexplained transport error, so
388 // supply the scheme the rest of this function would have chosen anyway.
389 // `unix:` is the exception: tonic reads it as a Unix socket, and turning
390 // it into `http://unix:/path` dialled TCP host `unix` instead. A socket
391 // cannot carry TLS (tonic refuses it), so with TLS it is refused here.
392 if endpoint.starts_with("unix:") {
393 if tls_configured {
394 return Err(Error::InvalidRequest(format!(
395 "TLS is configured, but {endpoint} is a Unix socket, which cannot carry it"
396 )));
397 }
398 return Ok((endpoint.to_string(), false));
399 }
400 let Some((scheme, rest)) = endpoint.split_once("://") else {
401 let scheme = if tls_configured { "https" } else { "http" };
402 return Ok((format!("{scheme}://{endpoint}"), tls_configured));
403 };
404
405 let is = |name: &str| scheme.eq_ignore_ascii_case(name);
406 let want_tls = tls_configured || is("https") || is("grpcs");
407 if !want_tls {
408 return Ok((endpoint.to_string(), false));
409 }
410 if is("http") || is("https") || is("grpcs") {
411 Ok((format!("https://{rest}"), true))
412 } else {
413 Err(Error::InvalidRequest(format!(
414 "TLS is configured, but the endpoint {} has a scheme that cannot carry it; \
415 use https://",
416 redact_url(endpoint)
417 )))
418 }
419}
420
421#[cfg(test)]
422mod decode_limit_tests {
423 use super::*;
424
425 #[test]
426 fn the_default_is_far_above_what_a_real_page_needs() {
427 // tonic's own default is 4 MiB. A `GetActiveContractsPageResponse`
428 // carries a whole page in one message and the participant allows page
429 // sizes up to 10 000, so the default is reachable in ordinary use —
430 // measured against a live 3.5.7 participant, 627 trivial contracts with
431 // created-event blobs already fill a quarter of it.
432 assert_eq!(DEFAULT_MAX_DECODING_MESSAGE_SIZE, 128 * 1024 * 1024);
433 const { assert!(DEFAULT_MAX_DECODING_MESSAGE_SIZE > 4 * 1024 * 1024) };
434 assert_eq!(
435 Config::new("http://localhost:3901").max_decoding_message_size(),
436 DEFAULT_MAX_DECODING_MESSAGE_SIZE
437 );
438 }
439
440 #[test]
441 fn the_limit_is_configurable_in_both_directions() {
442 // Raise it for a participant returning very large pages…
443 let big = Config::new("http://x").with_max_decoding_message_size(512 * 1024 * 1024);
444 assert_eq!(big.max_decoding_message_size(), 512 * 1024 * 1024);
445 // …or lower it to bound what one response can claim.
446 let small = Config::new("http://x").with_max_decoding_message_size(1024);
447 assert_eq!(small.max_decoding_message_size(), 1024);
448 }
449}
450
451#[cfg(test)]
452#[allow(clippy::unwrap_used, clippy::expect_used)]
453mod redaction_tests {
454 use super::*;
455
456 const KEY: &[u8] = b"-----BEGIN PRIVATE KEY-----SUPERSECRET-----END PRIVATE KEY-----";
457
458 /// The mutual-TLS private key must never reach a log. The derived `Debug`
459 /// printed it byte by byte, and a `Config` is exactly what an application
460 /// attaches to a span while debugging a handshake.
461 #[test]
462 fn debug_never_prints_key_material() {
463 let tls = TlsConfig::new().with_client_identity(b"certbytes".to_vec(), KEY.to_vec());
464 let rendered = format!("{tls:?}");
465
466 // 'S','U','P' as Debug-formatted bytes, which is how the leak looked.
467 assert!(
468 !rendered.contains("83, 85, 80"),
469 "key bytes leaked: {rendered}"
470 );
471 assert!(!rendered.contains("PRIVATE KEY"), "{rendered}");
472 // What a reader debugging a handshake actually needs is still there.
473 assert!(rendered.contains("redacted"), "{rendered}");
474 assert!(
475 rendered.contains(&format!("{} bytes", KEY.len())),
476 "{rendered}"
477 );
478
479 // And through a Config, which is the realistic path.
480 let cfg = Config::new("https://host:3901").with_tls(tls);
481 let rendered = format!("{cfg:?}");
482 assert!(
483 !rendered.contains("83, 85, 80"),
484 "leaked via Config: {rendered}"
485 );
486 }
487
488 #[test]
489 fn debug_redacts_credentials_in_the_endpoint() {
490 let cfg = Config::new("https://alice:s3cr3t@localhost:3901");
491 let rendered = format!("{cfg:?}");
492 assert!(!rendered.contains("s3cr3t"), "{rendered}");
493 assert!(!rendered.contains("alice"), "{rendered}");
494 assert!(
495 rendered.contains("localhost:3901"),
496 "host must survive: {rendered}"
497 );
498 }
499
500 #[test]
501 fn redact_url_keeps_everything_that_is_not_a_credential() {
502 // Redacted.
503 assert_eq!(redact_url("https://u:p@h:1/x?q=1"), "https://***@h:1/x?q=1");
504 assert_eq!(redact_url("ws://tok@h/v2/updates"), "ws://***@h/v2/updates");
505 // An '@' later in the path is not userinfo.
506 assert_eq!(redact_url("https://h/a@b"), "https://h/a@b");
507 // Untouched: no userinfo, no scheme, empty, and the malformed input
508 // this is most likely to meet — it runs on the *invalid*-URI path.
509 for url in [
510 "https://localhost:3901",
511 "http://kc:8082/realms/AppProvider/protocol/openid-connect/token",
512 "not a url at all",
513 "://",
514 "",
515 ] {
516 assert_eq!(redact_url(url), url, "should be untouched: {url}");
517 }
518 }
519}
520
521#[cfg(test)]
522#[allow(clippy::bool_assert_comparison, clippy::unwrap_used)]
523mod tests {
524 use super::resolve_endpoint;
525
526 #[test]
527 fn with_tls_on_http_endpoint_is_upgraded_to_https() {
528 // The security bug: `with_tls` on an http:// endpoint would otherwise
529 // connect in plaintext. It must become https so TLS is applied.
530 let (uri, tls) = resolve_endpoint("http://host:5001", true).unwrap();
531 assert_eq!(uri, "https://host:5001");
532 assert_eq!(tls, true);
533 }
534
535 #[test]
536 fn https_scheme_detection_is_case_insensitive() {
537 // `HTTPS://` (no explicit with_tls) must still get TLS — tonic sees the
538 // lowercased scheme and would otherwise error on an https URI with no TLS.
539 let (uri, tls) = resolve_endpoint("HTTPS://host:443", false).unwrap();
540 assert_eq!(uri, "https://host:443");
541 assert_eq!(tls, true);
542 }
543
544 #[test]
545 fn plain_http_without_tls_stays_plaintext() {
546 let (uri, tls) = resolve_endpoint("http://host:3901", false).unwrap();
547 assert_eq!(uri, "http://host:3901");
548 assert_eq!(tls, false);
549 }
550
551 #[test]
552 fn https_without_explicit_tls_wants_tls() {
553 let (uri, tls) = resolve_endpoint("https://host:443", false).unwrap();
554 assert_eq!(uri, "https://host:443");
555 assert_eq!(tls, true);
556 }
557
558 #[test]
559 fn uppercase_http_with_tls_is_upgraded() {
560 let (uri, tls) = resolve_endpoint("HTTP://host:5001", true).unwrap();
561 assert_eq!(uri, "https://host:5001");
562 assert_eq!(tls, true);
563 }
564
565 /// A bare `host:port` is what a gRPC client dials, so it is the form
566 /// tooling hands out — `canton-devkit localnet env` exports
567 /// `CANTON_GRPC_LEDGER_API_URL` exactly this way. `Endpoint::from_shared`
568 /// needs a scheme, and without one nothing complains until the first RPC
569 /// fails as an unexplained transport error.
570 #[test]
571 fn a_scheme_less_host_and_port_gets_the_scheme_it_implies() {
572 let (uri, tls) =
573 resolve_endpoint("grpc-ledger-api.app-provider.demo.localhost:3901", false).unwrap();
574 assert_eq!(
575 uri,
576 "http://grpc-ledger-api.app-provider.demo.localhost:3901"
577 );
578 assert_eq!(tls, false);
579
580 // With TLS configured it is the same choice the rest of this function
581 // makes: never plaintext when the caller asked for TLS.
582 let (uri, tls) = resolve_endpoint("ledger.example:443", true).unwrap();
583 assert_eq!(uri, "https://ledger.example:443");
584 assert_eq!(tls, true);
585
586 // An IPv6 literal has colons of its own and still is not a scheme.
587 let (uri, _) = resolve_endpoint("[::1]:3901", false).unwrap();
588 assert_eq!(uri, "http://[::1]:3901");
589 }
590
591 /// `grpcs://` asks for TLS as `https://` does.
592 #[test]
593 fn grpcs_is_tls() {
594 for tls_configured in [false, true] {
595 let (uri, tls) = resolve_endpoint("grpcs://host:443", tls_configured).unwrap();
596 assert_eq!(uri, "https://host:443");
597 assert_eq!(tls, true);
598 }
599 }
600
601 /// tonic picks TLS by the scheme, so with TLS configured any other scheme
602 /// sent plaintext HTTP/2 with the bearer token. It is refused instead.
603 #[test]
604 fn with_tls_a_scheme_that_cannot_carry_it_is_refused() {
605 for endpoint in [
606 "grpc://host:1",
607 "dns://host:1",
608 "ws://host:1",
609 "h2://host:1",
610 ] {
611 assert!(
612 matches!(
613 resolve_endpoint(endpoint, true),
614 Err(crate::Error::InvalidRequest(_))
615 ),
616 "{endpoint}"
617 );
618 // Without TLS the caller gets the plaintext they asked for.
619 assert_eq!(resolve_endpoint(endpoint, false).unwrap().1, false);
620 }
621 }
622
623 /// tonic reads `unix:` as a Unix socket. Given a scheme, it became TCP
624 /// host `unix`; it is now passed through, and refused with TLS.
625 #[test]
626 fn a_unix_socket_is_passed_through() {
627 for endpoint in ["unix:/var/run/canton.sock", "unix:relative.sock"] {
628 assert_eq!(
629 resolve_endpoint(endpoint, false).unwrap(),
630 (endpoint.to_string(), false)
631 );
632 assert!(
633 matches!(
634 resolve_endpoint(endpoint, true),
635 Err(crate::Error::InvalidRequest(_))
636 ),
637 "{endpoint}"
638 );
639 }
640 }
641}