Skip to main content

nautilus_betfair/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//! Betfair API credential storage.
17
18use std::fmt::Debug;
19
20use nautilus_core::string::secret::REDACTED;
21use thiserror::Error;
22use zeroize::ZeroizeOnDrop;
23
24/// Environment variable name for the Betfair account username.
25pub const BETFAIR_USERNAME_ENV: &str = "BETFAIR_USERNAME";
26
27/// Environment variable name for the Betfair account password.
28pub const BETFAIR_PASSWORD_ENV: &str = "BETFAIR_PASSWORD";
29
30/// Environment variable name for the Betfair application key.
31pub const BETFAIR_APP_KEY_ENV: &str = "BETFAIR_APP_KEY";
32
33/// Errors that can occur when resolving credentials.
34#[derive(Debug, Error)]
35pub enum CredentialError {
36    /// Username was provided but password is missing.
37    #[error("Username provided but password is missing")]
38    MissingPassword,
39    /// Password was provided but username is missing.
40    #[error("Password provided but username is missing")]
41    MissingUsername,
42    /// App key is missing.
43    #[error("App key is missing")]
44    MissingAppKey,
45}
46
47/// Betfair API credentials for session-token authentication.
48///
49/// Betfair uses username/password login to obtain a session token,
50/// which is then passed as `X-Authentication` on subsequent requests.
51/// The `app_key` identifies the application and is sent as `X-Application`.
52///
53/// Secrets are automatically zeroized on drop for security.
54#[derive(Clone, ZeroizeOnDrop)]
55pub struct BetfairCredential {
56    username: Box<str>,
57    password: Box<str>,
58    app_key: Box<str>,
59    certs_dir: Option<String>,
60}
61
62impl Debug for BetfairCredential {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        f.debug_struct(stringify!(BetfairCredential))
65            .field("username", &REDACTED)
66            .field("password", &REDACTED)
67            .field("app_key", &REDACTED)
68            .field("certs_dir", &self.certs_dir)
69            .finish()
70    }
71}
72
73impl BetfairCredential {
74    /// Creates a new [`BetfairCredential`] instance.
75    #[must_use]
76    pub fn new(username: String, password: String, app_key: String) -> Self {
77        Self {
78            username: username.into_boxed_str(),
79            password: password.into_boxed_str(),
80            app_key: app_key.into_boxed_str(),
81            certs_dir: None,
82        }
83    }
84
85    /// Sets the certificate directory to enable certificate login.
86    #[must_use]
87    pub fn with_certs_dir(mut self, certs_dir: String) -> Self {
88        self.certs_dir = Some(certs_dir);
89        self
90    }
91
92    /// Load credentials from environment variables.
93    ///
94    /// Reads `BETFAIR_USERNAME`, `BETFAIR_PASSWORD`, and `BETFAIR_APP_KEY`.
95    ///
96    /// Returns `None` if any variable is not set.
97    #[must_use]
98    pub fn from_env() -> Option<Self> {
99        let username = std::env::var(BETFAIR_USERNAME_ENV).ok()?;
100        let password = std::env::var(BETFAIR_PASSWORD_ENV).ok()?;
101        let app_key = std::env::var(BETFAIR_APP_KEY_ENV).ok()?;
102        Some(Self::new(username, password, app_key))
103    }
104
105    /// Resolves credentials from provided values or environment.
106    ///
107    /// If all three values are provided, uses those directly.
108    /// If none are provided, falls back to environment variables.
109    ///
110    /// # Errors
111    ///
112    /// Returns an error if credentials are partially provided.
113    pub fn resolve(
114        username: Option<String>,
115        password: Option<String>,
116        app_key: Option<String>,
117    ) -> Result<Option<Self>, CredentialError> {
118        match (username, password, app_key) {
119            (Some(u), Some(p), Some(k)) => Ok(Some(Self::new(u, p, k))),
120            (None, None, None) => Ok(Self::from_env()),
121            (Some(_), None, _) => Err(CredentialError::MissingPassword),
122            (None, Some(_), _) => Err(CredentialError::MissingUsername),
123            (_, _, None) => Err(CredentialError::MissingAppKey),
124            (None, None, Some(_)) => Err(CredentialError::MissingUsername),
125        }
126    }
127
128    /// Returns the certificate directory, if certificate login is enabled.
129    #[must_use]
130    pub fn certs_dir(&self) -> Option<&str> {
131        self.certs_dir.as_deref()
132    }
133
134    /// Returns the account username.
135    #[must_use]
136    pub fn username(&self) -> &str {
137        &self.username
138    }
139
140    /// Returns the account password.
141    #[must_use]
142    pub fn password(&self) -> &str {
143        &self.password
144    }
145
146    /// Returns the application key.
147    #[must_use]
148    pub fn app_key(&self) -> &str {
149        &self.app_key
150    }
151}
152
153#[cfg(test)]
154mod tests {
155    use rstest::rstest;
156
157    use super::*;
158
159    #[rstest]
160    fn test_credential_creation() {
161        let cred = BetfairCredential::new(
162            "testuser".to_string(),
163            "testpass".to_string(),
164            "appkey123".to_string(),
165        );
166
167        assert_eq!(cred.username(), "testuser");
168        assert_eq!(cred.password(), "testpass");
169        assert_eq!(cred.app_key(), "appkey123");
170        assert_eq!(cred.certs_dir(), None);
171    }
172
173    #[rstest]
174    fn test_debug_redacts_credentials() {
175        let cred = BetfairCredential::new(
176            "myuser".to_string(),
177            "supersecret".to_string(),
178            "myappkey".to_string(),
179        );
180
181        let debug_output = format!("{cred:?}");
182
183        assert_eq!(debug_output.matches(REDACTED).count(), 3);
184        assert!(!debug_output.contains("myuser"));
185        assert!(!debug_output.contains("supersecret"));
186        assert!(!debug_output.contains("myappkey"));
187    }
188
189    #[rstest]
190    fn test_resolve_with_all_credentials() {
191        let result = BetfairCredential::resolve(
192            Some("user".to_string()),
193            Some("pass".to_string()),
194            Some("key".to_string()),
195        );
196
197        assert!(result.is_ok());
198        let cred = result.unwrap().unwrap();
199        assert_eq!(cred.username(), "user");
200    }
201
202    #[rstest]
203    fn test_resolve_missing_password() {
204        let result =
205            BetfairCredential::resolve(Some("user".to_string()), None, Some("key".to_string()));
206
207        assert!(result.is_err());
208        assert!(matches!(
209            result.unwrap_err(),
210            CredentialError::MissingPassword
211        ));
212    }
213
214    #[rstest]
215    fn test_resolve_missing_username() {
216        let result =
217            BetfairCredential::resolve(None, Some("pass".to_string()), Some("key".to_string()));
218
219        assert!(result.is_err());
220        assert!(matches!(
221            result.unwrap_err(),
222            CredentialError::MissingUsername
223        ));
224    }
225
226    #[rstest]
227    fn test_resolve_missing_app_key() {
228        let result =
229            BetfairCredential::resolve(Some("user".to_string()), Some("pass".to_string()), None);
230
231        assert!(result.is_err());
232        assert!(matches!(
233            result.unwrap_err(),
234            CredentialError::MissingAppKey
235        ));
236    }
237
238    #[rstest]
239    fn test_resolve_none_falls_back_to_env() {
240        // Without env vars set, should return None
241        let result = BetfairCredential::resolve(None, None, None);
242
243        assert!(result.is_ok());
244        // Will be None unless env vars are set in the test environment
245    }
246}