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