1use nautilus_common::{
19 config::{ConfigError, ConfigResult, check_unique_values},
20 live::dst::time::{Duration, Instant},
21};
22use nautilus_core::string::secret::SecretString;
23use nautilus_live::book::DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS;
24use nautilus_model::identifiers::{AccountId, InstrumentId};
25use nautilus_network::websocket::TransportBackend;
26use serde::{Deserialize, Serialize};
27use url::Url;
28
29use crate::common::{
30 credential::validate_credentials,
31 enums::KalshiEnvironment,
32 parse::parse_ticker,
33 urls::{kalshi_http_base_url, kalshi_ws_url},
34};
35
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, bon::Builder)]
38#[serde(default, deny_unknown_fields)]
39#[cfg_attr(
40 feature = "python",
41 pyo3::pyclass(module = "nautilus_trader._libnautilus.kalshi", from_py_object)
42)]
43#[cfg_attr(
44 feature = "python",
45 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.kalshi")
46)]
47pub struct KalshiDataClientConfig {
48 pub api_key_id: Option<SecretString>,
50 pub private_key: Option<SecretString>,
52 #[builder(default)]
54 pub environment: KalshiEnvironment,
55 pub base_url_http: Option<SecretString>,
57 pub base_url_ws: Option<SecretString>,
59 pub proxy_url: Option<SecretString>,
61 #[builder(default = 60)]
63 pub http_timeout_secs: u64,
64 #[builder(default = 30)]
66 pub ws_timeout_secs: u64,
67 #[builder(default = DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS)]
69 pub book_snapshot_timeout_secs: u64,
70 #[builder(default = 60)]
72 pub update_instruments_interval_mins: u64,
73 #[builder(default = TransportBackend::Sockudo)]
75 pub transport_backend: TransportBackend,
76 #[builder(default)]
79 pub instrument_ids: Vec<InstrumentId>,
80}
81
82#[cfg(feature = "python")]
83nautilus_core::impl_pyo3_config_getters!(KalshiDataClientConfig {
84 environment: KalshiEnvironment,
85 http_timeout_secs: u64,
86 ws_timeout_secs: u64,
87 update_instruments_interval_mins: u64,
88 book_snapshot_timeout_secs: u64,
89 transport_backend: TransportBackend,
90 instrument_ids: Vec<InstrumentId>,
91});
92
93impl Default for KalshiDataClientConfig {
94 fn default() -> Self {
95 Self::builder().build()
96 }
97}
98
99impl KalshiDataClientConfig {
100 #[must_use]
102 pub fn new() -> Self {
103 Self::default()
104 }
105
106 #[must_use]
108 pub fn has_credentials(&self) -> bool {
109 self.api_key_id
110 .as_ref()
111 .is_some_and(|s| !s.expose_secret().trim().is_empty())
112 && self
113 .private_key
114 .as_ref()
115 .is_some_and(|s| !s.expose_secret().trim().is_empty())
116 }
117
118 #[must_use]
120 pub fn http_url(&self) -> &str {
121 self.base_url_http.as_ref().map_or_else(
122 || kalshi_http_base_url(self.environment),
123 SecretString::expose_secret,
124 )
125 }
126
127 #[must_use]
129 pub fn ws_url(&self) -> &str {
130 self.base_url_ws.as_ref().map_or_else(
131 || kalshi_ws_url(self.environment),
132 SecretString::expose_secret,
133 )
134 }
135
136 pub fn validate(&self) -> ConfigResult<()> {
146 validate_credentials(self.api_key_id.as_ref(), self.private_key.as_ref())?;
147 validate_transport(
148 self.environment,
149 self.http_url(),
150 self.ws_url(),
151 self.proxy_url.as_ref(),
152 self.http_timeout_secs,
153 self.ws_timeout_secs,
154 self.transport_backend,
155 )?;
156
157 if Instant::now()
158 .checked_add(Duration::from_secs(self.book_snapshot_timeout_secs))
159 .is_none()
160 {
161 return Err(ConfigError::invalid_value(
162 "book_snapshot_timeout_secs",
163 "exceeds the supported clock range",
164 ));
165 }
166
167 validate_positive(
168 "update_instruments_interval_mins",
169 self.update_instruments_interval_mins,
170 )?;
171 validate_instrument_ids(&self.instrument_ids)?;
172
173 if self
174 .update_instruments_interval_mins
175 .checked_mul(60)
176 .is_none()
177 {
178 return Err(ConfigError::invalid_value(
179 "update_instruments_interval_mins",
180 "seconds overflow",
181 ));
182 }
183
184 Ok(())
185 }
186}
187
188#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, bon::Builder)]
190#[serde(default, deny_unknown_fields)]
191#[cfg_attr(
192 feature = "python",
193 pyo3::pyclass(module = "nautilus_trader._libnautilus.kalshi", from_py_object)
194)]
195#[cfg_attr(
196 feature = "python",
197 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.kalshi")
198)]
199pub struct KalshiExecutionClientConfig {
200 #[builder(default = AccountId::from("KALSHI-001"))]
202 pub account_id: AccountId,
203 pub api_key_id: Option<SecretString>,
205 pub private_key: Option<SecretString>,
207 #[builder(default)]
209 pub environment: KalshiEnvironment,
210 pub base_url_http: Option<SecretString>,
212 pub base_url_ws: Option<SecretString>,
214 pub proxy_url: Option<SecretString>,
216 #[builder(default = 60)]
218 pub http_timeout_secs: u64,
219 #[builder(default = 30)]
221 pub ws_timeout_secs: u64,
222 #[builder(default)]
224 pub exchange_index: u32,
225 #[builder(default = TransportBackend::Sockudo)]
227 pub transport_backend: TransportBackend,
228}
229
230#[cfg(feature = "python")]
231nautilus_core::impl_pyo3_config_getters!(KalshiExecutionClientConfig {
232 account_id: AccountId,
233 environment: KalshiEnvironment,
234 http_timeout_secs: u64,
235 ws_timeout_secs: u64,
236 exchange_index: u32,
237 transport_backend: TransportBackend,
238});
239
240impl Default for KalshiExecutionClientConfig {
241 fn default() -> Self {
242 Self::builder().build()
243 }
244}
245
246impl KalshiExecutionClientConfig {
247 #[must_use]
249 pub fn new() -> Self {
250 Self::default()
251 }
252
253 #[must_use]
255 pub fn has_credentials(&self) -> bool {
256 self.api_key_id
257 .as_ref()
258 .is_some_and(|s| !s.expose_secret().trim().is_empty())
259 && self
260 .private_key
261 .as_ref()
262 .is_some_and(|s| !s.expose_secret().trim().is_empty())
263 }
264
265 #[must_use]
267 pub fn http_url(&self) -> &str {
268 self.base_url_http.as_ref().map_or_else(
269 || kalshi_http_base_url(self.environment),
270 SecretString::expose_secret,
271 )
272 }
273
274 #[must_use]
276 pub fn ws_url(&self) -> &str {
277 self.base_url_ws.as_ref().map_or_else(
278 || kalshi_ws_url(self.environment),
279 SecretString::expose_secret,
280 )
281 }
282
283 pub fn validate(&self) -> ConfigResult<()> {
293 validate_credentials(self.api_key_id.as_ref(), self.private_key.as_ref())?;
294 validate_transport(
295 self.environment,
296 self.http_url(),
297 self.ws_url(),
298 self.proxy_url.as_ref(),
299 self.http_timeout_secs,
300 self.ws_timeout_secs,
301 self.transport_backend,
302 )?;
303
304 Ok(())
305 }
306}
307
308fn validate_transport(
309 environment: KalshiEnvironment,
310 http_url: &str,
311 ws_url: &str,
312 proxy_url: Option<&SecretString>,
313 http_timeout_secs: u64,
314 ws_timeout_secs: u64,
315 transport_backend: TransportBackend,
316) -> ConfigResult<()> {
317 if transport_backend != TransportBackend::Sockudo {
318 return Err(ConfigError::invalid_value(
319 "transport_backend",
320 "Kalshi requires the Sockudo WebSocket backend",
321 ));
322 }
323
324 validate_endpoint("base_url_http", http_url, &["http", "https"], environment)?;
325 validate_endpoint("base_url_ws", ws_url, &["ws", "wss"], environment)?;
326
327 if let Some(proxy) = proxy_url {
328 let url = Url::parse(proxy.expose_secret()).map_err(|_| {
329 ConfigError::invalid_value("proxy_url", "expected an HTTP/HTTPS proxy URL")
330 })?;
331
332 let is_valid = matches!(url.scheme(), "http" | "https") && url.host_str().is_some();
333 let serialization = String::from(url);
335 let _serialization = SecretString::from(serialization);
336
337 if !is_valid {
338 return Err(ConfigError::invalid_value(
339 "proxy_url",
340 "expected an HTTP/HTTPS proxy URL",
341 ));
342 }
343 }
344
345 validate_positive("http_timeout_secs", http_timeout_secs)?;
346
347 if Instant::now()
348 .checked_add(Duration::from_secs(http_timeout_secs))
349 .is_none()
350 {
351 return Err(ConfigError::invalid_value(
352 "http_timeout_secs",
353 "exceeds the supported clock range",
354 ));
355 }
356
357 validate_positive("ws_timeout_secs", ws_timeout_secs)?;
358
359 if ws_timeout_secs.checked_mul(1_000).is_none() {
360 return Err(ConfigError::invalid_value(
361 "ws_timeout_secs",
362 "milliseconds overflow",
363 ));
364 }
365
366 Ok(())
367}
368
369fn validate_endpoint(
370 field: &str,
371 value: &str,
372 schemes: &[&str],
373 environment: KalshiEnvironment,
374) -> ConfigResult<()> {
375 let url = Url::parse(value)
376 .map_err(|_| ConfigError::invalid_value(field, "expected an absolute transport URL"))?;
377
378 let is_invalid = !schemes.contains(&url.scheme())
379 || url.host_str().is_none()
380 || !url.username().is_empty()
381 || url.password().is_some()
382 || url.query().is_some()
383 || url.fragment().is_some();
384
385 let host = url.host_str().unwrap_or_default();
386
387 let venue_environment = match host.strip_suffix('.').unwrap_or(host) {
388 "external-api.kalshi.com" | "external-api-ws.kalshi.com" | "api.elections.kalshi.com" => {
389 Some(KalshiEnvironment::Production)
390 }
391 "external-api.demo.kalshi.co" | "external-api-ws.demo.kalshi.co" | "demo-api.kalshi.co" => {
392 Some(KalshiEnvironment::Demo)
393 }
394 _ => None,
395 };
396
397 let is_insecure_venue = venue_environment.is_some() && !matches!(url.scheme(), "https" | "wss");
398
399 let serialization = String::from(url);
401 let _serialization = SecretString::from(serialization);
402
403 if is_invalid {
404 return Err(ConfigError::invalid_value(
405 field,
406 "expected an absolute transport URL without user information, query, or fragment",
407 ));
408 }
409
410 if is_insecure_venue {
411 return Err(ConfigError::invalid_value(
412 field,
413 "known venue hosts require an encrypted transport",
414 ));
415 }
416
417 if venue_environment.is_some_and(|selected| selected != environment) {
418 return Err(ConfigError::invalid_value(
419 field,
420 "venue host does not match environment",
421 ));
422 }
423
424 Ok(())
425}
426
427fn validate_instrument_ids(ids: &[InstrumentId]) -> ConfigResult<()> {
428 check_unique_values("instrument_ids", ids)?;
429
430 for id in ids {
431 if let Err(e) = parse_ticker(*id) {
432 return Err(ConfigError::invalid_value("instrument_ids", e.to_string()));
433 }
434 }
435
436 Ok(())
437}
438
439fn validate_positive(field: &str, value: u64) -> ConfigResult<()> {
440 if value == 0 {
441 return Err(ConfigError::invalid_value(field, "must be positive"));
442 }
443
444 Ok(())
445}
446
447#[cfg(test)]
448mod tests {
449 use rstest::rstest;
450
451 use super::*;
452
453 #[rstest]
454 fn test_defaults_have_one_source() {
455 let data = KalshiDataClientConfig::default();
456 let execution = KalshiExecutionClientConfig::default();
457 assert_eq!(data, KalshiDataClientConfig::builder().build());
458 assert_eq!(data, KalshiDataClientConfig::new());
459 assert_eq!(data, toml::from_str("").unwrap());
460 assert_eq!(execution, KalshiExecutionClientConfig::builder().build());
461 assert_eq!(execution, KalshiExecutionClientConfig::new());
462 assert_eq!(execution, toml::from_str("").unwrap());
463 assert_eq!(
464 data,
465 KalshiDataClientConfig {
466 api_key_id: None,
467 private_key: None,
468 environment: KalshiEnvironment::Production,
469 base_url_http: None,
470 base_url_ws: None,
471 proxy_url: None,
472 http_timeout_secs: 60,
473 ws_timeout_secs: 30,
474 update_instruments_interval_mins: 60,
475 book_snapshot_timeout_secs: DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS,
476 transport_backend: TransportBackend::Sockudo,
477 instrument_ids: Vec::new(),
478 }
479 );
480 assert_eq!(
481 execution,
482 KalshiExecutionClientConfig {
483 account_id: AccountId::from("KALSHI-001"),
484 api_key_id: None,
485 private_key: None,
486 environment: KalshiEnvironment::Production,
487 base_url_http: None,
488 base_url_ws: None,
489 proxy_url: None,
490 http_timeout_secs: 60,
491 ws_timeout_secs: 30,
492 exchange_index: 0,
493 transport_backend: TransportBackend::Sockudo,
494 }
495 );
496 assert!(!data.has_credentials());
497 assert!(!execution.has_credentials());
498 assert_eq!(data.validate(), Ok(()));
499 assert_eq!(execution.validate(), Ok(()));
500 }
501
502 #[rstest]
503 fn test_instrument_ids_reject_duplicates_and_foreign_venues() {
504 let duplicate = KalshiDataClientConfig {
505 instrument_ids: vec![
506 InstrumentId::from("KXHIGHNY-26OCT31-T70.KALSHI"),
507 InstrumentId::from("KXHIGHNY-26OCT31-T70.KALSHI"),
508 ],
509 ..Default::default()
510 };
511
512 let foreign = KalshiDataClientConfig {
513 instrument_ids: vec![InstrumentId::from("BTC-USD.BINANCE")],
514 ..Default::default()
515 };
516
517 let selected = KalshiDataClientConfig {
518 instrument_ids: vec![InstrumentId::from("KXHIGHNY-26OCT31-T70.KALSHI")],
519 ..Default::default()
520 };
521
522 assert_eq!(
523 duplicate.validate(),
524 Err(ConfigError::duplicate("instrument_ids", None))
525 );
526 assert_eq!(
527 foreign.validate(),
528 Err(ConfigError::invalid_value(
529 "instrument_ids",
530 "instrument venue must be KALSHI",
531 ))
532 );
533 assert_eq!(selected.validate(), Ok(()));
534 assert_eq!(KalshiDataClientConfig::default().validate(), Ok(()));
535 }
536
537 #[rstest]
538 fn test_tungstenite_backend_is_rejected() {
539 let data = KalshiDataClientConfig {
540 transport_backend: TransportBackend::Tungstenite,
541 ..Default::default()
542 };
543
544 let execution = KalshiExecutionClientConfig {
545 transport_backend: TransportBackend::Tungstenite,
546 ..Default::default()
547 };
548
549 let expected = ConfigError::invalid_value(
550 "transport_backend",
551 "Kalshi requires the Sockudo WebSocket backend",
552 );
553
554 assert_eq!(data.validate(), Err(expected.clone()));
555 assert_eq!(execution.validate(), Err(expected));
556 }
557
558 #[rstest]
559 fn test_decode_all_fields_and_round_trip() {
560 let data: KalshiDataClientConfig =
561 serde_json::from_str(include_str!("../test_data/config_data.json")).unwrap();
562 let execution: KalshiExecutionClientConfig =
563 serde_json::from_str(include_str!("../test_data/config_execution.json")).unwrap();
564 let expected_data = KalshiDataClientConfig::builder()
565 .api_key_id(SecretString::from("data-key"))
566 .private_key(SecretString::from("data-private-key"))
567 .environment(KalshiEnvironment::Demo)
568 .base_url_http(SecretString::from("http://localhost:14001/custom-api"))
569 .base_url_ws(SecretString::from("ws://localhost:14002/custom-ws"))
570 .proxy_url(SecretString::from(
571 "http://proxy-user:data-password@localhost:14003",
572 ))
573 .http_timeout_secs(17)
574 .ws_timeout_secs(19)
575 .update_instruments_interval_mins(23)
576 .book_snapshot_timeout_secs(31)
577 .transport_backend(TransportBackend::Sockudo)
578 .instrument_ids(vec![InstrumentId::from("KXBTC15M-26OCT31-T100000.KALSHI")])
579 .build();
580 let expected_execution = KalshiExecutionClientConfig::builder()
581 .account_id(AccountId::from("KALSHI-TEST"))
582 .api_key_id(SecretString::from("execution-key"))
583 .private_key(SecretString::from("execution-private-key"))
584 .environment(KalshiEnvironment::Demo)
585 .base_url_http(SecretString::from("http://localhost:14001/custom-api"))
586 .base_url_ws(SecretString::from("ws://localhost:14002/custom-ws"))
587 .proxy_url(SecretString::from(
588 "http://proxy-user:execution-password@localhost:14003",
589 ))
590 .http_timeout_secs(17)
591 .ws_timeout_secs(19)
592 .exchange_index(3)
593 .transport_backend(TransportBackend::Sockudo)
594 .build();
595 let round_trip_data: KalshiDataClientConfig =
596 serde_json::from_str(&serde_json::to_string(&data).unwrap()).unwrap();
597 let round_trip_execution: KalshiExecutionClientConfig =
598 serde_json::from_str(&serde_json::to_string(&execution).unwrap()).unwrap();
599 assert_eq!(data, expected_data);
600 assert_eq!(execution, expected_execution);
601 assert_eq!(data, round_trip_data);
602 assert_eq!(execution, round_trip_execution);
603 assert!(data.has_credentials());
604 assert!(execution.has_credentials());
605 assert_eq!(data.validate(), Ok(()));
606 assert_eq!(execution.validate(), Ok(()));
607 assert_eq!(data.http_url(), "http://localhost:14001/custom-api");
608 assert_eq!(data.ws_url(), "ws://localhost:14002/custom-ws");
609 assert_eq!(execution.http_url(), "http://localhost:14001/custom-api");
610 assert_eq!(execution.ws_url(), "ws://localhost:14002/custom-ws");
611 }
612
613 #[rstest]
614 #[case(
615 KalshiEnvironment::Production,
616 "https://external-api.kalshi.com/trade-api/v2",
617 "wss://external-api-ws.kalshi.com/trade-api/ws/v2"
618 )]
619 #[case(
620 KalshiEnvironment::Demo,
621 "https://external-api.demo.kalshi.co/trade-api/v2",
622 "wss://external-api-ws.demo.kalshi.co/trade-api/ws/v2"
623 )]
624 fn test_environment_endpoints(
625 #[case] environment: KalshiEnvironment,
626 #[case] http_url: &str,
627 #[case] ws_url: &str,
628 ) {
629 let data = KalshiDataClientConfig {
630 environment,
631 ..Default::default()
632 };
633
634 let execution = KalshiExecutionClientConfig {
635 environment,
636 ..Default::default()
637 };
638
639 assert_eq!(data.http_url(), http_url);
640 assert_eq!(data.ws_url(), ws_url);
641 assert_eq!(execution.http_url(), http_url);
642 assert_eq!(execution.ws_url(), ws_url);
643 }
644
645 #[rstest]
646 #[case("unknown_field = true")]
647 #[case("http_timeout_secs = -1")]
648 #[case("http_timeout_secs = 'slow'")]
649 #[case("environment = 'sandbox'")]
650 #[case("transport_backend = 'other'")]
651 #[case("trader_id = 'TRADER-001'")]
652 fn test_strict_decode(#[case] input: &str) {
653 assert!(toml::from_str::<KalshiDataClientConfig>(input).is_err());
654 assert!(toml::from_str::<KalshiExecutionClientConfig>(input).is_err());
655 }
656
657 #[rstest]
658 #[case("http_timeout_secs = 0", "http_timeout_secs")]
659 #[case("ws_timeout_secs = 0", "ws_timeout_secs")]
660 #[case("api_key_id = 'key'", "api_key_id")]
661 #[case("private_key = 'private'", "api_key_id")]
662 #[case(
663 "api_key_id = 'key with spaces'\nprivate_key = 'private'",
664 "api_key_id"
665 )]
666 #[case("api_key_id = 'key'\nprivate_key = ' '", "private_key")]
667 #[case("base_url_http = 'invalid-secret-url'", "base_url_http")]
668 #[case("base_url_http = 'wss://localhost/path'", "base_url_http")]
669 #[case("base_url_ws = 'https://localhost/path'", "base_url_ws")]
670 #[case(
671 "base_url_http = 'https://external-api.demo.kalshi.co/trade-api/v2'",
672 "base_url_http"
673 )]
674 #[case(
675 "environment = 'demo'\nbase_url_http = 'https://api.elections.kalshi.com/trade-api/v2'",
676 "base_url_http"
677 )]
678 #[case(
679 "environment = 'demo'\nbase_url_ws = 'wss://external-api-ws.kalshi.com/trade-api/ws/v2'",
680 "base_url_ws"
681 )]
682 #[case(
683 "base_url_ws = 'wss://demo-api.kalshi.co/trade-api/ws/v2'",
684 "base_url_ws"
685 )]
686 #[case("base_url_http = 'http://user:secret@localhost/path'", "base_url_http")]
687 #[case(
688 "base_url_http = 'http://localhost/path?token=secret'",
689 "base_url_http"
690 )]
691 #[case("base_url_ws = 'ws://localhost/path#secret'", "base_url_ws")]
692 #[case("proxy_url = 'socks5://localhost:1234'", "proxy_url")]
693 #[case(
694 "base_url_http = 'https://external-api.demo.kalshi.co./trade-api/v2'",
695 "base_url_http"
696 )]
697 #[case(
698 "environment = 'demo'\nbase_url_ws = 'wss://external-api-ws.kalshi.com./trade-api/ws/v2'",
699 "base_url_ws"
700 )]
701 #[case("proxy_url = 'secret-bad-proxy'", "proxy_url")]
702 fn test_invalid_values(#[case] input: &str, #[case] field: &str) {
703 let data: KalshiDataClientConfig = toml::from_str(input).unwrap();
704 let execution: KalshiExecutionClientConfig = toml::from_str(input).unwrap();
705 let data_error = data.validate().unwrap_err();
706 let execution_error = execution.validate().unwrap_err();
707
708 match &data_error {
709 ConfigError::InvalidValue { field: actual, .. }
710 | ConfigError::EmptyField { field: actual } => assert_eq!(actual, field),
711 other => panic!("unexpected config error {other:?}"),
712 }
713
714 assert_eq!(data_error, execution_error);
715
716 for output in [format!("{data_error:?}"), data_error.to_string()] {
717 for secret in [
718 "invalid-secret-url",
719 "user:secret",
720 "token=secret",
721 "secret-bad-proxy",
722 ] {
723 assert!(!output.contains(secret));
724 }
725 }
726 }
727
728 #[rstest]
729 #[case(KalshiEnvironment::Production, "external-api.kalshi.com")]
730 #[case(KalshiEnvironment::Production, "external-api-ws.kalshi.com")]
731 #[case(KalshiEnvironment::Production, "api.elections.kalshi.com")]
732 #[case(KalshiEnvironment::Demo, "external-api.demo.kalshi.co")]
733 #[case(KalshiEnvironment::Demo, "external-api-ws.demo.kalshi.co")]
734 #[case(KalshiEnvironment::Demo, "demo-api.kalshi.co")]
735 fn test_venue_endpoints_require_encryption(
736 #[case] environment: KalshiEnvironment,
737 #[case] host: &str,
738 ) {
739 for suffix in ["", "."] {
740 for (field, scheme, secure_scheme) in [
741 ("base_url_http", "http", "https"),
742 ("base_url_ws", "ws", "wss"),
743 ] {
744 let input = format!(
745 "environment = '{environment}'\n{field} = '{scheme}://{host}{suffix}/path'"
746 );
747 let data: KalshiDataClientConfig = toml::from_str(&input).unwrap();
748 let execution: KalshiExecutionClientConfig = toml::from_str(&input).unwrap();
749 let expected = ConfigError::invalid_value(
750 field,
751 "known venue hosts require an encrypted transport",
752 );
753 assert_eq!(data.validate(), Err(expected.clone()));
754 assert_eq!(execution.validate(), Err(expected));
755
756 let input = format!(
757 "environment = '{environment}'\n{field} = '{secure_scheme}://{host}{suffix}/path'"
758 );
759 let data: KalshiDataClientConfig = toml::from_str(&input).unwrap();
760 let execution: KalshiExecutionClientConfig = toml::from_str(&input).unwrap();
761 assert_eq!(data.validate(), Ok(()));
762 assert_eq!(execution.validate(), Ok(()));
763 }
764 }
765 }
766
767 #[rstest]
768 fn test_http_timeout_overflow() {
769 let data = KalshiDataClientConfig {
770 http_timeout_secs: u64::MAX,
771 ..Default::default()
772 };
773
774 let execution = KalshiExecutionClientConfig {
775 http_timeout_secs: u64::MAX,
776 ..Default::default()
777 };
778
779 let expected =
780 ConfigError::invalid_value("http_timeout_secs", "exceeds the supported clock range");
781 assert_eq!(data.validate(), Err(expected.clone()));
782 assert_eq!(execution.validate(), Err(expected));
783 }
784
785 #[rstest]
786 fn test_overflow_and_refresh_validation() {
787 let config = KalshiDataClientConfig {
788 ws_timeout_secs: u64::MAX,
789 ..Default::default()
790 };
791
792 assert_eq!(
793 config.validate(),
794 Err(ConfigError::invalid_value(
795 "ws_timeout_secs",
796 "milliseconds overflow"
797 ))
798 );
799
800 for interval in [0, u64::MAX] {
801 let config = KalshiDataClientConfig {
802 update_instruments_interval_mins: interval,
803 ..Default::default()
804 };
805
806 assert!(config.validate().is_err());
807 }
808 }
809
810 #[rstest]
811 #[case(None, None, false)]
812 #[case(Some("key"), None, false)]
813 #[case(None, Some("private"), false)]
814 #[case(Some(""), Some("private"), false)]
815 #[case(Some(" "), Some("private"), false)]
816 #[case(Some("key"), Some(" "), false)]
817 #[case(Some("key"), Some("private"), true)]
818 fn test_credential_presence(
819 #[case] api_key_id: Option<&str>,
820 #[case] private_key: Option<&str>,
821 #[case] expected: bool,
822 ) {
823 let data = KalshiDataClientConfig {
824 api_key_id: api_key_id.map(SecretString::from),
825 private_key: private_key.map(SecretString::from),
826 ..Default::default()
827 };
828
829 let execution = KalshiExecutionClientConfig {
830 api_key_id: data.api_key_id.clone(),
831 private_key: data.private_key.clone(),
832 ..Default::default()
833 };
834
835 assert_eq!(data.has_credentials(), expected);
836 assert_eq!(execution.has_credentials(), expected);
837 }
838
839 #[rstest]
840 fn test_debug_redacts_all_secret_owners() {
841 let data = KalshiDataClientConfig {
842 api_key_id: Some("distinct-key".into()),
843 private_key: Some("distinct-private".into()),
844 base_url_http: Some("http://secret-host/path".into()),
845 base_url_ws: Some("ws://secret-ws/path".into()),
846 proxy_url: Some("http://user:distinct-proxy@localhost".into()),
847 ..Default::default()
848 };
849
850 let execution = KalshiExecutionClientConfig {
851 account_id: AccountId::from("KALSHI-LOCAL"),
852 api_key_id: data.api_key_id.clone(),
853 private_key: data.private_key.clone(),
854 base_url_http: data.base_url_http.clone(),
855 base_url_ws: data.base_url_ws.clone(),
856 proxy_url: data.proxy_url.clone(),
857 ..Default::default()
858 };
859
860 for formatted in [format!("{data:?}"), format!("{execution:?}")] {
861 assert_eq!(formatted.matches("<redacted>").count(), 5);
862
863 for secret in [
864 "distinct-key",
865 "distinct-private",
866 "secret-host",
867 "secret-ws",
868 "distinct-proxy",
869 ] {
870 assert!(!formatted.contains(secret));
871 }
872 }
873 }
874
875 #[rstest]
876 #[case(0)]
877 #[case(1)]
878 #[case(31)]
879 fn book_snapshot_timeout_round_trips_and_accepts_zero(#[case] seconds: u64) {
880 let config: KalshiDataClientConfig =
881 serde_json::from_value(serde_json::json!({"book_snapshot_timeout_secs": seconds}))
882 .unwrap();
883 assert_eq!(config.book_snapshot_timeout_secs, seconds);
884 assert_eq!(config.validate(), Ok(()));
885 assert_eq!(
886 serde_json::to_value(&config).unwrap()["book_snapshot_timeout_secs"],
887 seconds
888 );
889 }
890
891 #[rstest]
892 fn book_snapshot_timeout_rejects_clock_overflow() {
893 let config = KalshiDataClientConfig::builder()
894 .book_snapshot_timeout_secs(u64::MAX)
895 .build();
896 assert_eq!(
897 config.validate(),
898 Err(ConfigError::invalid_value(
899 "book_snapshot_timeout_secs",
900 "exceeds the supported clock range"
901 ))
902 );
903 }
904}