Skip to main content

nautilus_kalshi/common/
credential.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Atomic credential resolution and RSA-PSS or Ed25519 request authentication.
17//!
18//! Config validation checks explicit pairs without reading the environment. Authenticated clients
19//! resolve a complete pair and parse the private key before sending traffic.
20
21use std::fmt::Debug;
22
23use aws_lc_rs::{
24    rand::SystemRandom,
25    rsa::KeyPair,
26    signature::{Ed25519KeyPair, RSA_PSS_SHA256},
27};
28use base64::prelude::*;
29use nautilus_common::config::{ConfigError, ConfigResult};
30use nautilus_core::string::secret::SecretString;
31use zeroize::Zeroizing;
32
33use super::{
34    consts::{
35        KALSHI_ACCESS_KEY_HEADER, KALSHI_ACCESS_SIGNATURE_HEADER, KALSHI_ACCESS_TIMESTAMP_HEADER,
36    },
37    enums::KalshiEnvironment,
38};
39
40/// A validated API identity and parsed RSA or Ed25519 private key.
41///
42/// Explicit credentials take precedence as a complete pair. Environment fallback applies only
43/// when both explicit fields are absent. Diagnostics omit the identity and key material.
44pub struct KalshiCredential {
45    api_key_id: SecretString,
46    key: SigningKey,
47}
48
49impl KalshiCredential {
50    /// Resolves and validates one complete credential set for the selected environment.
51    ///
52    /// # Errors
53    ///
54    /// Returns an error if credentials are missing, empty, incomplete, or invalid, or the key
55    /// is not an unencrypted RSA or Ed25519 private key in PEM format.
56    pub fn resolve(
57        api_key_id: Option<SecretString>,
58        private_key: Option<SecretString>,
59        environment: KalshiEnvironment,
60    ) -> ConfigResult<Self> {
61        validate_credentials(api_key_id.as_ref(), private_key.as_ref())?;
62
63        let (api_key_id, private_key) = match api_key_id.zip(private_key) {
64            Some(pair) => pair,
65            None => {
66                let (key_var, private_var) = credential_env_vars(environment);
67
68                let key = std::env::var(key_var)
69                    .map(SecretString::from)
70                    .map_err(|_| {
71                        ConfigError::invalid_value(
72                            "api_key_id",
73                            "selected environment credentials are missing or invalid",
74                        )
75                    })?;
76
77                let private = std::env::var(private_var)
78                    .map(SecretString::from)
79                    .map_err(|_| {
80                        ConfigError::invalid_value(
81                            "private_key",
82                            "selected environment credentials are missing or invalid",
83                        )
84                    })?;
85
86                (key, private)
87            }
88        };
89
90        validate_credentials(Some(&api_key_id), Some(&private_key))?;
91        let key = decode_key(private_key.expose_secret())?;
92        Ok(Self { api_key_id, key })
93    }
94
95    /// Signs a full API path and returns the three access headers.
96    ///
97    /// `timestamp_ms` is Unix time in milliseconds. The method is converted to uppercase.
98    /// The path starts at `/`, for example `/trade-api/v2/portfolio/balance`; any query is excluded.
99    /// Hostnames are not accepted.
100    /// Header values retain zeroizing, redacted ownership until passed to the transport.
101    ///
102    /// # Errors
103    ///
104    /// Returns an error if the method or path is invalid, or signing fails.
105    pub fn headers(
106        &self,
107        timestamp_ms: u64,
108        method: &str,
109        path: &str,
110    ) -> ConfigResult<Vec<(String, SecretString)>> {
111        let method = method.to_ascii_uppercase();
112        if method.is_empty() || !method.bytes().all(|b| b.is_ascii_uppercase()) {
113            return Err(ConfigError::invalid_value(
114                "method",
115                "expected an HTTP method",
116            ));
117        }
118
119        let path = path.split('?').next().unwrap_or_default();
120        if !path.starts_with('/') || path.starts_with("//") || path.contains('#') {
121            return Err(ConfigError::invalid_value(
122                "path",
123                "expected a full API path",
124            ));
125        }
126
127        let timestamp = timestamp_ms.to_string();
128        let payload = Zeroizing::new(format!("{timestamp}{method}{path}"));
129
130        let signature = match &self.key {
131            SigningKey::Rsa(key) => {
132                let mut bytes = Zeroizing::new(vec![0; key.public_modulus_len()]);
133                key.sign(
134                    &RSA_PSS_SHA256,
135                    &SystemRandom::new(),
136                    payload.as_bytes(),
137                    &mut bytes,
138                )
139                .map_err(|_| ConfigError::invalid_value("signature", "RSA-PSS signing failed"))?;
140                BASE64_STANDARD.encode(bytes.as_slice())
141            }
142            SigningKey::Ed25519(key) => {
143                let bytes = key.try_sign(payload.as_bytes()).map_err(|_| {
144                    ConfigError::invalid_value("signature", "Ed25519 signing failed")
145                })?;
146
147                BASE64_STANDARD.encode(bytes.as_ref())
148            }
149        };
150
151        Ok(vec![
152            (KALSHI_ACCESS_KEY_HEADER.into(), self.api_key_id.clone()),
153            (KALSHI_ACCESS_TIMESTAMP_HEADER.into(), timestamp.into()),
154            (KALSHI_ACCESS_SIGNATURE_HEADER.into(), signature.into()),
155        ])
156    }
157}
158
159impl Debug for KalshiCredential {
160    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
161        f.debug_struct(stringify!(KalshiCredential))
162            .finish_non_exhaustive()
163    }
164}
165
166enum SigningKey {
167    Rsa(KeyPair),
168    Ed25519(Ed25519KeyPair),
169}
170
171fn decode_key(value: &str) -> ConfigResult<SigningKey> {
172    let invalid_key = || {
173        ConfigError::invalid_value(
174            "private_key",
175            "expected one unencrypted RSA or Ed25519 private key in PEM format",
176        )
177    };
178
179    let pem = value.trim();
180    let (tag, rest) = pem
181        .strip_prefix("-----BEGIN ")
182        .and_then(|s| s.split_once("-----"))
183        .ok_or_else(invalid_key)?;
184
185    if !matches!(tag, "PRIVATE KEY" | "RSA PRIVATE KEY") {
186        return Err(invalid_key());
187    }
188
189    let end = format!("-----END {tag}-----");
190    let body = rest.strip_suffix(&end).ok_or_else(invalid_key)?;
191
192    let mut encoded = Zeroizing::new(String::with_capacity(body.len()));
193    encoded.extend(body.chars().filter(|c| !c.is_ascii_whitespace()));
194
195    let mut der = Zeroizing::new(Vec::new());
196    BASE64_STANDARD
197        .decode_vec(encoded.as_bytes(), &mut der)
198        .map_err(|_| invalid_key())?;
199
200    if !is_complete_der(&der) {
201        return Err(invalid_key());
202    }
203
204    if let Ok(key) = KeyPair::from_pkcs8(&der) {
205        return Ok(SigningKey::Rsa(key));
206    }
207
208    if let Ok(key) = KeyPair::from_der(&der) {
209        return Ok(SigningKey::Rsa(key));
210    }
211
212    if let Ok(key) = Ed25519KeyPair::from_pkcs8(&der) {
213        return Ok(SigningKey::Ed25519(key));
214    }
215
216    Err(invalid_key())
217}
218
219// The key decoders do not reject bytes after the outer ASN.1 sequence
220fn is_complete_der(der: &[u8]) -> bool {
221    let [0x30, first, rest @ ..] = der else {
222        return false;
223    };
224
225    if first & 0x80 == 0 {
226        return rest.len() == usize::from(*first);
227    }
228
229    let count = usize::from(first & 0x7f);
230    if count == 0 || count > size_of::<usize>() || rest.len() < count || rest[0] == 0 {
231        return false;
232    }
233
234    let length = rest[..count].iter().try_fold(0usize, |length, b| {
235        length.checked_mul(256)?.checked_add(usize::from(*b))
236    });
237
238    length.is_some_and(|length| length >= 128 && length == rest.len() - count)
239}
240
241/// Environment variable names for Kalshi API credentials.
242#[must_use]
243pub const fn credential_env_vars(environment: KalshiEnvironment) -> (&'static str, &'static str) {
244    match environment {
245        KalshiEnvironment::Production => ("KALSHI_API_KEY_ID", "KALSHI_PRIVATE_KEY"),
246        KalshiEnvironment::Demo => ("KALSHI_DEMO_API_KEY_ID", "KALSHI_DEMO_PRIVATE_KEY"),
247    }
248}
249
250pub(crate) fn validate_credentials(
251    api_key_id: Option<&SecretString>,
252    private_key: Option<&SecretString>,
253) -> ConfigResult<()> {
254    match (api_key_id, private_key) {
255        (None, None) => Ok(()),
256        (Some(key), Some(private_key)) => {
257            if key.expose_secret().is_empty()
258                || !key.expose_secret().bytes().all(|b| (33..=126).contains(&b))
259            {
260                return Err(ConfigError::invalid_value(
261                    "api_key_id",
262                    "must contain non-empty visible ASCII",
263                ));
264            }
265
266            if private_key.expose_secret().trim().is_empty() {
267                return Err(ConfigError::empty_field("private_key"));
268            }
269
270            Ok(())
271        }
272        _ => Err(ConfigError::invalid_value(
273            "api_key_id",
274            "api_key_id and private_key must be supplied together",
275        )),
276    }
277}
278
279#[cfg(test)]
280mod tests {
281    use std::process::Command;
282
283    use aws_lc_rs::signature::{
284        KeyPair as _, RSA_PKCS1_2048_8192_SHA256, RSA_PSS_2048_8192_SHA256, UnparsedPublicKey,
285    };
286    use rstest::rstest;
287
288    use super::*;
289
290    mod keys {
291        include!(concat!(
292            env!("CARGO_MANIFEST_DIR"),
293            "/tests/integration/keys.rs"
294        ));
295    }
296
297    #[derive(serde::Deserialize)]
298    struct Vector {
299        timestamp_ms: u64,
300        method: String,
301        path: String,
302        payload: String,
303        signature: String,
304    }
305
306    #[rstest]
307    fn test_ed25519_exact_openssl_vectors_and_canonical_payloads() {
308        let credential = KalshiCredential::resolve(
309            Some("vector-key".into()),
310            Some(keys::ed25519_pkcs8().into()),
311            KalshiEnvironment::Production,
312        )
313        .unwrap();
314        let vectors: Vec<Vector> =
315            serde_json::from_str(include_str!("../../test_data/auth_vectors.json")).unwrap();
316
317        for vector in vectors {
318            assert_eq!(
319                vector.payload,
320                format!("{}{}{}", vector.timestamp_ms, vector.method, vector.path)
321            );
322
323            for method in [vector.method.clone(), vector.method.to_ascii_lowercase()] {
324                for path in [
325                    vector.path.clone(),
326                    format!("{}?limit=7&token=secret-query", vector.path),
327                ] {
328                    let headers = credential
329                        .headers(vector.timestamp_ms, &method, &path)
330                        .unwrap();
331                    let actual = headers
332                        .iter()
333                        .map(|(k, v)| (k.as_str(), v.expose_secret()))
334                        .collect::<Vec<_>>();
335                    assert_eq!(
336                        actual,
337                        vec![
338                            (KALSHI_ACCESS_KEY_HEADER, "vector-key"),
339                            (
340                                KALSHI_ACCESS_TIMESTAMP_HEADER,
341                                vector.timestamp_ms.to_string().as_str()
342                            ),
343                            (KALSHI_ACCESS_SIGNATURE_HEADER, vector.signature.as_str()),
344                        ]
345                    );
346                    assert!(!format!("{headers:?}").contains(&vector.signature));
347                }
348            }
349        }
350
351        assert_eq!(format!("{credential:?}"), "KalshiCredential { .. }");
352    }
353
354    #[rstest]
355    #[case(&keys::rsa_pkcs1())]
356    #[case(&keys::rsa_pkcs8())]
357    fn test_rsa_pss_parameters_and_randomized_signatures(#[case] pem: &str) {
358        let credential = KalshiCredential::resolve(
359            Some("rsa-key".into()),
360            Some(pem.into()),
361            KalshiEnvironment::Production,
362        )
363        .unwrap();
364
365        let SigningKey::Rsa(key) = &credential.key else {
366            panic!("expected decoded RSA key");
367        };
368
369        let payload = b"1703123456789GET/trade-api/v2/portfolio/balance";
370        let mut signatures = Vec::new();
371
372        for _ in 0..2 {
373            let headers = credential
374                .headers(
375                    1703123456789,
376                    "get",
377                    "/trade-api/v2/portfolio/balance?limit=4",
378                )
379                .unwrap();
380            let signature = BASE64_STANDARD
381                .decode(headers[2].1.expose_secret())
382                .unwrap();
383            let public_key = key.public_key().as_ref();
384            UnparsedPublicKey::new(&RSA_PSS_2048_8192_SHA256, public_key)
385                .verify(payload, &signature)
386                .unwrap();
387            assert!(
388                UnparsedPublicKey::new(&RSA_PKCS1_2048_8192_SHA256, public_key)
389                    .verify(payload, &signature)
390                    .is_err()
391            );
392            assert!(
393                UnparsedPublicKey::new(&RSA_PSS_2048_8192_SHA256, public_key)
394                    .verify(b"1703123456GET/trade-api/v2/portfolio/balance", &signature)
395                    .is_err()
396            );
397            assert!(!format!("{headers:?}").contains(headers[2].1.expose_secret()));
398            signatures.push(signature);
399        }
400
401        assert_ne!(signatures[0], signatures[1]);
402    }
403
404    #[rstest]
405    #[case(&keys::ed25519_pkcs8(), "RSA PRIVATE KEY")]
406    #[case(&keys::rsa_pkcs1(), "PRIVATE KEY")]
407    fn test_algorithm_selected_from_der_not_pem_label(#[case] pem: &str, #[case] label: &str) {
408        let mut lines = pem.lines().collect::<Vec<_>>();
409        lines.remove(0);
410        lines.pop();
411        let relabeled = format!(
412            "-----BEGIN {label}-----\n{}\n-----END {label}-----",
413            lines.join("\n")
414        );
415        let actual = decode_key(&relabeled).unwrap();
416        assert_eq!(
417            matches!(actual, SigningKey::Ed25519(_)),
418            pem == keys::ed25519_pkcs8()
419        );
420    }
421
422    #[rstest]
423    #[case(&keys::ed25519_pkcs8())]
424    #[case(&keys::rsa_pkcs1())]
425    #[case(&keys::rsa_pkcs8())]
426    fn test_rejects_extra_pem_or_der_and_redacts_errors(#[case] pem: &str) {
427        let lines = pem.lines().collect::<Vec<_>>();
428        let mut der = BASE64_STANDARD
429            .decode(lines[1..lines.len() - 1].join(""))
430            .unwrap();
431        der.extend_from_slice(b"trailing-sensitive-data");
432        let trailing_der = format!(
433            "{}\n{}\n{}",
434            lines[0],
435            BASE64_STANDARD.encode(der),
436            lines[lines.len() - 1]
437        );
438
439        for value in [
440            format!("prefix-secret{pem}"),
441            format!("{pem}suffix-secret"),
442            format!("{pem}{pem}"),
443            trailing_der,
444        ] {
445            let error = KalshiCredential::resolve(
446                Some("sensitive-key-id".into()),
447                Some(value.clone().into()),
448                KalshiEnvironment::Production,
449            )
450            .unwrap_err();
451
452            for rendered in [error.to_string(), format!("{error:?}")] {
453                assert!(!rendered.contains("sensitive-key-id"));
454                assert!(!rendered.contains(&value));
455                assert!(!rendered.contains("trailing-sensitive-data"));
456            }
457        }
458    }
459
460    #[rstest]
461    #[case("")]
462    #[case(" \n")]
463    #[case("not-a-private-key-secret")]
464    #[case(concat!("-----BEGIN ", "PRIVATE KEY-----\n%%%secret%%%\n-----END ", "PRIVATE KEY-----"))]
465    #[case(&keys::unsupported_ec())]
466    #[case(&keys::encrypted())]
467    fn test_rejects_invalid_and_unsupported_keys(#[case] pem: &str) {
468        assert!(
469            KalshiCredential::resolve(
470                Some("valid-id".into()),
471                Some(pem.into()),
472                KalshiEnvironment::Production
473            )
474            .is_err()
475        );
476    }
477
478    #[rstest]
479    #[case("", Some(keys::ed25519_pkcs8()))]
480    #[case("\nsecret", Some(keys::ed25519_pkcs8()))]
481    #[case("valid-id", None)]
482    fn test_rejects_invalid_explicit_pair(#[case] key: &str, #[case] pem: Option<String>) {
483        assert!(
484            KalshiCredential::resolve(
485                Some(key.into()),
486                pem.map(SecretString::from),
487                KalshiEnvironment::Production
488            )
489            .is_err()
490        );
491    }
492
493    #[rstest]
494    #[case("GET\r\nkey: secret", "/trade-api/v2")]
495    #[case("", "/trade-api/v2")]
496    #[case("GET", "https://secret-host/trade-api/v2")]
497    #[case("GET", "//secret-host/path")]
498    #[case("GET", "/path#secret-fragment")]
499    fn test_rejects_invalid_signing_target(#[case] method: &str, #[case] path: &str) {
500        let credential = KalshiCredential::resolve(
501            Some("id".into()),
502            Some(keys::ed25519_pkcs8().into()),
503            KalshiEnvironment::Production,
504        )
505        .unwrap();
506        let error = credential.headers(1, method, path).unwrap_err();
507        assert!(!error.to_string().contains("secret"));
508    }
509
510    #[rstest]
511    fn test_environment_resolution_in_isolated_processes() {
512        for scenario in [
513            "production",
514            "demo",
515            "explicit",
516            "missing",
517            "incomplete",
518            "cross-environment",
519            "incomplete-explicit",
520            "empty",
521            "malformed",
522        ] {
523            let mut command = Command::new(std::env::current_exe().unwrap());
524            command
525                .args([
526                    "--exact",
527                    "common::credential::tests::test_environment_resolution_child",
528                ])
529                .env("NAUTILUS_KALSHI_AUTH_SCENARIO", scenario);
530
531            for environment in [KalshiEnvironment::Production, KalshiEnvironment::Demo] {
532                let (key, private) = credential_env_vars(environment);
533                command.env_remove(key).env_remove(private);
534            }
535
536            match scenario {
537                "production" | "demo" | "incomplete-explicit" => {
538                    command
539                        .env("KALSHI_API_KEY_ID", "production-id")
540                        .env("KALSHI_PRIVATE_KEY", keys::rsa_pkcs8())
541                        .env("KALSHI_DEMO_API_KEY_ID", "demo-id")
542                        .env("KALSHI_DEMO_PRIVATE_KEY", keys::ed25519_pkcs8());
543                }
544                "explicit" => {
545                    command
546                        .env("KALSHI_API_KEY_ID", "invalid\n")
547                        .env("KALSHI_PRIVATE_KEY", "invalid");
548                }
549                "incomplete" => {
550                    command.env("KALSHI_API_KEY_ID", "production-id");
551                }
552                "cross-environment" => {
553                    command
554                        .env("KALSHI_API_KEY_ID", "production-id")
555                        .env("KALSHI_DEMO_PRIVATE_KEY", keys::ed25519_pkcs8());
556                }
557                "empty" => {
558                    command
559                        .env("KALSHI_API_KEY_ID", "")
560                        .env("KALSHI_PRIVATE_KEY", keys::rsa_pkcs8());
561                }
562                "malformed" => {
563                    command
564                        .env("KALSHI_API_KEY_ID", "production-id")
565                        .env("KALSHI_PRIVATE_KEY", "invalid-sensitive-key");
566                }
567                _ => {}
568            }
569
570            let output = command.output().unwrap();
571            let stdout = String::from_utf8_lossy(&output.stdout);
572            assert!(output.status.success(), "scenario {scenario}: {stdout}");
573            assert!(
574                stdout.contains("test result: ok. 1 passed; 0 failed; 0 ignored;"),
575                "scenario {scenario}: {stdout}"
576            );
577        }
578    }
579
580    #[rstest]
581    fn test_environment_resolution_child() {
582        let Ok(scenario) = std::env::var("NAUTILUS_KALSHI_AUTH_SCENARIO") else {
583            return;
584        };
585
586        let environment = if scenario == "demo" {
587            KalshiEnvironment::Demo
588        } else {
589            KalshiEnvironment::Production
590        };
591
592        let (key, private) = match scenario.as_str() {
593            "explicit" => (
594                Some("explicit-id".into()),
595                Some(keys::ed25519_pkcs8().into()),
596            ),
597            "incomplete-explicit" => (Some("incomplete-id".into()), None),
598            _ => (None, None),
599        };
600
601        let actual = KalshiCredential::resolve(key, private, environment);
602
603        match scenario.as_str() {
604            "production" | "demo" | "explicit" => {
605                let credential = actual.unwrap();
606                let expected = format!("{scenario}-id");
607                assert_eq!(credential.api_key_id.expose_secret(), expected);
608                assert_eq!(
609                    matches!(credential.key, SigningKey::Rsa(_)),
610                    scenario == "production"
611                );
612            }
613            _ => assert!(actual.is_err()),
614        }
615    }
616
617    #[rstest]
618    fn test_credential_env_vars() {
619        assert_eq!(
620            credential_env_vars(KalshiEnvironment::Production),
621            ("KALSHI_API_KEY_ID", "KALSHI_PRIVATE_KEY"),
622        );
623        assert_eq!(
624            credential_env_vars(KalshiEnvironment::Demo),
625            ("KALSHI_DEMO_API_KEY_ID", "KALSHI_DEMO_PRIVATE_KEY"),
626        );
627    }
628}