ig_client/application/auth.rs
1/******************************************************************************
2 Author: Joaquín Béjar García
3 Email: jb@taunais.com
4 Date: 19/10/25
5******************************************************************************/
6
7//! Authentication module for IG Markets API
8//!
9//! This module provides a simplified authentication interface that handles:
10//! - API v2 (CST/X-SECURITY-TOKEN) authentication
11//! - API v3 (OAuth) authentication with automatic token refresh
12//! - Account switching
13//! - Automatic re-authentication when tokens expire
14
15use crate::application::config::Config;
16use crate::application::http::make_http_request;
17use crate::application::rate_limiter::RateLimiter;
18use crate::constants::USER_AGENT;
19use crate::error::{AppError, AuthError};
20pub(crate) use crate::model::auth::{SecurityHeaders, SessionResponse};
21use crate::model::retry::RetryConfig;
22use reqwest::{Client, Method};
23use std::sync::Arc;
24use tokio::sync::RwLock;
25use tracing::{debug, error, info, warn};
26// `OAuthToken` and `chrono::Utc` are only referenced from the unit tests below
27// (the `Session` data type that used them in production moved to
28// `crate::model::auth`), so they are imported under `cfg(test)` to keep the
29// non-test build free of unused-import warnings.
30#[cfg(test)]
31use crate::model::auth::OAuthToken;
32#[cfg(test)]
33use chrono::Utc;
34
35// `Session` and `WebsocketInfo` are pure data types and live in the model
36// layer (`crate::model::auth`). They are re-exported here so the historical
37// public paths `crate::application::auth::Session` /
38// `crate::application::auth::WebsocketInfo` keep resolving, and so the auth
39// I/O manager below can reference them unqualified.
40pub use crate::model::auth::{Session, WebsocketInfo};
41
42/// Merges freshly-issued v2 security tokens into a session after an account
43/// switch.
44///
45/// IG returns a new `X-SECURITY-TOKEN` (and sometimes a new `CST`) in the
46/// response to `PUT /session`. When a token is present it replaces the stale
47/// one; when absent the existing token is preserved — the switch response does
48/// not always re-issue both, and nulling a token would break the next request.
49/// All other session fields are carried through unchanged.
50#[must_use]
51fn apply_switch_headers(mut session: Session, cst: Option<&str>, xst: Option<&str>) -> Session {
52 if let Some(cst) = cst {
53 session.cst = Some(cst.to_string());
54 }
55 if let Some(xst) = xst {
56 session.x_security_token = Some(xst.to_string());
57 }
58 session
59}
60
61/// Decides whether a v2 login should switch to the configured account.
62///
63/// Returns `true` only when a *real* account was configured (not empty and not
64/// the [`DEFAULT_ACCOUNT_ID`](crate::constants::DEFAULT_ACCOUNT_ID) sentinel) and
65/// it differs from the account the login landed on. OAuth (v3) pins the account
66/// elsewhere and is never switched here. Guarding the sentinel is essential: it
67/// is non-empty, so without this check an unconfigured client would try to
68/// switch to `"default_account_id"`, which IG rejects, failing an otherwise-valid
69/// login.
70#[must_use]
71fn should_switch_account(api_version: u8, configured: &str, current: &str) -> bool {
72 api_version != 3
73 && !configured.is_empty()
74 && configured != crate::constants::DEFAULT_ACCOUNT_ID
75 && configured != current
76}
77
78/// Selects the proactive-refresh safety margin (in seconds) for a session based
79/// on its authentication model.
80///
81/// v3 (OAuth) access tokens are short-lived (~60s), so the v2 margin would keep
82/// them permanently "about to expire" and force a login on every call; a small
83/// [`PROACTIVE_REFRESH_MARGIN_V3_SECS`](crate::constants::PROACTIVE_REFRESH_MARGIN_V3_SECS)
84/// margin is used instead. v2 (CST / X-SECURITY-TOKEN) sessions last ~6h, so the
85/// larger
86/// [`PROACTIVE_REFRESH_MARGIN_V2_SECS`](crate::constants::PROACTIVE_REFRESH_MARGIN_V2_SECS)
87/// margin gives ample lead time.
88///
89/// The *same* margin is used by both [`Auth::get_session`] (to decide a refresh
90/// is due) and [`Auth::refresh_token`] (to actually perform it), so the
91/// proactive-refresh window is consistent and always fires — the previous 300s /
92/// 1s mismatch meant the advertised margin never triggered a refresh.
93#[must_use]
94fn proactive_refresh_margin_secs(session: &Session) -> u64 {
95 if session.is_oauth() {
96 crate::constants::PROACTIVE_REFRESH_MARGIN_V3_SECS
97 } else {
98 crate::constants::PROACTIVE_REFRESH_MARGIN_V2_SECS
99 }
100}
101
102/// Ensures a v3 (OAuth) login actually produced an OAuth session.
103///
104/// The v3 `/session` endpoint is expected to return an OAuth body. Because
105/// [`SessionResponse`] is untagged, a v2-shaped body sent to the v3 request
106/// still deserializes successfully — as a v2 session carrying no OAuth token.
107/// That is a server-side / protocol mismatch, not a client bug. On the reactive
108/// [`force_refresh`](Auth::force_refresh) -> [`login`](Auth::login) path a 401
109/// reaches this code more often, so a mismatched body must surface as a typed
110/// error rather than panic.
111///
112/// The offending response body / token is never logged.
113///
114/// # Errors
115/// Returns [`AppError::Unauthorized`] when the session lacks an OAuth token.
116fn ensure_oauth_session(session: Session) -> Result<Session, AppError> {
117 if session.is_oauth() {
118 Ok(session)
119 } else {
120 error!("v3 login response did not contain an OAuth token");
121 Err(AppError::Unauthorized)
122 }
123}
124
125/// Authentication manager for IG Markets API
126///
127/// Handles all authentication operations including:
128/// - Login with API v2 or v3
129/// - Automatic OAuth token refresh
130/// - Account switching
131/// - Session management
132/// - Rate limiting for API requests
133pub struct Auth {
134 config: Arc<Config>,
135 client: Client,
136 session: Arc<RwLock<Option<Session>>>,
137 // `RateLimiter` is `Clone` and already wraps each governor bucket in an
138 // `Arc`, so it is shared directly without an outer `RwLock`: the limiter is
139 // configured once at construction and never write-swapped.
140 rate_limiter: RateLimiter,
141}
142
143impl Auth {
144 /// Creates a new Auth instance, returning an error if the HTTP client
145 /// cannot be constructed.
146 ///
147 /// This is the sole constructor for [`Auth`]: it surfaces a TLS /
148 /// client-builder failure as a typed [`AppError`] instead of panicking, so
149 /// callers can handle a broken TLS backend gracefully.
150 ///
151 /// # Arguments
152 /// * `config` - Configuration containing credentials and API settings
153 ///
154 /// # Errors
155 /// Returns [`AppError::Network`] if the underlying `reqwest` client cannot
156 /// be built (e.g. the system TLS backend fails to initialize).
157 pub fn try_new(config: Arc<Config>) -> Result<Self, AppError> {
158 let rate_limiter = RateLimiter::new(&config.rate_limiter);
159 Self::with_rate_limiter(config, rate_limiter)
160 }
161
162 /// Builds an `Auth` that paces against a caller-supplied limiter.
163 ///
164 /// IG meters its allowance per API key, and a login is one of the requests
165 /// it counts. When a key's session and its data requests pace against
166 /// separate limiters, the key's real budget is the sum of the two and IG
167 /// rejects requests the client believed were within budget. Sharing one
168 /// limiter per key is what makes the local pacing match the remote one.
169 ///
170 /// # Arguments
171 /// * `config` - Configuration containing credentials and API settings
172 /// * `rate_limiter` - The limiter owned by this key
173 ///
174 /// # Errors
175 /// Returns [`AppError::Network`] if the underlying `reqwest` client cannot
176 /// be built (e.g. the system TLS backend fails to initialize).
177 pub fn with_rate_limiter(
178 config: Arc<Config>,
179 rate_limiter: RateLimiter,
180 ) -> Result<Self, AppError> {
181 let client = Client::builder().user_agent(USER_AGENT).build()?;
182
183 Ok(Self {
184 config,
185 client,
186 session: Arc::new(RwLock::new(None)),
187 rate_limiter,
188 })
189 }
190
191 /// Gets WebSocket connection information for Lightstreamer, reusing the
192 /// cached session.
193 ///
194 /// This calls [`Auth::get_session`], which returns the cached session when
195 /// it is still valid and only logs in (storing the new session) when none
196 /// exists or it has expired. The configured API version is honoured — no
197 /// per-call v2 re-login is performed.
198 ///
199 /// # Returns
200 /// * `Ok(WebsocketInfo)` - Endpoint and authentication tokens for the
201 /// current session.
202 /// * `Err(AppError)` - If session retrieval (login / refresh) fails.
203 ///
204 /// # Errors
205 /// Returns [`AppError`] when the session cannot be retrieved (login or token
206 /// refresh failure).
207 pub async fn ws_info(&self) -> Result<WebsocketInfo, AppError> {
208 let session = self.get_session().await?;
209 Ok(session.get_websocket_info())
210 }
211
212 /// Gets the WebSocket password for Lightstreamer authentication
213 ///
214 /// # Returns
215 /// * WebSocket password in format "CST-{cst}|XST-{token}" or empty string if session is not available
216 #[deprecated(
217 note = "use ws_info() which reuses the cached session and returns a typed error instead of a default-on-error WebsocketInfo"
218 )]
219 pub async fn get_ws_info(&self) -> WebsocketInfo {
220 self.ws_info().await.unwrap_or_default()
221 }
222
223 /// Whether a session is cached and not within its refresh margin.
224 ///
225 /// Lets a caller tell "this key can send right now" from "this key would
226 /// have to log in first" without triggering the login. The key pool needs
227 /// that distinction: probing every key with `get_session` would
228 /// authenticate the whole pool to serve one request.
229 pub async fn has_ready_session(&self) -> bool {
230 let session = self.session.read().await;
231 session.as_ref().is_some_and(|sess| {
232 !sess.needs_token_refresh(Some(proactive_refresh_margin_secs(sess)))
233 })
234 }
235
236 /// Gets the current session, ensuring tokens are valid
237 ///
238 /// This method automatically refreshes expired OAuth tokens or re-authenticates if needed.
239 ///
240 /// # Returns
241 /// * `Ok(Session)` - Valid session with fresh tokens
242 /// * `Err(AppError)` - If authentication fails
243 ///
244 /// # Errors
245 /// Returns [`AppError`] when login or token refresh fails.
246 pub async fn get_session(&self) -> Result<Session, AppError> {
247 let session = self.session.read().await;
248
249 if let Some(sess) = session.as_ref() {
250 // Refresh proactively once the session enters its refresh margin. The
251 // margin is derived from the session type so it matches the one
252 // `refresh_token` re-checks with — otherwise the refresh detour would
253 // hand back the same near-expired session (the old 300s/1s mismatch).
254 let margin = proactive_refresh_margin_secs(sess);
255 if sess.needs_token_refresh(Some(margin)) {
256 drop(session); // Release read lock
257 debug!(margin_secs = margin, "session within refresh margin");
258 return self.refresh_token().await;
259 }
260 return Ok(sess.clone());
261 }
262
263 drop(session);
264
265 // No session exists, need to login
266 info!("No active session, logging in");
267 self.login().await
268 }
269
270 /// Performs initial login to IG Markets API
271 ///
272 /// Automatically detects API version from config and uses appropriate authentication method.
273 ///
274 /// # Returns
275 /// * `Ok(Session)` - Authenticated session
276 /// * `Err(AppError)` - If login fails
277 pub async fn login(&self) -> Result<Session, AppError> {
278 let api_version = self.config.api_version.unwrap_or(2);
279
280 debug!("Logging in with API v{}", api_version);
281
282 let session = if api_version == 3 {
283 self.login_oauth().await?
284 } else {
285 self.login_v2().await?
286 };
287
288 // Store session. The write guard is scoped so it is released before any
289 // account-selection switch below: `switch_account` reads `self.session`
290 // via `get_session`, and holding the guard across that call would
291 // deadlock.
292 {
293 let mut sess = self.session.write().await;
294 *sess = Some(session.clone());
295 }
296
297 info!("✓ Login successful, account: {}", session.account_id);
298
299 // v2 account selection: the v2 `/session` response reports IG's
300 // current/default account, which may differ from the configured one.
301 // Switch to the configured account when it is set and differs. This
302 // cannot recurse: the session was just stored above, so
303 // `switch_account` -> `get_session` returns the cached (valid) session
304 // and never triggers another login. OAuth (v3) already pins the account
305 // in `login_oauth`, so it is skipped here.
306 if api_version != 3 {
307 let configured = self.config.credentials.account_id.clone();
308 if should_switch_account(api_version, &configured, &session.account_id) {
309 info!("selecting configured account after v2 login");
310 // `Box::pin` breaks the compile-time async recursion cycle
311 // (login -> switch_account -> get_session -> login). The cycle
312 // is runtime-bounded: the session was stored above, so
313 // `get_session` returns it without logging in again.
314 return Box::pin(self.switch_account(&configured, None)).await;
315 }
316 }
317
318 Ok(session)
319 }
320
321 /// Performs login using API v2 (CST/X-SECURITY-TOKEN) with automatic retry on rate limit
322 async fn login_v2(&self) -> Result<Session, AppError> {
323 let url = format!("{}/session", self.config.rest_api.base_url);
324
325 let body = serde_json::json!({
326 "identifier": self.config.credentials.username,
327 "password": self.config.credentials.password,
328 });
329
330 debug!("Sending v2 login request to: {}", url);
331
332 let headers = vec![
333 ("X-IG-API-KEY", self.config.credentials.api_key.as_str()),
334 ("Content-Type", "application/json"),
335 ("Version", "2"),
336 ];
337
338 let response = make_http_request(
339 &self.client,
340 &self.rate_limiter,
341 Method::POST,
342 &url,
343 headers,
344 &Some(body),
345 RetryConfig::default(),
346 )
347 .await?;
348
349 // Extract CST and X-SECURITY-TOKEN from headers
350 let cst: String = match response
351 .headers()
352 .get("CST")
353 .and_then(|v| v.to_str().ok())
354 .map(String::from)
355 {
356 Some(token) => token,
357 None => {
358 // A rejected / malformed auth response, not bad caller input:
359 // surface a typed auth error naming the missing header.
360 error!("missing cst header in login response");
361 return Err(AuthError::MissingSessionToken("cst".to_string()).into());
362 }
363 };
364 let x_security_token: String = match response
365 .headers()
366 .get("X-SECURITY-TOKEN")
367 .and_then(|v| v.to_str().ok())
368 .map(String::from)
369 {
370 Some(token) => token,
371 None => {
372 // A rejected / malformed auth response, not bad caller input:
373 // surface a typed auth error naming the missing header.
374 error!("missing x-security-token header in login response");
375 return Err(AuthError::MissingSessionToken("x-security-token".to_string()).into());
376 }
377 };
378
379 let x_ig_api_key: String = response
380 .headers()
381 .get("X-IG-API-KEY")
382 .and_then(|v| v.to_str().ok())
383 .map(String::from)
384 .unwrap_or_else(|| self.config.credentials.api_key.clone());
385
386 let security_headers: SecurityHeaders = SecurityHeaders {
387 cst,
388 x_security_token,
389 x_ig_api_key,
390 };
391
392 // Get response body as text first for debugging
393 let body_text = response.text().await.map_err(|e| {
394 error!("Failed to read response body: {}", e);
395 AppError::Network(e)
396 })?;
397 debug!("Login response body length: {} bytes", body_text.len());
398
399 // Parse the JSON
400 let mut response: SessionResponse = serde_json::from_str(&body_text).map_err(|e| {
401 // Never log the body: the `/session` response carries credentials.
402 error!(
403 endpoint = %url,
404 body_len = body_text.len(),
405 "failed to parse login response: {}",
406 e
407 );
408 AppError::Deserialization(format!("Failed to parse login response: {}", e))
409 })?;
410 let session = response.get_session_v2(&security_headers);
411
412 Ok(session)
413 }
414
415 /// Performs login using API v3 (OAuth) with automatic retry on rate limit
416 async fn login_oauth(&self) -> Result<Session, AppError> {
417 let url = format!("{}/session", self.config.rest_api.base_url);
418
419 let body = serde_json::json!({
420 "identifier": self.config.credentials.username,
421 "password": self.config.credentials.password,
422 });
423
424 debug!("Sending OAuth login request to: {}", url);
425 let headers = vec![
426 ("X-IG-API-KEY", self.config.credentials.api_key.as_str()),
427 ("Content-Type", "application/json"),
428 ("Version", "3"),
429 ];
430
431 let response = make_http_request(
432 &self.client,
433 &self.rate_limiter,
434 Method::POST,
435 &url,
436 headers,
437 &Some(body),
438 RetryConfig::default(),
439 )
440 .await?;
441
442 let response: SessionResponse = response.json().await?;
443 let mut session = response.get_session();
444 if session.account_id != self.config.credentials.account_id {
445 session.account_id = self.config.credentials.account_id.clone();
446 };
447
448 // A v2-shaped body on the v3 path (server-side mismatch) must not panic;
449 // surface it as a typed error instead.
450 ensure_oauth_session(session)
451 }
452
453 /// Proactively refreshes the session when it is within its refresh margin.
454 ///
455 /// This is the *proactive* path (driven by the local clock). It re-checks the
456 /// cached session against the same margin
457 /// [`get_session`](Self::get_session) used to decide a refresh was due, so
458 /// the two stay consistent and the refresh actually fires when the session is
459 /// close to expiry. If the session is still comfortably valid it is returned
460 /// unchanged; otherwise a full [`login`](Self::login) is performed.
461 ///
462 /// For the reactive 401 / server-side-invalidation path — where the local
463 /// clock still considers the token valid but IG has already rejected it — use
464 /// [`force_refresh`](Self::force_refresh), which re-authenticates
465 /// unconditionally.
466 ///
467 /// # Returns
468 /// * `Ok(Session)` - A valid session (refreshed if it was within margin).
469 /// * `Err(AppError)` - If re-authentication fails.
470 ///
471 /// # Errors
472 /// Returns [`AppError`] when a required login fails (network, credentials, or
473 /// rate limiting).
474 pub async fn refresh_token(&self) -> Result<Session, AppError> {
475 let current_session = {
476 let session = self.session.read().await;
477 session.clone()
478 };
479
480 if let Some(sess) = current_session {
481 // Honour the SAME margin `get_session` used to route here, so a
482 // session inside the proactive window is actually re-authenticated
483 // instead of being handed back near-expired.
484 let margin = proactive_refresh_margin_secs(&sess);
485 if sess.is_expired(Some(margin)) {
486 debug!(
487 margin_secs = margin,
488 "session within refresh margin, logging in"
489 );
490 self.login().await
491 } else {
492 Ok(sess)
493 }
494 } else {
495 warn!("No session to refresh, performing login");
496 self.login().await
497 }
498 }
499
500 /// Forces a fresh re-authentication regardless of local expiry state.
501 ///
502 /// This is the reactive 401 / server-side-invalidation path. When IG rejects
503 /// a token that the local clock still considers valid (server-side
504 /// invalidation, a concurrent login elsewhere, or clock skew), a proactive
505 /// [`refresh_token`](Self::refresh_token) would see a "valid" session and
506 /// hand back the *same* stale token, so the replayed request would fail
507 /// again. `force_refresh` ignores local expiry and performs a full
508 /// [`login`](Self::login), which fetches and stores a brand-new session.
509 ///
510 /// It cannot loop back through the 401 handler: [`login`](Self::login) issues
511 /// its HTTP requests through
512 /// [`make_http_request`] directly, not
513 /// through the [`HttpClient`](crate::application::http::HttpClient) refresh-and-replay
514 /// path, so a 401 encountered *during* login surfaces as a typed error rather
515 /// than recursing into `force_refresh`.
516 ///
517 /// # Returns
518 /// * `Ok(Session)` - A freshly authenticated session with new tokens.
519 /// * `Err(AppError)` - If re-authentication fails.
520 ///
521 /// # Errors
522 /// Returns [`AppError`] when the login request fails (network, credentials,
523 /// or rate limiting).
524 pub async fn force_refresh(&self) -> Result<Session, AppError> {
525 debug!("forcing re-authentication, ignoring local expiry");
526 self.login().await
527 }
528
529 /// Switches to a different trading account
530 ///
531 /// # Arguments
532 /// * `account_id` - The account ID to switch to
533 /// * `default_account` - Whether to set as default account
534 ///
535 /// # Returns
536 /// * `Ok(Session)` - New session for the switched account
537 /// * `Err(AppError)` - If account switch fails
538 pub async fn switch_account(
539 &self,
540 account_id: &str,
541 default_account: Option<bool>,
542 ) -> Result<Session, AppError> {
543 let current_session = self.get_session().await?;
544 if matches!(current_session.api_version, 3) {
545 return Err(AppError::InvalidInput(
546 "Cannot switch accounts with OAuth".to_string(),
547 ));
548 }
549
550 if current_session.account_id == account_id {
551 debug!("Already on account {}", account_id);
552 return Ok(current_session);
553 }
554
555 info!("Switching to account: {}", account_id);
556
557 let url = format!("{}/session", self.config.rest_api.base_url);
558
559 let mut body = serde_json::json!({
560 "accountId": account_id,
561 });
562
563 if let Some(default) = default_account {
564 body["defaultAccount"] = serde_json::json!(default);
565 }
566
567 // Build headers with authentication. Only the v2 (CST /
568 // X-SECURITY-TOKEN) path is reachable here: OAuth sessions
569 // (`api_version == 3`) are rejected above, so no `Authorization: Bearer`
570 // branch is needed.
571 let api_key = self.config.credentials.api_key.clone();
572 let cst;
573 let x_security_token;
574
575 let mut headers = vec![
576 ("X-IG-API-KEY", api_key.as_str()),
577 ("Content-Type", "application/json"),
578 ("Version", "1"),
579 ];
580
581 if let Some(cst_val) = ¤t_session.cst {
582 cst = cst_val.clone();
583 headers.push(("CST", cst.as_str()));
584 }
585 if let Some(token_val) = ¤t_session.x_security_token {
586 x_security_token = token_val.clone();
587 headers.push(("X-SECURITY-TOKEN", x_security_token.as_str()));
588 }
589
590 let response = make_http_request(
591 &self.client,
592 &self.rate_limiter,
593 Method::PUT,
594 &url,
595 headers,
596 &Some(body),
597 RetryConfig::default(),
598 )
599 .await?;
600
601 // IG re-issues the X-SECURITY-TOKEN (and sometimes CST) in the switch
602 // response. Read them from the headers and merge them in; a missing
603 // header keeps the existing token rather than nulling it.
604 let new_cst = response
605 .headers()
606 .get("CST")
607 .and_then(|v| v.to_str().ok())
608 .map(String::from);
609 let new_x_security_token = response
610 .headers()
611 .get("X-SECURITY-TOKEN")
612 .and_then(|v| v.to_str().ok())
613 .map(String::from);
614
615 // IG re-issues X-SECURITY-TOKEN on a successful switch. Its absence on a
616 // 2xx response is anomalous (proxy stripping / response-shape drift): the
617 // old token is kept below, but flag it since it will 401 the next call.
618 if new_x_security_token.is_none() {
619 warn!("switch response carried no X-SECURITY-TOKEN; keeping the previous token");
620 }
621
622 // After switching, update the session with the fresh tokens and the new
623 // account id.
624 let mut new_session = apply_switch_headers(
625 current_session.clone(),
626 new_cst.as_deref(),
627 new_x_security_token.as_deref(),
628 );
629 new_session.account_id = account_id.to_string();
630
631 {
632 let mut session = self.session.write().await;
633 *session = Some(new_session.clone());
634 }
635
636 info!("✓ Switched to account: {}", account_id);
637 Ok(new_session)
638 }
639
640 /// Logs out and clears the current session.
641 ///
642 /// Before clearing local state, this issues `DELETE /session` (IG API
643 /// Version 1) with the current authentication headers. For a **v2** session
644 /// (CST / X-SECURITY-TOKEN) this invalidates the session server-side. For a
645 /// **v3 / OAuth** session there is no IG token-revocation endpoint and the
646 /// short-lived access token has usually already expired, so `DELETE /session`
647 /// is best-effort: logout clears local state and the OAuth tokens lapse on
648 /// their own expiry rather than being actively revoked. A `401 Unauthorized`
649 /// (or an already-invalid OAuth token) is treated as already-logged-out and
650 /// reported as success.
651 ///
652 /// The local session is always cleared, even when the server-side call
653 /// fails, so the client is never wedged in an authenticated-but-unusable
654 /// state; the underlying failure is still returned as a typed error.
655 ///
656 /// # Errors
657 /// Returns [`AppError`] when the server-side logout request fails for a
658 /// reason other than an already-invalid session (401). The local session is
659 /// cleared regardless.
660 pub async fn logout(&self) -> Result<(), AppError> {
661 info!("Logging out");
662
663 // Snapshot the current session without holding the lock across the HTTP
664 // call. With no session there is nothing to revoke server-side.
665 let current_session = {
666 let session = self.session.read().await;
667 session.clone()
668 };
669
670 let server_result = match current_session {
671 Some(sess) => self.revoke_session(&sess).await,
672 None => Ok(()),
673 };
674
675 // Always clear local state so the client is never wedged, regardless of
676 // the server-side outcome.
677 {
678 let mut session = self.session.write().await;
679 *session = None;
680 }
681
682 match server_result {
683 Ok(()) => {
684 info!("✓ Logged out successfully");
685 Ok(())
686 }
687 Err(e) => {
688 // The error type carries no secrets (see `AppError`), so it is
689 // safe to log; local state has already been cleared.
690 error!("server-side logout failed: {}", e);
691 Err(e)
692 }
693 }
694 }
695
696 /// Issues `DELETE /session` (IG API Version 1) to terminate the session
697 /// server-side.
698 ///
699 /// A `401 Unauthorized` (or an already-invalid OAuth token) means the
700 /// session is no longer valid server-side and is treated as success.
701 ///
702 /// # Errors
703 /// Returns [`AppError`] if the request fails for any reason other than an
704 /// already-invalid session.
705 async fn revoke_session(&self, session: &Session) -> Result<(), AppError> {
706 let url = format!("{}/session", self.config.rest_api.base_url);
707 let api_key = self.config.credentials.api_key.clone();
708
709 let auth_header_value;
710 let cst;
711 let x_security_token;
712
713 let mut headers = vec![
714 ("X-IG-API-KEY", api_key.as_str()),
715 ("Content-Type", "application/json"),
716 ("Version", "1"),
717 ];
718
719 if let Some(oauth) = &session.oauth_token {
720 auth_header_value = format!("Bearer {}", oauth.access_token);
721 headers.push(("Authorization", auth_header_value.as_str()));
722 headers.push(("IG-ACCOUNT-ID", session.account_id.as_str()));
723 } else {
724 if let Some(cst_val) = &session.cst {
725 cst = cst_val.clone();
726 headers.push(("CST", cst.as_str()));
727 }
728 if let Some(token_val) = &session.x_security_token {
729 x_security_token = token_val.clone();
730 headers.push(("X-SECURITY-TOKEN", x_security_token.as_str()));
731 }
732 }
733
734 match make_http_request(
735 &self.client,
736 &self.rate_limiter,
737 Method::DELETE,
738 &url,
739 headers,
740 &None::<()>,
741 RetryConfig::default(),
742 )
743 .await
744 {
745 Ok(_) => Ok(()),
746 // A 401 (or an expired OAuth token) means the session is already
747 // invalid server-side: the logout goal is met.
748 Err(AppError::Unauthorized | AppError::OAuthTokenExpired) => {
749 debug!("session already invalid server-side; treating as logged out");
750 Ok(())
751 }
752 Err(e) => Err(e),
753 }
754 }
755}
756
757#[cfg(test)]
758mod session_lifecycle_tests {
759 use super::*;
760
761 fn v2_session(cst: Option<&str>, xst: Option<&str>) -> Session {
762 Session {
763 account_id: "ACC-OLD".to_string(),
764 client_id: "CLIENT1".to_string(),
765 lightstreamer_endpoint: "demo-apd.marketdatasystems.com".to_string(),
766 cst: cst.map(String::from),
767 x_security_token: xst.map(String::from),
768 oauth_token: None,
769 api_version: 2,
770 expires_at: 123,
771 }
772 }
773
774 #[test]
775 fn test_apply_switch_headers_replaces_xst_and_keeps_other_fields() {
776 let session = v2_session(Some("OLD-CST"), Some("OLD-XST"));
777 // A switch response that only re-issues the X-SECURITY-TOKEN.
778 let updated = apply_switch_headers(session, None, Some("NEW-XST"));
779
780 assert_eq!(updated.x_security_token.as_deref(), Some("NEW-XST"));
781 // CST is preserved when the header is absent.
782 assert_eq!(updated.cst.as_deref(), Some("OLD-CST"));
783 // Unrelated fields carry through unchanged.
784 assert_eq!(updated.account_id, "ACC-OLD");
785 assert_eq!(updated.expires_at, 123);
786 assert_eq!(updated.api_version, 2);
787 }
788
789 #[test]
790 fn test_apply_switch_headers_updates_both_tokens() {
791 let session = v2_session(Some("OLD-CST"), Some("OLD-XST"));
792 let updated = apply_switch_headers(session, Some("NEW-CST"), Some("NEW-XST"));
793
794 assert_eq!(updated.cst.as_deref(), Some("NEW-CST"));
795 assert_eq!(updated.x_security_token.as_deref(), Some("NEW-XST"));
796 }
797
798 #[test]
799 fn test_apply_switch_headers_none_preserves_existing_tokens() {
800 let session = v2_session(Some("OLD-CST"), Some("OLD-XST"));
801 // A switch response carrying neither header must not null the tokens.
802 let updated = apply_switch_headers(session, None, None);
803
804 assert_eq!(updated.cst.as_deref(), Some("OLD-CST"));
805 assert_eq!(updated.x_security_token.as_deref(), Some("OLD-XST"));
806 }
807
808 #[test]
809 fn test_should_switch_account_guards_the_sentinel_and_v3() {
810 use crate::constants::DEFAULT_ACCOUNT_ID;
811
812 // Real configured account that differs from the current one: switch.
813 assert!(should_switch_account(2, "ACC-B", "ACC-A"));
814 // Unconfigured default sentinel: must NOT switch (would fail login).
815 assert!(!should_switch_account(2, DEFAULT_ACCOUNT_ID, "ACC-A"));
816 // Empty configured account: must not switch.
817 assert!(!should_switch_account(2, "", "ACC-A"));
818 // Already on the configured account: no switch needed.
819 assert!(!should_switch_account(2, "ACC-A", "ACC-A"));
820 // OAuth (v3) is never switched through this path.
821 assert!(!should_switch_account(3, "ACC-B", "ACC-A"));
822 }
823
824 #[tokio::test]
825 async fn test_ws_info_uses_cached_session_without_login() {
826 let auth =
827 Auth::try_new(Arc::new(Config::default())).expect("auth construction should succeed");
828
829 // Seed a valid (non-expired) v2 session with known tokens. Because the
830 // session is valid, `ws_info` -> `get_session` must return it without a
831 // network login (a login would require real credentials and fail).
832 let expires_at = (Utc::now().timestamp() + 3600) as u64;
833 let seeded = Session {
834 account_id: "ACC123".to_string(),
835 client_id: "CLIENT1".to_string(),
836 lightstreamer_endpoint: "demo-apd.marketdatasystems.com".to_string(),
837 cst: Some("CST-TOKEN".to_string()),
838 x_security_token: Some("XST-TOKEN".to_string()),
839 oauth_token: None,
840 api_version: 2,
841 expires_at,
842 };
843 {
844 let mut guard = auth.session.write().await;
845 *guard = Some(seeded);
846 }
847
848 let ws = match auth.ws_info().await {
849 Ok(ws) => ws,
850 Err(e) => panic!("ws_info should return Ok for a cached session: {e}"),
851 };
852
853 // The returned info derives from the cached session's tokens, proving no
854 // fresh login occurred.
855 assert_eq!(ws.account_id, "ACC123");
856 assert_eq!(ws.cst.as_deref(), Some("CST-TOKEN"));
857 assert_eq!(ws.x_security_token.as_deref(), Some("XST-TOKEN"));
858 assert!(ws.server.contains("demo-apd.marketdatasystems.com"));
859 }
860}
861
862#[cfg(test)]
863mod expiry_and_refresh_tests {
864 use super::*;
865
866 fn v2_session(expires_at: u64) -> Session {
867 Session {
868 account_id: "ACC123".to_string(),
869 client_id: "CLIENT1".to_string(),
870 lightstreamer_endpoint: "demo-apd.marketdatasystems.com".to_string(),
871 cst: Some("CST-TOKEN".to_string()),
872 x_security_token: Some("XST-TOKEN".to_string()),
873 oauth_token: None,
874 api_version: 2,
875 expires_at,
876 }
877 }
878
879 fn v3_session(expires_at: u64) -> Session {
880 Session {
881 account_id: "ACC123".to_string(),
882 client_id: "CLIENT1".to_string(),
883 lightstreamer_endpoint: "demo-apd.marketdatasystems.com".to_string(),
884 cst: None,
885 x_security_token: None,
886 oauth_token: Some(OAuthToken {
887 access_token: "ACCESS".to_string(),
888 refresh_token: "REFRESH".to_string(),
889 scope: "read write".to_string(),
890 token_type: "Bearer".to_string(),
891 expires_in: "60".to_string(),
892 created_at: Utc::now(),
893 }),
894 api_version: 3,
895 expires_at,
896 }
897 }
898
899 #[test]
900 fn test_seconds_until_expiry_expired_session_returns_zero() {
901 // expires_at 100s in the past -> saturating to 0, never a huge u64.
902 let past = u64::try_from(Utc::now().timestamp())
903 .unwrap_or(0)
904 .saturating_sub(100);
905 let session = v2_session(past);
906 assert_eq!(session.seconds_until_expiry(), 0);
907 }
908
909 #[test]
910 fn test_seconds_until_expiry_valid_session_is_positive() {
911 let future = u64::try_from(Utc::now().timestamp())
912 .unwrap_or(0)
913 .saturating_add(3600);
914 let session = v2_session(future);
915 // Allow a small slack for the wall-clock read inside the method.
916 assert!(session.seconds_until_expiry() > 3500);
917 }
918
919 #[test]
920 fn test_time_until_expiry_expired_session_is_zero() {
921 let past = u64::try_from(Utc::now().timestamp())
922 .unwrap_or(0)
923 .saturating_sub(100);
924 let session = v2_session(past);
925 assert_eq!(session.time_until_expiry(), std::time::Duration::ZERO);
926 }
927
928 #[test]
929 fn test_is_expired_large_margin_does_not_underflow() {
930 // Tiny expires_at with an enormous margin must not underflow / panic;
931 // it simply reports the session as expired.
932 let session = v2_session(1);
933 assert!(session.is_expired(Some(u64::MAX)));
934 assert!(session.is_expired(Some(1000)));
935 }
936
937 #[test]
938 fn test_is_expired_valid_session_within_margin_still_valid() {
939 let future = u64::try_from(Utc::now().timestamp())
940 .unwrap_or(0)
941 .saturating_add(3600);
942 let session = v2_session(future);
943 assert!(!session.is_expired(Some(60)));
944 }
945
946 #[test]
947 fn test_proactive_refresh_margin_v3_is_small_v2_is_large() {
948 let v3 = v3_session(0);
949 let v2 = v2_session(0);
950 assert_eq!(
951 proactive_refresh_margin_secs(&v3),
952 crate::constants::PROACTIVE_REFRESH_MARGIN_V3_SECS
953 );
954 assert_eq!(
955 proactive_refresh_margin_secs(&v2),
956 crate::constants::PROACTIVE_REFRESH_MARGIN_V2_SECS
957 );
958 // v3's short-lived tokens get a tighter margin than v2's 6h sessions.
959 assert!(proactive_refresh_margin_secs(&v3) < proactive_refresh_margin_secs(&v2));
960 }
961
962 #[tokio::test]
963 async fn test_refresh_token_returns_cached_valid_session_without_login() {
964 // refresh_token has an expiry gate: a comfortably-valid session is
965 // returned unchanged, so no network login is attempted. This is the
966 // behaviour that differs from force_refresh (which always re-logs in).
967 let auth =
968 Auth::try_new(Arc::new(Config::default())).expect("auth construction should succeed");
969 let future = u64::try_from(Utc::now().timestamp())
970 .unwrap_or(0)
971 .saturating_add(3600);
972 let seeded = v2_session(future);
973 {
974 let mut guard = auth.session.write().await;
975 *guard = Some(seeded);
976 }
977
978 let refreshed = match auth.refresh_token().await {
979 Ok(session) => session,
980 Err(e) => panic!("refresh_token should return the cached session: {e}"),
981 };
982 // Same cached tokens returned: no re-authentication happened.
983 assert_eq!(refreshed.account_id, "ACC123");
984 assert_eq!(refreshed.cst.as_deref(), Some("CST-TOKEN"));
985 assert_eq!(refreshed.expires_at, future);
986 }
987
988 #[test]
989 fn test_force_refresh_is_public_and_present() {
990 // Compile-time proof that the additive 401-path API exists. Invoking it
991 // would perform a real login, so it is not called here (no network in
992 // unit tests).
993 let _ = Auth::force_refresh;
994 }
995}
996
997#[cfg(test)]
998mod oauth_login_guard_tests {
999 use super::*;
1000
1001 // Captured real IG demo v2 `/session` body (same shape as the existing
1002 // deserialization tests). Deserialized through the untagged
1003 // `SessionResponse` it lands on the V2 variant, so the derived session
1004 // carries no OAuth token — exactly the mismatch `login_oauth` must reject.
1005 const V2_BODY: &str = r#"{"accountType":"CFD","accountInfo":{"balance":21065.86,"deposit":3033.31,"profitLoss":-285.27,"available":16659.01},"currencyIsoCode":"EUR","currencySymbol":"E","currentAccountId":"ZZZZZ","lightstreamerEndpoint":"https://demo-apd.marketdatasystems.com","accounts":[{"accountId":"Z405P5","accountName":"Turbo24","preferred":false,"accountType":"PHYSICAL"},{"accountId":"ZHJ5N","accountName":"DEMO_A","preferred":false,"accountType":"CFD"},{"accountId":"ZZZZZ","accountName":"Opciones","preferred":true,"accountType":"CFD"}],"clientId":"101290216","timezoneOffset":1,"hasActiveDemoAccounts":true,"hasActiveLiveAccounts":true,"trailingStopsEnabled":false,"reroutingEnvironment":null,"dealingEnabled":true}"#;
1006
1007 #[test]
1008 fn test_ensure_oauth_session_v2_body_on_v3_path_yields_unauthorized()
1009 -> Result<(), serde_json::Error> {
1010 // Deserialize a v2-shaped body the way `login_oauth` does after a v3
1011 // request, then run it through the same guard.
1012 let response: SessionResponse = serde_json::from_str(V2_BODY)?;
1013 let session = response.get_session();
1014 // A v2 body carries no OAuth token.
1015 assert!(!session.is_oauth());
1016
1017 // The guard maps this to a typed error instead of panicking (the old
1018 // `assert!(session.is_oauth())` would have aborted here).
1019 match ensure_oauth_session(session) {
1020 Err(AppError::Unauthorized) => Ok(()),
1021 other => panic!("expected AppError::Unauthorized, got {other:?}"),
1022 }
1023 }
1024
1025 #[test]
1026 fn test_ensure_oauth_session_oauth_body_passes_through() {
1027 // A genuine v3 session passes the guard unchanged.
1028 let session = Session {
1029 account_id: "ACC123".to_string(),
1030 client_id: "CLIENT1".to_string(),
1031 lightstreamer_endpoint: "demo-apd.marketdatasystems.com".to_string(),
1032 cst: None,
1033 x_security_token: None,
1034 oauth_token: Some(OAuthToken {
1035 access_token: "ACCESS".to_string(),
1036 refresh_token: "REFRESH".to_string(),
1037 scope: "read write".to_string(),
1038 token_type: "Bearer".to_string(),
1039 expires_in: "60".to_string(),
1040 created_at: Utc::now(),
1041 }),
1042 api_version: 3,
1043 expires_at: 0,
1044 };
1045 assert!(ensure_oauth_session(session).is_ok());
1046 }
1047}
1048
1049#[cfg(test)]
1050mod redaction_tests {
1051 use super::*;
1052
1053 fn secret_session() -> Session {
1054 Session {
1055 account_id: "ACC123".to_string(),
1056 client_id: "CLIENT1".to_string(),
1057 lightstreamer_endpoint: "https://ls.example.com".to_string(),
1058 cst: Some("SECRET-CST-VALUE".to_string()),
1059 x_security_token: Some("SECRET-XST-VALUE".to_string()),
1060 oauth_token: Some(OAuthToken {
1061 access_token: "SECRET-ACCESS-VALUE".to_string(),
1062 refresh_token: "SECRET-REFRESH-VALUE".to_string(),
1063 scope: "read write".to_string(),
1064 token_type: "Bearer".to_string(),
1065 expires_in: "60".to_string(),
1066 created_at: chrono::Utc::now(),
1067 }),
1068 api_version: 3,
1069 expires_at: 0,
1070 }
1071 }
1072
1073 #[test]
1074 fn test_session_debug_redacts_tokens() {
1075 let session = secret_session();
1076 let rendered = format!("{session:?}");
1077
1078 assert!(!rendered.contains("SECRET-CST-VALUE"));
1079 assert!(!rendered.contains("SECRET-XST-VALUE"));
1080 assert!(!rendered.contains("SECRET-ACCESS-VALUE"));
1081 assert!(!rendered.contains("SECRET-REFRESH-VALUE"));
1082 assert!(rendered.contains("<redacted>"));
1083 // Non-secret fields stay visible.
1084 assert!(rendered.contains("ACC123"));
1085 assert!(rendered.contains("ls.example.com"));
1086 }
1087
1088 #[test]
1089 fn test_websocket_info_debug_redacts_tokens() {
1090 let ws = WebsocketInfo {
1091 server: "https://ls.example.com/lightstreamer".to_string(),
1092 cst: Some("SECRET-CST-VALUE".to_string()),
1093 x_security_token: Some("SECRET-XST-VALUE".to_string()),
1094 account_id: "ACC123".to_string(),
1095 };
1096 let rendered = format!("{ws:?}");
1097
1098 assert!(!rendered.contains("SECRET-CST-VALUE"));
1099 assert!(!rendered.contains("SECRET-XST-VALUE"));
1100 assert!(rendered.contains("Some(<redacted>)"));
1101 assert!(rendered.contains("ACC123"));
1102 assert!(rendered.contains("ls.example.com"));
1103 }
1104
1105 #[test]
1106 fn test_websocket_info_display_redacts_tokens() {
1107 let ws = WebsocketInfo {
1108 server: "https://ls.example.com/lightstreamer".to_string(),
1109 cst: Some("SECRET-CST-VALUE".to_string()),
1110 x_security_token: Some("SECRET-XST-VALUE".to_string()),
1111 account_id: "ACC123".to_string(),
1112 };
1113 let rendered = format!("{ws}");
1114
1115 assert!(!rendered.contains("SECRET-CST-VALUE"));
1116 assert!(!rendered.contains("SECRET-XST-VALUE"));
1117 assert!(rendered.contains("<redacted>"));
1118 assert!(rendered.contains("ACC123"));
1119
1120 // `None` tokens render as `None`, not as a redacted placeholder.
1121 let ws_none = WebsocketInfo {
1122 server: "https://ls.example.com/lightstreamer".to_string(),
1123 cst: None,
1124 x_security_token: None,
1125 account_id: "ACC123".to_string(),
1126 };
1127 assert!(format!("{ws_none}").contains("None"));
1128 }
1129}