Skip to main content

nautilus_polymarket/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//! Credential management for the Polymarket adapter.
17
18use std::{
19    fmt::{Debug, Display},
20    str::FromStr,
21};
22
23use alloy::signers::local::PrivateKeySigner;
24use alloy_primitives::Address;
25use aws_lc_rs::hmac;
26use base64::{Engine, engine::general_purpose::URL_SAFE};
27use nautilus_core::{
28    env::{get_or_env_var, get_or_env_var_opt},
29    hex,
30    string::secret::{REDACTED, SecretString, mask_api_key},
31};
32use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
33
34use crate::http::error::{Error, Result};
35
36const API_KEY_VAR: &str = "POLYMARKET_API_KEY";
37const API_SECRET_VAR: &str = "POLYMARKET_API_SECRET";
38const PASSPHRASE_VAR: &str = "POLYMARKET_PASSPHRASE";
39const PRIVATE_KEY_VAR: &str = "POLYMARKET_PK";
40const FUNDER_VAR: &str = "POLYMARKET_FUNDER";
41const RELAYER_API_KEY_VAR: &str = "POLYMARKET_RELAYER_API_KEY";
42const RELAYER_SIGNER_ADDRESS_VAR: &str = "POLYMARKET_RELAYER_SIGNER_ADDRESS";
43
44/// Returns `(api_key_var, api_secret_var, passphrase_var, private_key_var, funder_var)`.
45#[must_use]
46pub const fn credential_env_vars() -> (
47    &'static str,
48    &'static str,
49    &'static str,
50    &'static str,
51    &'static str,
52) {
53    (
54        API_KEY_VAR,
55        API_SECRET_VAR,
56        PASSPHRASE_VAR,
57        PRIVATE_KEY_VAR,
58        FUNDER_VAR,
59    )
60}
61
62/// Returns `(relayer_api_key_var, relayer_signer_address_var)`.
63#[must_use]
64pub const fn relayer_credential_env_vars() -> (&'static str, &'static str) {
65    (RELAYER_API_KEY_VAR, RELAYER_SIGNER_ADDRESS_VAR)
66}
67
68/// Secure wrapper for an EVM private key, zeroized on drop.
69#[derive(Clone, Zeroize, ZeroizeOnDrop)]
70pub struct EvmPrivateKey {
71    formatted_key: String,
72    raw_bytes: Vec<u8>,
73}
74
75impl EvmPrivateKey {
76    /// Creates a new [`EvmPrivateKey`] from a hex string (with or without `0x` prefix).
77    pub fn new(key: &str) -> Result<Self> {
78        let key = Zeroizing::new(key.trim().to_string());
79        let hex_key = key.strip_prefix("0x").unwrap_or(&key);
80
81        if hex_key.len() != 64 {
82            return Err(Error::bad_request(
83                "EVM private key must be 32 bytes (64 hex chars)",
84            ));
85        }
86
87        if !hex_key.chars().all(|c| c.is_ascii_hexdigit()) {
88            return Err(Error::bad_request("EVM private key must be valid hex"));
89        }
90
91        let normalized = Zeroizing::new(hex_key.to_lowercase());
92        let formatted = format!("0x{}", normalized.as_str());
93
94        let raw_bytes = hex::decode(&normalized)
95            .map_err(|_| Error::bad_request("Invalid hex in private key"))?;
96
97        if raw_bytes.len() != 32 {
98            return Err(Error::bad_request(
99                "EVM private key must be exactly 32 bytes",
100            ));
101        }
102
103        Ok(Self {
104            formatted_key: formatted,
105            raw_bytes,
106        })
107    }
108
109    pub fn as_hex(&self) -> &str {
110        &self.formatted_key
111    }
112
113    pub fn as_bytes(&self) -> &[u8] {
114        &self.raw_bytes
115    }
116}
117
118impl Debug for EvmPrivateKey {
119    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120        write!(f, "EvmPrivateKey({REDACTED})")
121    }
122}
123
124impl Display for EvmPrivateKey {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        write!(f, "EvmPrivateKey({REDACTED})")
127    }
128}
129
130/// L2 API credential with HMAC-SHA256 signing for authenticated requests.
131///
132/// Stores the API key as owned text and the decoded secret as `Box<[u8]>`,
133/// both zeroized on drop. The base64 secret and
134/// HMAC key are initialized once to avoid repeated setup per request.
135/// `aws-lc-rs` cleanses the native HMAC context when the key is dropped.
136#[derive(Clone)]
137pub struct Credential {
138    api_key: Box<str>,
139    secret_bytes: Box<[u8]>,
140    signing_key: hmac::Key,
141    passphrase: String,
142}
143
144impl Credential {
145    /// Creates a new credential. The `api_secret` must be base64-encoded.
146    #[expect(
147        clippy::needless_pass_by_value,
148        reason = "ownership ensures the encoded secret is zeroized immediately after decoding"
149    )]
150    pub fn new(
151        api_key: SecretString,
152        api_secret: SecretString,
153        passphrase: SecretString,
154    ) -> Result<Self> {
155        // Polymarket API secrets are URL-safe base64 encoded
156        let secret_bytes = URL_SAFE
157            .decode(api_secret.expose_secret())
158            .map_err(|e| Error::auth(format!("Invalid base64 API secret: {e}")))?
159            .into_boxed_slice();
160        let signing_key = hmac::Key::new(hmac::HMAC_SHA256, &secret_bytes);
161
162        Ok(Self {
163            api_key: api_key.into_inner().into_boxed_str(),
164            secret_bytes,
165            signing_key,
166            passphrase: passphrase.into_inner(),
167        })
168    }
169
170    pub(crate) fn api_key_str(&self) -> &str {
171        &self.api_key
172    }
173
174    pub fn passphrase(&self) -> &str {
175        &self.passphrase
176    }
177
178    /// Returns the raw API secret as a base64-encoded string.
179    ///
180    /// Used for WebSocket user channel authentication which expects the raw
181    /// secret (not an HMAC signature).
182    pub fn api_secret(&self) -> SecretString {
183        URL_SAFE.encode(&*self.secret_bytes).into()
184    }
185
186    /// Signs a request with HMAC-SHA256 and returns the base64-encoded signature.
187    ///
188    /// Message format: `{timestamp}{method}{request_path}{body}`
189    pub fn sign(&self, timestamp: &str, method: &str, request_path: &str, body: &str) -> String {
190        let mut context = hmac::Context::with_key(&self.signing_key);
191        context.update(timestamp.as_bytes());
192        context.update(method.as_bytes());
193        context.update(request_path.as_bytes());
194        context.update(body.as_bytes());
195        let tag = context.sign();
196        URL_SAFE.encode(tag.as_ref())
197    }
198
199    /// Resolves from provided values, falling back to environment variables.
200    pub fn resolve(
201        api_key: Option<SecretString>,
202        api_secret: Option<SecretString>,
203        passphrase: Option<SecretString>,
204    ) -> Result<Self> {
205        let key = resolve_secret(api_key, "api_key", API_KEY_VAR)?;
206        let secret = resolve_secret(api_secret, "api_secret", API_SECRET_VAR)?;
207        let pass = resolve_secret(passphrase, "passphrase", PASSPHRASE_VAR)?;
208
209        Self::new(key, secret, pass)
210    }
211
212    pub fn from_env() -> Result<Self> {
213        Self::resolve(None, None, None)
214    }
215}
216
217/// Relayer API key used to authorize gasless Deposit Wallet submissions.
218#[derive(Clone)]
219pub struct RelayerApiKey {
220    key: SecretString,
221    address: String,
222}
223
224impl RelayerApiKey {
225    /// Creates a Relayer API key from the key value and signer address.
226    ///
227    /// # Errors
228    ///
229    /// Returns an error if the key is empty or `address` is not a valid EVM address.
230    pub fn new(key: SecretString, address: &str) -> Result<Self> {
231        if key.expose_secret().trim().is_empty() {
232            return Err(Error::bad_request("Relayer API key must not be empty"));
233        }
234
235        let parsed = Address::from_str(address.trim())
236            .map_err(|e| Error::bad_request(format!("Invalid Relayer API key address: {e}")))?;
237        Ok(Self {
238            key,
239            address: format!("{parsed:#x}"),
240        })
241    }
242
243    #[must_use]
244    pub fn key(&self) -> &str {
245        self.key.expose_secret()
246    }
247
248    #[must_use]
249    pub fn address(&self) -> &str {
250        &self.address
251    }
252
253    /// Resolves from provided values, falling back to environment variables.
254    ///
255    /// # Errors
256    ///
257    /// Returns an error if either value is missing or invalid.
258    pub fn resolve(key: Option<SecretString>, address: Option<String>) -> Result<Self> {
259        let key = key.filter(|value| !value.expose_secret().trim().is_empty());
260        let key = resolve_secret(key, "relayer_api_key", RELAYER_API_KEY_VAR)?;
261
262        let address = match address.filter(|value| !value.trim().is_empty()) {
263            Some(address) => address,
264            None => get_or_env_var(None, RELAYER_SIGNER_ADDRESS_VAR).map_err(|_| {
265                Error::bad_request(format!(
266                    "{RELAYER_SIGNER_ADDRESS_VAR} environment variable is not set"
267                ))
268            })?,
269        };
270
271        Self::new(key, &address)
272    }
273
274    /// Resolves Relayer credentials from the environment.
275    ///
276    /// # Errors
277    ///
278    /// Returns an error if either environment variable is missing or invalid.
279    pub fn from_env() -> Result<Self> {
280        Self::resolve(None, None)
281    }
282}
283
284impl Debug for RelayerApiKey {
285    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
286        f.debug_struct(stringify!(RelayerApiKey))
287            .field("key", &REDACTED)
288            .field("address", &self.address)
289            .finish()
290    }
291}
292
293impl Drop for Credential {
294    fn drop(&mut self) {
295        self.api_key.zeroize();
296        self.secret_bytes.zeroize();
297        self.passphrase.zeroize();
298    }
299}
300
301impl Debug for Credential {
302    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
303        f.debug_struct(stringify!(Credential))
304            .field("api_key", &REDACTED)
305            .field("secret_bytes", &REDACTED)
306            .field("passphrase", &REDACTED)
307            .finish()
308    }
309}
310
311/// Complete secrets configuration for Polymarket.
312///
313/// Ethereum address derived from the private key (lowercased with `0x` prefix).
314#[derive(Clone)]
315pub struct Secrets {
316    pub private_key: EvmPrivateKey,
317    pub credential: Credential,
318    pub funder: Option<String>,
319    pub address: String,
320}
321
322impl Debug for Secrets {
323    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
324        f.debug_struct(stringify!(Secrets))
325            .field("private_key", &self.private_key)
326            .field("credential", &self.credential)
327            .field("address", &self.address)
328            .field(
329                "funder",
330                &self.funder.as_deref().map(|s| {
331                    if s.len() > 10 {
332                        format!("{}...{}", &s[..6], &s[s.len() - 4..])
333                    } else {
334                        s.to_string()
335                    }
336                }),
337            )
338            .finish()
339    }
340}
341
342impl Secrets {
343    /// Resolves from provided values, falling back to environment variables.
344    pub fn resolve(
345        private_key: Option<SecretString>,
346        api_key: Option<SecretString>,
347        api_secret: Option<SecretString>,
348        passphrase: Option<SecretString>,
349        funder: Option<String>,
350    ) -> Result<Self> {
351        let pk_str = resolve_secret(private_key, "private_key", PRIVATE_KEY_VAR)?;
352
353        let private_key = EvmPrivateKey::new(pk_str.expose_secret())?;
354        let credential = Credential::resolve(api_key, api_secret, passphrase)?;
355
356        validate_env_override(funder.as_deref(), "funder", FUNDER_VAR)?;
357
358        let funder = get_or_env_var_opt(funder, FUNDER_VAR)
359            .filter(|s| !s.trim().is_empty())
360            .map(|value| {
361                Address::from_str(value.trim())
362                    .map(|address| format!("{address:#x}"))
363                    .map_err(|e| Error::bad_request(format!("Invalid funder address: {e}")))
364            })
365            .transpose()?;
366
367        let key_hex = private_key
368            .as_hex()
369            .strip_prefix("0x")
370            .unwrap_or(private_key.as_hex());
371        let signer = PrivateKeySigner::from_str(key_hex)
372            .map_err(|e| Error::bad_request(format!("Failed to derive address: {e}")))?;
373        let address = format!("{:#x}", signer.address());
374
375        log::debug!(
376            "Polymarket credentials resolved: address={}, funder={:?}, api_key={}",
377            address,
378            funder.as_deref().map(|s| &s[..10.min(s.len())]),
379            mask_api_key(credential.api_key_str()),
380        );
381
382        Ok(Self {
383            private_key,
384            credential,
385            funder,
386            address,
387        })
388    }
389
390    pub fn from_env() -> Result<Self> {
391        Self::resolve(None, None, None, None, None)
392    }
393}
394
395fn resolve_secret(value: Option<SecretString>, field: &str, env_var: &str) -> Result<SecretString> {
396    validate_env_override(
397        value.as_ref().map(SecretString::expose_secret),
398        field,
399        env_var,
400    )?;
401
402    if let Some(value) = value {
403        return Ok(value);
404    }
405
406    get_or_env_var(None, env_var)
407        .map(SecretString::from)
408        .map_err(|_| Error::bad_request(format!("{env_var} environment variable is not set")))
409}
410
411pub(crate) fn validate_env_override(value: Option<&str>, field: &str, env_var: &str) -> Result<()> {
412    if value.is_some_and(|value| value.trim().is_empty()) {
413        return Err(Error::bad_request(format!(
414            "{field} must not be blank; omit it or pass None to use {env_var}"
415        )));
416    }
417
418    Ok(())
419}
420
421#[cfg(test)]
422mod tests {
423    use rstest::rstest;
424
425    use super::*;
426
427    const TEST_PRIVATE_KEY: &str =
428        "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef";
429
430    fn test_secret_b64() -> String {
431        URL_SAFE.encode(b"test_secret_key_32bytes_pad12345")
432    }
433
434    #[rstest]
435    fn test_evm_private_key_with_0x_prefix() {
436        let key = EvmPrivateKey::new(TEST_PRIVATE_KEY).unwrap();
437        assert_eq!(key.as_hex(), TEST_PRIVATE_KEY);
438        assert_eq!(key.as_bytes().len(), 32);
439    }
440
441    #[rstest]
442    fn test_evm_private_key_without_0x_prefix() {
443        let key = EvmPrivateKey::new(&TEST_PRIVATE_KEY[2..]).unwrap();
444        assert_eq!(key.as_hex(), TEST_PRIVATE_KEY);
445    }
446
447    #[rstest]
448    fn test_evm_private_key_invalid_length() {
449        assert!(EvmPrivateKey::new("0x123").is_err());
450    }
451
452    #[rstest]
453    fn test_evm_private_key_invalid_hex() {
454        let bad = "0x123g567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef";
455        assert!(EvmPrivateKey::new(bad).is_err());
456    }
457
458    #[rstest]
459    fn test_evm_private_key_debug_redacts() {
460        let key = EvmPrivateKey::new(TEST_PRIVATE_KEY).unwrap();
461        let debug = format!("{key:?}");
462        assert_eq!(debug, format!("EvmPrivateKey({REDACTED})"));
463        assert!(!debug.contains("1234"));
464    }
465
466    #[rstest]
467    fn test_credential_creation() {
468        let cred = Credential::new(
469            "test_api_key".into(),
470            test_secret_b64().into(),
471            "test_pass".into(),
472        )
473        .unwrap();
474        let api_secret = cred.api_secret();
475
476        assert_eq!(cred.api_key_str(), "test_api_key");
477        assert_eq!(cred.passphrase(), "test_pass");
478        assert_eq!(api_secret.expose_secret(), test_secret_b64());
479        assert_eq!(format!("{api_secret:?}"), REDACTED);
480    }
481
482    #[rstest]
483    fn test_credential_invalid_base64_secret() {
484        let result = Credential::new("key".into(), "not-valid-base64!!!".into(), "pass".into());
485        assert!(result.is_err());
486    }
487
488    #[rstest]
489    fn test_credential_sign_produces_base64() {
490        let cred = Credential::new(
491            "key".into(),
492            URL_SAFE.encode(b"test_secret").into(),
493            "pass".into(),
494        )
495        .unwrap();
496
497        let sig = cred.sign("1234567890", "GET", "/order", "");
498        assert!(URL_SAFE.decode(&sig).is_ok());
499    }
500
501    #[rstest]
502    fn test_credential_sign_deterministic() {
503        let cred = Credential::new(
504            "key".into(),
505            URL_SAFE.encode(b"deterministic_test").into(),
506            "pass".into(),
507        )
508        .unwrap();
509
510        let sig1 = cred.sign("1000", "POST", "/order", r#"{"price":"0.5"}"#);
511        let sig2 = cred.sign("1000", "POST", "/order", r#"{"price":"0.5"}"#);
512        assert_eq!(sig1, sig2);
513    }
514
515    #[rstest]
516    fn test_credential_sign_different_timestamps() {
517        let cred = Credential::new(
518            "key".into(),
519            URL_SAFE.encode(b"test_key").into(),
520            "pass".into(),
521        )
522        .unwrap();
523
524        let sig1 = cred.sign("1000", "GET", "/order", "");
525        let sig2 = cred.sign("1001", "GET", "/order", "");
526        assert_ne!(sig1, sig2);
527    }
528
529    #[rstest]
530    fn test_credential_sign_different_methods() {
531        let cred = Credential::new(
532            "key".into(),
533            URL_SAFE.encode(b"test_key").into(),
534            "pass".into(),
535        )
536        .unwrap();
537
538        let sig1 = cred.sign("1000", "GET", "/order", "");
539        let sig2 = cred.sign("1000", "POST", "/order", "");
540        assert_ne!(sig1, sig2);
541    }
542
543    #[rstest]
544    fn test_credential_sign_different_paths() {
545        let cred = Credential::new(
546            "key".into(),
547            URL_SAFE.encode(b"test_key").into(),
548            "pass".into(),
549        )
550        .unwrap();
551
552        let sig1 = cred.sign("1000", "GET", "/order", "");
553        let sig2 = cred.sign("1000", "GET", "/trades", "");
554        assert_ne!(sig1, sig2);
555    }
556
557    #[rstest]
558    fn test_credential_sign_different_bodies() {
559        let cred = Credential::new(
560            "key".into(),
561            URL_SAFE.encode(b"test_key").into(),
562            "pass".into(),
563        )
564        .unwrap();
565
566        let sig1 = cred.sign("1000", "POST", "/order", r#"{"a":1}"#);
567        let sig2 = cred.sign("1000", "POST", "/order", r#"{"a":2}"#);
568        assert_ne!(sig1, sig2);
569    }
570
571    #[rstest]
572    fn test_credential_sign_empty_body() {
573        let cred = Credential::new(
574            "key".into(),
575            URL_SAFE.encode(b"test_key").into(),
576            "pass".into(),
577        )
578        .unwrap();
579
580        let sig1 = cred.sign("1000", "GET", "/order", "");
581        let sig2 = cred.sign("1000", "GET", "/order", "{}");
582        assert_ne!(sig1, sig2);
583    }
584
585    // Test vectors from Polymarket SDK (rs-clob-client/src/auth.rs)
586    const SDK_SECRET: &str = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
587    const SDK_PASSPHRASE: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
588
589    #[rstest]
590    fn test_credential_sign_matches_sdk_l2_vector() {
591        let cred = Credential::new(
592            "00000000-0000-0000-0000-000000000000".into(),
593            SDK_SECRET.into(),
594            SDK_PASSPHRASE.into(),
595        )
596        .unwrap();
597
598        // SDK test: timestamp=1, GET, "/", empty body
599        let sig = cred.sign("1", "GET", "/", "");
600        assert_eq!(sig, "eHaylCwqRSOa2LFD77Nt_SaTpbsxzN8eTEI3LryhEj4=");
601    }
602
603    #[rstest]
604    fn test_credential_sign_matches_sdk_hmac_vector() {
605        let cred = Credential::new("key".into(), SDK_SECRET.into(), "pass".into()).unwrap();
606
607        // SDK test: raw message "1000000test-sign/orders{"hash":"0x123"}"
608        let sig = cred.sign("1000000", "test-sign", "/orders", r#"{"hash":"0x123"}"#);
609        assert_eq!(sig, "4gJVbox-R6XlDK4nlaicig0_ANVL1qdcahiL8CXfXLM=");
610    }
611
612    #[rstest]
613    fn test_credential_debug_redacts_secret() {
614        let cred = Credential::new(
615            "my_api_key_12345678".into(),
616            test_secret_b64().into(),
617            "my_passphrase".into(),
618        )
619        .unwrap();
620
621        let debug = format!("{cred:?}");
622        assert_eq!(debug.matches(REDACTED).count(), 3);
623        assert!(!debug.contains("my_api_key_12345678"));
624        assert!(!debug.contains("test_secret"));
625        assert!(!debug.contains("my_passphrase"));
626    }
627
628    #[rstest]
629    fn test_relayer_api_key_normalizes_address_and_redacts_key() {
630        let key = RelayerApiKey::new(
631            "relayer-secret".into(),
632            "0xF39Fd6e51aad88F6F4ce6aB8827279cffFb92266",
633        )
634        .unwrap();
635        assert_eq!(key.key(), "relayer-secret");
636        assert_eq!(key.address(), "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266");
637        let debug = format!("{key:?}");
638        assert!(debug.contains(REDACTED));
639        assert!(!debug.contains("relayer-secret"));
640    }
641
642    #[rstest]
643    fn test_relayer_api_key_retains_secret_owner_and_allocation() {
644        let mut value = String::with_capacity(4096);
645        value.push_str("relayer-secret");
646        let allocation = value.as_ptr();
647        let key =
648            RelayerApiKey::new(value.into(), "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266").unwrap();
649        let secret: &SecretString = &key.key;
650
651        assert_eq!(secret.expose_secret().as_ptr(), allocation);
652
653        let cloned = key.clone();
654        drop(key);
655
656        assert_eq!(cloned.key(), "relayer-secret");
657        assert_eq!(
658            cloned.address(),
659            "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266"
660        );
661        assert_eq!(
662            format!("{cloned:?}"),
663            "RelayerApiKey { key: \"<redacted>\", address: \"0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266\" }",
664        );
665    }
666
667    #[rstest]
668    fn test_relayer_api_key_rejects_empty_key_and_invalid_address() {
669        assert!(
670            RelayerApiKey::new("".into(), "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266").is_err()
671        );
672        assert!(RelayerApiKey::new("key".into(), "not-an-address").is_err());
673    }
674
675    #[rstest]
676    #[case("")]
677    #[case(" \t")]
678    fn blank_override_never_falls_back(#[case] blank: &str) {
679        let error = resolve_secret(Some(blank.into()), "private_key", "POLYMARKET_PK").unwrap_err();
680        assert_eq!(
681            error.to_string(),
682            "bad request: private_key must not be blank; omit it or pass None to use POLYMARKET_PK"
683        );
684    }
685
686    #[rstest]
687    fn explicit_override_does_not_require_environment() {
688        let resolved = resolve_secret(
689            Some("explicit-value".into()),
690            "api_key",
691            "POLYMARKET_CONFIG_TEST_MISSING_VARIABLE",
692        )
693        .unwrap();
694        assert_eq!(resolved.expose_secret(), "explicit-value");
695    }
696
697    #[rstest]
698    fn omitted_override_requires_environment() {
699        let error =
700            resolve_secret(None, "api_key", "POLYMARKET_CONFIG_TEST_MISSING_VARIABLE").unwrap_err();
701        assert_eq!(
702            error.to_string(),
703            "bad request: POLYMARKET_CONFIG_TEST_MISSING_VARIABLE environment variable is not set"
704        );
705    }
706}