rhood-core 0.2.0

Async Rust client library for the Robinhood trading API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
//! Login cascade and OAuth token refresh for [`RobinhoodClient`].
//!
//! Owns the multi-step login flow (cache → validate → refresh → headless OAuth),
//! token extraction/persistence, and SMS/email challenge response handling.

use super::{DEFAULT_TOKEN_TYPE, RobinhoodClient};
use crate::api::paths;
use crate::auth::{AuthState, CachedToken};
use crate::models::auth::{
    ChallengeResponsePayload, ChallengeResponseResult, LoginPayload, OAuthResponse,
    RefreshTokenPayload,
};
use crate::{ChallengeType, Result, RhoodError};
use chrono::Utc;
use secrecy::{ExposeSecret, SecretString};
use std::time::{SystemTime, SystemTimeError, UNIX_EPOCH};

impl RobinhoodClient {
    /// Unified login that cascades through all available authentication strategies.
    ///
    /// The cascade order is:
    /// 1. **Cache** - load token from disk
    /// 2. **Validate** - confirm the cached token is accepted by the server
    /// 3. **Refresh** - if validation fails, try refreshing the access token
    /// 4. **Headless** - if refresh fails, perform a full OAuth password grant
    ///
    /// If the headless login encounters a challenge (SMS/email), the error
    /// [`RhoodError::ChallengeRequired`] is returned with the challenge details.
    /// The caller should collect the code from the user and call
    /// [`submit_challenge_response()`](Self::submit_challenge_response) to complete authentication.
    ///
    /// # Arguments
    ///
    /// * `username` - Robinhood account email/username
    /// * `password` - Robinhood account password
    /// * `mfa_secret` - Optional base32-encoded TOTP secret for automated MFA
    ///
    /// # Errors
    ///
    /// Returns [`RhoodError::ChallengeRequired`] if SMS/email verification is needed.
    /// Returns [`RhoodError::DeviceVerificationRequired`] if push verification is needed
    /// (for push challenges, the library polls automatically during `login_headless`).
    /// Returns cache, transport, or API errors.
    ///
    /// In particular, an insecure token-cache file permission mode is returned
    /// so the caller can correct it before logging in again.
    pub async fn login(
        &self,
        username: &str,
        password: &str,
        mfa_secret: Option<&str>,
    ) -> Result<()> {
        // Step 1: Try loading from cache
        if let Some(cached) = self.token_cache.load()? {
            tracing::debug!("Found cached token, restoring auth state");
            self.device_token
                .write()
                .await
                .clone_from(&cached.device_token);
            *self.auth_state.write().await = AuthState::Authenticated {
                access_token: cached.access_token.clone(),
                token_type: cached.token_type.clone(),
                refresh_token: cached.refresh_token.clone(),
            };

            // Step 2: Validate cached token with a live API call
            match self.validate_token().await {
                Ok(true) => {
                    tracing::debug!("Cached token validated successfully");
                    return Ok(());
                }
                Ok(false) => {
                    tracing::debug!("Cached token rejected by server, trying refresh");
                }
                Err(err) => {
                    tracing::warn!(%err, "Token validation failed with error, trying refresh");
                }
            }

            // Step 3: Try refreshing the token
            match self.try_refresh_token().await {
                Ok(true) => {
                    tracing::debug!("Token refresh succeeded");
                    return Ok(());
                }
                Ok(false) => {
                    tracing::debug!("Token refresh failed, falling through to headless login");
                }
                Err(err) => {
                    tracing::warn!(%err, "Token refresh error, falling through to headless login");
                }
            }
        }

        // Step 4: Full headless login
        tracing::debug!("Attempting headless login");
        *self.auth_state.write().await = AuthState::Unauthenticated;
        self.login_headless(username, password, mfa_secret).await
    }

    /// Attempts to restore an authenticated session from the on-disk token cache.
    ///
    /// Loads the cached token, validates it with a live API call via
    /// [`validate_token()`](Self::validate_token), and on failure attempts
    /// to refresh it. Returns `true` if the client is now authenticated,
    /// `false` if all recovery strategies failed.
    ///
    /// # Errors
    ///
    /// Returns an error on I/O failures or HTTP transport errors.
    pub async fn login_from_cache(&self) -> Result<bool> {
        let Some(cached) = self.token_cache.load()? else {
            tracing::debug!("No cached token found");
            return Ok(false);
        };
        tracing::debug!("Found cached token, validating");
        self.device_token
            .write()
            .await
            .clone_from(&cached.device_token);
        *self.auth_state.write().await = AuthState::Authenticated {
            access_token: cached.access_token.clone(),
            token_type: cached.token_type.clone(),
            refresh_token: cached.refresh_token.clone(),
        };

        // Validate with a live API call
        match self.validate_token().await {
            Ok(true) => {
                tracing::debug!("Cached token is valid");
                return Ok(true);
            }
            Ok(false) => {
                tracing::debug!("Cached token validation failed, attempting refresh");
            }
            Err(err) => {
                tracing::debug!(%err, "Token validation error, attempting refresh");
            }
        }

        // Token validation failed so try to refresh before giving up
        if self.try_refresh_token().await? {
            tracing::debug!("Token refresh succeeded");
            return Ok(true);
        }

        tracing::debug!("Token refresh failed, clearing auth state");
        *self.auth_state.write().await = AuthState::Unauthenticated;
        Ok(false)
    }

    /// Validates the current access token by making a lightweight API call.
    ///
    /// Returns `Ok(true)` if the token is accepted by the server, `Ok(false)`
    /// if the server returns 401 or 403 (token revoked or invalid), and
    /// `Err` on network/transport errors.
    ///
    /// Uses `GET /positions/?nonzero=true` as the validation endpoint because
    /// it returns a small payload and is always available for authenticated users.
    pub async fn validate_token(&self) -> Result<bool> {
        let auth = match self.auth_state.read().await.authorization_header() {
            Some(header) => header,
            None => return Ok(false),
        };
        let url = self.api_url(paths::POSITIONS);
        let res = self
            .http
            .get(&url)
            .header("Authorization", &auth)
            .query(&[("nonzero", "true")])
            .send()
            .await?;
        let status = res.status().as_u16();
        Ok(status != 401 && status != 403 && res.status().is_success())
    }

    /// Attempt to refresh the access token using the stored refresh_token.
    ///
    /// Returns `Ok(true)` if refresh succeeded and state is now Authenticated.
    /// Returns `Ok(false)` if refresh failed gracefully (no refresh token, server
    /// rejection, or the refresh token itself has expired which is indicated by the
    /// server returning a `verification_workflow` in the response).
    async fn try_refresh_token(&self) -> Result<bool> {
        let refresh_token = match self.auth_state.read().await.refresh_token() {
            Some(rt) if !rt.expose_secret().is_empty() => rt.clone(),
            _ => return Ok(false),
        };

        let payload = RefreshTokenPayload {
            client_id: self.config.auth.client_id.clone(),
            grant_type: "refresh_token",
            refresh_token: refresh_token.expose_secret().to_string(),
            scope: "internal",
            device_token: self.device_token.read().await.clone(),
        };

        let token_url = self.api_url(paths::TOKEN);
        tracing::debug!("Attempting token refresh");
        let res = self.http.post(&token_url).form(&payload).send().await?;
        let status = res.status();
        let body = res.text().await.unwrap_or_default();
        tracing::debug!(
            status = status.as_u16(),
            body_len = body.len(),
            "Token refresh response"
        );

        if !status.is_success() {
            return Ok(false);
        }

        let data: OAuthResponse = serde_json::from_str(&body).map_err(|err| RhoodError::Api {
            status: status.as_u16(),
            message: format!("Failed to parse token refresh response: {err}"),
        })?;

        // If the refresh response contains a verification_workflow, the refresh
        // token itself has expired and a full re-authentication is required.
        // Return false to let the cascade fall through to headless login.
        if data.verification_workflow.is_some() {
            tracing::debug!("Refresh token expired (verification_workflow in response)");
            return Ok(false);
        }

        match self.extract_tokens(&data).await {
            Ok(()) => Ok(true),
            Err(_) => Ok(false),
        }
    }

    /// Submit the initial OAuth2 password grant. Sets `auth_state` based on
    /// the response (Authenticated, MfaRequired, DeviceVerification, or Challenged).
    pub async fn login_headless(
        &self,
        username: &str,
        password: &str,
        mfa_secret: Option<&str>,
    ) -> Result<()> {
        if self.login_from_cache().await? {
            return Ok(());
        }

        let mfa_code = if let Some(secret) = mfa_secret {
            let totp = totp_rs::Builder::new()
                .with_algorithm(totp_rs::Algorithm::SHA1)
                .with_digits(6)
                .with_skew(1)
                .with_step_duration(30)
                .with_secret(totp_rs::Secret::try_from_base32(secret).map_err(|err| {
                    RhoodError::InvalidParameter(format!("Invalid MFA secret: {err}"))
                })?)
                .build()
                .map_err(|err| RhoodError::InvalidParameter(format!("TOTP error: {err}")))?;
            // `Totp::generate_current` panics if the clock is before the Unix epoch;
            // reading the clock here keeps that a recoverable error, as it was before
            // totp-rs 6 moved the fallibility out of the return type.
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .map_err(|err: SystemTimeError| {
                    RhoodError::InvalidParameter(format!("TOTP generation failed: {err}"))
                })?
                .as_secs();
            Some(totp.generate(now).to_string())
        } else {
            None
        };

        let payload = LoginPayload {
            client_id: self.config.auth.client_id.clone(),
            expires_in: self.config.auth.token_expiry_secs.to_string(),
            grant_type: "password",
            username: username.to_string(),
            password: password.to_string(),
            scope: "internal",
            device_token: self.device_token.read().await.clone(),
            try_passkeys: "false",
            token_request_path: "/login",
            create_read_only_secondary_token: "true",
            mfa_code,
        };

        let token_url = self.api_url(paths::TOKEN);
        tracing::debug!(url = %token_url, "Sending login request");
        let res = self.http.post(&token_url).form(&payload).send().await?;
        let status = res.status();
        let body = res.text().await.unwrap_or_default();
        tracing::debug!(
            status = status.as_u16(),
            body_len = body.len(),
            "Login response"
        );

        let data: OAuthResponse = serde_json::from_str(&body).map_err(|err| {
            tracing::error!(status = status.as_u16(), "Failed to parse login response");
            RhoodError::Api {
                status: status.as_u16(),
                message: format!("Failed to parse login response: {err}"),
            }
        })?;

        // A non-success status is always an API error, regardless of any auth-shaped
        // fields in the response body. Preserve an API-provided detail when present.
        if !status.is_success() {
            if let Some(detail) = &data.detail {
                return Err(RhoodError::Api {
                    status: status.as_u16(),
                    message: detail.clone(),
                });
            }
            return Err(RhoodError::Api {
                status: status.as_u16(),
                message: format!(
                    "Login failed with no actionable response: {}",
                    super::transport::redacted_response_body_message(&body)
                ),
            });
        }

        // Surface API error detail when no actionable auth fields are present
        if data.access_token.is_none()
            && data.mfa_required.is_none()
            && data.verification_workflow.is_none()
            && data.challenge.is_none()
            && let Some(detail) = &data.detail
        {
            return Err(RhoodError::Api {
                status: status.as_u16(),
                message: detail.clone(),
            });
        }

        // Device verification: run the pathfinder flow, then retry login
        if let Some(workflow) = &data.verification_workflow {
            let workflow_id = workflow.id.clone();
            tracing::info!("Device verification required, approve on your Robinhood app");
            self.handle_device_verification(&workflow_id).await?;

            // Retry the original login after device is verified
            tracing::info!("Device verified, now completing login");
            let res = self.http.post(&token_url).form(&payload).send().await?;
            let retry_status = res.status();
            let retry_body = res.text().await.unwrap_or_default();
            tracing::debug!(
                status = retry_status.as_u16(),
                body_len = retry_body.len(),
                "Login retry response"
            );
            let data: OAuthResponse =
                serde_json::from_str(&retry_body).map_err(|err| RhoodError::Api {
                    status: retry_status.as_u16(),
                    message: format!("Failed to parse login retry response: {err}"),
                })?;
            if !retry_status.is_success() {
                if let Some(detail) = &data.detail {
                    return Err(RhoodError::Api {
                        status: retry_status.as_u16(),
                        message: detail.clone(),
                    });
                }
                return Err(RhoodError::Api {
                    status: retry_status.as_u16(),
                    message: format!(
                        "Login failed with no actionable response: {}",
                        super::transport::redacted_response_body_message(&retry_body)
                    ),
                });
            }
            return self
                .handle_login_response(&data, mfa_secret.is_none())
                .await;
        }

        self.handle_login_response(&data, mfa_secret.is_none())
            .await
    }

    /// Handle the OAuth2 response, transitioning auth_state appropriately.
    async fn handle_login_response(
        &self,
        data: &OAuthResponse,
        mfa_secret_absent: bool,
    ) -> Result<()> {
        // Device verification required (should not reach here from login_headless,
        // but kept as a fallback for direct callers)
        if let Some(workflow) = &data.verification_workflow {
            tracing::debug!(workflow_id = %workflow.id, "Device verification required");
            *self.auth_state.write().await = AuthState::DeviceVerification {
                workflow_id: workflow.id.clone(),
            };
            return Err(RhoodError::DeviceVerificationRequired);
        }

        // MFA challenge required
        if data.mfa_required == Some(true) {
            tracing::debug!("MFA required");
            *self.auth_state.write().await = AuthState::MfaRequired;
            if mfa_secret_absent {
                return Err(RhoodError::InvalidParameter(
                    "MFA required but no mfa_secret provided".into(),
                ));
            }
        }

        // SMS/email challenge
        if let Some(challenge) = &data.challenge {
            tracing::debug!(
                challenge_type = %challenge.challenge_type,
                challenge_id = %challenge.id,
                "Challenge required"
            );
            let challenge_type = match challenge.challenge_type.as_str() {
                "sms" => ChallengeType::Sms,
                "email" => ChallengeType::Email,
                _ => ChallengeType::Prompt,
            };
            *self.auth_state.write().await = AuthState::Challenged {
                challenge_type: challenge_type.clone(),
                challenge_id: challenge.id.clone(),
            };
            return Err(RhoodError::ChallengeRequired(challenge_type));
        }

        tracing::debug!("Extracting tokens from login response");
        self.extract_tokens(data).await
    }

    /// Extract access/refresh tokens from a successful OAuth2 response,
    /// transition to Authenticated, and persist to cache.
    async fn extract_tokens(&self, data: &OAuthResponse) -> Result<()> {
        let access_token =
            SecretString::from(
                data.access_token
                    .as_deref()
                    .ok_or_else(|| RhoodError::Api {
                        status: 401,
                        message: "No access_token in response".into(),
                    })?,
            );
        let token_type = data
            .token_type
            .as_deref()
            .unwrap_or(DEFAULT_TOKEN_TYPE)
            .to_string();
        let refresh_token = SecretString::from(data.refresh_token.as_deref().unwrap_or(""));

        *self.auth_state.write().await = AuthState::Authenticated {
            access_token: access_token.clone(),
            token_type: token_type.clone(),
            refresh_token: refresh_token.clone(),
        };

        #[expect(
            clippy::arithmetic_side_effects,
            reason = "the externally configured AuthConfig::token_expiry_secs value is assumed to fit a signed Unix timestamp; no in-code bound enforces this"
        )]
        let cached = CachedToken {
            access_token,
            refresh_token,
            token_type,
            device_token: self.device_token.read().await.clone(),
            expires_at: Some({
                Utc::now().timestamp() + self.config.auth.token_expiry_secs.cast_signed()
            }),
        };
        self.token_cache.save(&cached)?;
        Ok(())
    }

    /// Respond to an SMS/email challenge with the user-provided code.
    /// On success, transitions to Authenticated.
    pub async fn respond_to_challenge(&self, code: &str) -> Result<()> {
        let challenge_id = match &*self.auth_state.read().await {
            AuthState::Challenged { challenge_id, .. } => challenge_id.clone(),
            _ => {
                return Err(RhoodError::InvalidParameter(
                    "No pending challenge to respond to".into(),
                ));
            }
        };

        let url = format!("{}{challenge_id}/respond/", self.api_url(paths::CHALLENGE));
        let payload = ChallengeResponsePayload {
            response: code.to_string(),
        };

        let res = self.http.post(&url).form(&payload).send().await?;
        let data: ChallengeResponseResult = res.json().await?;
        tracing::debug!(body = ?data, "Challenge response");

        if data.status.as_deref() == Some("validated") {
            // Challenge validated so the caller should re-attempt login
            *self.auth_state.write().await = AuthState::Unauthenticated;
            Ok(())
        } else {
            Err(RhoodError::Api {
                status: 400,
                message: "Challenge response not validated".into(),
            })
        }
    }

    /// Respond to an SMS/email challenge and re-attempt login.
    ///
    /// This is the full challenge-response flow:
    /// 1. POSTs the user-provided code to the challenge endpoint
    /// 2. If validated, re-attempts login with the provided credentials
    /// 3. On success, transitions to `Authenticated` and caches tokens
    ///
    /// The caller must provide the original login credentials because the
    /// challenge response only validates the device. A fresh OAuth password
    /// grant is still required to obtain tokens.
    ///
    /// # Errors
    ///
    /// Returns [`RhoodError::InvalidParameter`] if no challenge is pending.
    /// Returns [`RhoodError::Api`] if the challenge response is rejected.
    /// Returns any login error from the re-attempted `login_headless()` call.
    pub async fn submit_challenge_response(
        &self,
        challenge_id: &str,
        code: &str,
        username: &str,
        password: &str,
        mfa_secret: Option<&str>,
    ) -> Result<()> {
        // Step 1: Submit the challenge response
        let url = format!("{}{challenge_id}/respond/", self.api_url(paths::CHALLENGE));
        let payload = ChallengeResponsePayload {
            response: code.to_string(),
        };

        let res = self.http.post(&url).form(&payload).send().await?;
        let data: ChallengeResponseResult = res.json().await?;
        tracing::debug!(body = ?data, "Challenge response");

        if data.status.as_deref() != Some("validated") {
            return Err(RhoodError::Api {
                status: 400,
                message: "Challenge response not validated".into(),
            });
        }

        // Step 2: Challenge validated so re-attempt login
        tracing::debug!("Challenge validated, re-attempting login");
        *self.auth_state.write().await = AuthState::Unauthenticated;
        self.login_headless(username, password, mfa_secret).await
    }
}

#[cfg(test)]
#[expect(
    clippy::let_underscore_must_use,
    reason = "compile-only async helpers prove public method signatures without executing requests"
)]
mod tests {
    use super::super::{default_oauth_response, test_config, test_config_with_tempdir};
    use super::*;
    use crate::models::auth::{ChallengeDetail, VerificationWorkflow};
    use secrecy::ExposeSecret;
    use wiremock::matchers::{body_string_contains, header, method, path, query_param};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[cfg(unix)]
    fn set_mode(path: &std::path::Path, mode: u32) {
        use std::os::unix::fs::PermissionsExt;

        std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap();
    }

    async fn client_for_server(base_url: &str) -> (tempfile::TempDir, RobinhoodClient) {
        let dir = tempfile::tempdir().unwrap();
        let mut config = test_config_with_tempdir(&dir);
        config.api.base_url = base_url.to_string();
        let client = RobinhoodClient::with_config(config).unwrap();
        (dir, client)
    }

    async fn authenticated_client_for_server(
        base_url: &str,
        refresh_token: &str,
    ) -> (tempfile::TempDir, RobinhoodClient) {
        let (dir, client) = client_for_server(base_url).await;
        *client.auth_state.write().await = AuthState::Authenticated {
            access_token: SecretString::from("old-access"),
            token_type: "Bearer".to_string(),
            refresh_token: SecretString::from(refresh_token),
        };
        (dir, client)
    }

    #[tokio::test]
    async fn handle_login_response_device_verification() {
        let dir = tempfile::tempdir().unwrap();
        let client = RobinhoodClient::with_config(test_config_with_tempdir(&dir)).unwrap();
        let data = OAuthResponse {
            verification_workflow: Some(VerificationWorkflow {
                id: "wf-abc".into(),
                _workflow_status: None,
            }),
            ..default_oauth_response()
        };
        let err = client.handle_login_response(&data, true).await.unwrap_err();
        assert!(matches!(err, RhoodError::DeviceVerificationRequired));
        assert!(matches!(
            client.auth_state().await,
            AuthState::DeviceVerification { workflow_id } if workflow_id == "wf-abc"
        ));
    }

    #[tokio::test]
    async fn handle_login_response_mfa_required() {
        let dir = tempfile::tempdir().unwrap();
        let client = RobinhoodClient::with_config(test_config_with_tempdir(&dir)).unwrap();
        let data = OAuthResponse {
            mfa_required: Some(true),
            ..default_oauth_response()
        };
        let err = client.handle_login_response(&data, true).await.unwrap_err();
        assert!(matches!(err, RhoodError::InvalidParameter(_)));
        assert!(matches!(client.auth_state().await, AuthState::MfaRequired));
    }

    #[tokio::test]
    async fn handle_login_response_challenge() {
        let dir = tempfile::tempdir().unwrap();
        let client = RobinhoodClient::with_config(test_config_with_tempdir(&dir)).unwrap();
        let data = OAuthResponse {
            challenge: Some(ChallengeDetail {
                id: "ch-123".into(),
                challenge_type: "sms".into(),
                _status: Some("issued".into()),
            }),
            ..default_oauth_response()
        };
        let err = client.handle_login_response(&data, true).await.unwrap_err();
        assert!(matches!(
            err,
            RhoodError::ChallengeRequired(ChallengeType::Sms)
        ));
        assert!(matches!(
            client.auth_state().await,
            AuthState::Challenged {
                challenge_type: ChallengeType::Sms,
                ..
            }
        ));
    }

    #[test]
    fn login_method_signature_exists() {
        async fn _assert_login(client: &RobinhoodClient) {
            let _ = client.login("user", "pass", None).await;
        }
    }

    #[test]
    fn submit_challenge_response_signature_exists() {
        async fn _assert_method_exists(client: &RobinhoodClient) {
            let _ = client
                .submit_challenge_response("test-id", "123456", "user", "pass", None)
                .await;
        }
    }

    #[test]
    fn refresh_response_with_verification_workflow_is_detected() {
        let data = OAuthResponse {
            verification_workflow: Some(VerificationWorkflow {
                id: "wf-expired".into(),
                _workflow_status: None,
            }),
            ..default_oauth_response()
        };
        assert!(data.verification_workflow.is_some());
        assert!(data.access_token.is_none());
    }

    #[tokio::test]
    async fn respond_to_challenge_requires_challenged_state() {
        let dir = tempfile::tempdir().unwrap();
        let client = RobinhoodClient::with_config(test_config_with_tempdir(&dir)).unwrap();
        let err = client.respond_to_challenge("123456").await.unwrap_err();
        assert!(matches!(err, RhoodError::InvalidParameter(_)));
    }

    #[test]
    fn submit_challenge_response_requires_credentials() {
        async fn _check(client: &RobinhoodClient) {
            // 5 params: challenge_id, code, username, password, mfa_secret
            let _ = client
                .submit_challenge_response("id", "code", "user", "pass", None)
                .await;
        }
    }

    #[test]
    fn login_cascade_method_exists() {
        async fn _check(client: &RobinhoodClient) {
            let _ = client.login("user", "pass", Some("secret")).await;
            let _ = client.login("user", "pass", None).await;
        }
    }

    #[tokio::test]
    async fn validate_token_returns_false_when_unauthenticated() {
        let dir = tempfile::tempdir().unwrap();
        let client = RobinhoodClient::with_config(test_config_with_tempdir(&dir)).unwrap();
        let result = client.validate_token().await.unwrap();
        assert!(
            !result,
            "validate_token should return false when unauthenticated"
        );
    }

    #[tokio::test]
    async fn validate_token_returns_true_for_successful_positions_probe() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/positions/"))
            .and(query_param("nonzero", "true"))
            .and(header("Authorization", "Bearer old-access"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "results": []
            })))
            .mount(&server)
            .await;
        let (_dir, client) = authenticated_client_for_server(&server.uri(), "refresh").await;

        assert!(client.validate_token().await.unwrap());
    }

    #[tokio::test]
    async fn validate_token_returns_false_for_unauthorized_probe() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/positions/"))
            .and(query_param("nonzero", "true"))
            .respond_with(ResponseTemplate::new(401).set_body_string("unauthorized"))
            .mount(&server)
            .await;
        let (_dir, client) = authenticated_client_for_server(&server.uri(), "refresh").await;

        assert!(!client.validate_token().await.unwrap());
    }

    #[tokio::test]
    async fn try_refresh_token_returns_false_without_refresh_token() {
        let server = MockServer::start().await;
        let (_dir, client) = authenticated_client_for_server(&server.uri(), "").await;

        assert!(!client.try_refresh_token().await.unwrap());
    }

    #[tokio::test]
    async fn try_refresh_token_updates_auth_state_and_cache_on_success() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/oauth2/token/"))
            .and(body_string_contains("grant_type=refresh_token"))
            .and(body_string_contains("refresh_token=old-refresh"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "access_token": "new-access",
                "token_type": "Token",
                "refresh_token": "new-refresh"
            })))
            .mount(&server)
            .await;
        let (dir, client) = authenticated_client_for_server(&server.uri(), "old-refresh").await;

        assert!(client.try_refresh_token().await.unwrap());
        let state = client.auth_state().await;
        assert_eq!(
            state.authorization_header().as_deref(),
            Some("Token new-access")
        );

        let cache = client.token_cache.load().unwrap().unwrap();
        assert_eq!(cache.access_token.expose_secret(), "new-access");
        drop(dir);
    }

    #[tokio::test]
    async fn try_refresh_token_returns_false_on_server_rejection() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/oauth2/token/"))
            .respond_with(ResponseTemplate::new(400).set_body_string("bad refresh"))
            .mount(&server)
            .await;
        let (_dir, client) = authenticated_client_for_server(&server.uri(), "old-refresh").await;

        assert!(!client.try_refresh_token().await.unwrap());
        assert_eq!(
            client.auth_state().await.authorization_header().as_deref(),
            Some("Bearer old-access")
        );
    }

    #[tokio::test]
    async fn try_refresh_token_returns_false_when_refresh_requires_verification() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/oauth2/token/"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "verification_workflow": {
                    "id": "wf-expired",
                    "workflow_status": "issued"
                }
            })))
            .mount(&server)
            .await;
        let (_dir, client) = authenticated_client_for_server(&server.uri(), "old-refresh").await;

        assert!(!client.try_refresh_token().await.unwrap());
    }

    #[tokio::test]
    async fn login_from_cache_restores_valid_cached_token() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/positions/"))
            .and(query_param("nonzero", "true"))
            .and(header("Authorization", "Bearer cached-access"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "results": []
            })))
            .mount(&server)
            .await;
        let dir = tempfile::tempdir().unwrap();
        let cache_path = dir.path().join("token.json");
        let mut config = test_config(cache_path.to_str().unwrap());
        config.api.base_url = server.uri();
        let client = RobinhoodClient::with_config(config).unwrap();
        client
            .token_cache
            .save(&CachedToken {
                access_token: SecretString::from("cached-access"),
                refresh_token: SecretString::from("cached-refresh"),
                token_type: "Bearer".into(),
                device_token: "cached-device".into(),
                expires_at: Some(Utc::now().timestamp() + 60),
            })
            .unwrap();

        assert!(client.login_from_cache().await.unwrap());
        assert_eq!(
            client.auth_state().await.authorization_header().as_deref(),
            Some("Bearer cached-access")
        );
        assert_eq!(&*client.device_token.read().await, "cached-device");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn login_restores_owner_only_cached_token() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/positions/"))
            .and(query_param("nonzero", "true"))
            .and(header("Authorization", "Bearer cached-access"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "results": []
            })))
            .mount(&server)
            .await;
        let dir = tempfile::tempdir().unwrap();
        let cache_path = dir.path().join("token.json");
        let mut config = test_config(cache_path.to_str().unwrap());
        config.api.base_url = server.uri();
        let client = RobinhoodClient::with_config(config).unwrap();
        client
            .token_cache
            .save(&CachedToken {
                access_token: SecretString::from("cached-access"),
                refresh_token: SecretString::from("cached-refresh"),
                token_type: "Bearer".into(),
                device_token: "cached-device".into(),
                expires_at: Some(Utc::now().timestamp() + 60),
            })
            .unwrap();
        set_mode(&cache_path, 0o600);

        client.login("user", "pass", None).await.unwrap();

        assert_eq!(
            client.auth_state().await.authorization_header().as_deref(),
            Some("Bearer cached-access")
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn login_rejects_world_readable_cached_token() {
        let dir = tempfile::tempdir().unwrap();
        let cache_path = dir.path().join("token.json");
        let client =
            RobinhoodClient::with_config(test_config(cache_path.to_str().unwrap())).unwrap();
        client
            .token_cache
            .save(&CachedToken {
                access_token: SecretString::from("cached-access"),
                refresh_token: SecretString::from("cached-refresh"),
                token_type: "Bearer".into(),
                device_token: "cached-device".into(),
                expires_at: Some(Utc::now().timestamp() + 60),
            })
            .unwrap();
        set_mode(&cache_path, 0o644);

        let error = client.login("user", "pass", None).await.unwrap_err();

        assert!(
            error
                .to_string()
                .contains(&cache_path.display().to_string())
        );
        assert!(error.to_string().contains("chmod 600"));
    }

    #[tokio::test]
    async fn login_falls_through_when_cache_is_absent() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/oauth2/token/"))
            .and(body_string_contains("grant_type=password"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "access_token": "login-access",
                "token_type": "Bearer",
                "refresh_token": "login-refresh"
            })))
            .mount(&server)
            .await;
        let dir = tempfile::tempdir().unwrap();
        let cache_path = dir.path().join("token.json");
        let mut config = test_config(cache_path.to_str().unwrap());
        config.api.base_url = server.uri();
        let client = RobinhoodClient::with_config(config).unwrap();

        client.login("user", "pass", None).await.unwrap();

        assert_eq!(
            client.auth_state().await.authorization_header().as_deref(),
            Some("Bearer login-access")
        );
    }

    #[tokio::test]
    async fn login_headless_surfaces_api_detail_when_no_actionable_fields_exist() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/oauth2/token/"))
            .respond_with(ResponseTemplate::new(400).set_body_json(serde_json::json!({
                "detail": "invalid login"
            })))
            .mount(&server)
            .await;
        let (_dir, client) = client_for_server(&server.uri()).await;

        let err = client
            .login_headless("user", "pass", None)
            .await
            .unwrap_err();

        assert!(matches!(
            err,
            RhoodError::Api {
                status: 400,
                message
            } if message == "invalid login"
        ));
    }

    #[tokio::test]
    async fn login_headless_rejects_non_success_response_with_access_token() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/oauth2/token/"))
            .respond_with(ResponseTemplate::new(500).set_body_json(serde_json::json!({
                "access_token": "server-error-token"
            })))
            .mount(&server)
            .await;
        let (_dir, client) = client_for_server(&server.uri()).await;

        let err = client
            .login_headless("user", "pass", None)
            .await
            .unwrap_err();

        assert!(matches!(
            err,
            RhoodError::Api {
                status: 500,
                message
            } if message.contains("Login failed with no actionable response")
                && !message.contains("server-error-token")
        ));
        assert!(!client.is_authenticated().await);
    }

    #[tokio::test]
    async fn login_headless_handles_mfa_required_on_successful_response() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/oauth2/token/"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "mfa_required": true
            })))
            .mount(&server)
            .await;
        let (_dir, client) = client_for_server(&server.uri()).await;

        let err = client
            .login_headless("user", "pass", None)
            .await
            .unwrap_err();

        assert!(matches!(err, RhoodError::InvalidParameter(_)));
        assert!(matches!(client.auth_state().await, AuthState::MfaRequired));
    }

    #[tokio::test]
    async fn login_headless_handles_challenge_on_successful_password_grant() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/oauth2/token/"))
            .and(body_string_contains("grant_type=password"))
            .and(body_string_contains("username=user"))
            .and(body_string_contains("password=pass"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "challenge": {
                    "id": "ch-login-1",
                    "type": "sms",
                    "status": "issued"
                }
            })))
            .mount(&server)
            .await;
        let (_dir, client) = client_for_server(&server.uri()).await;

        let err = client
            .login_headless("user", "pass", None)
            .await
            .unwrap_err();

        assert!(matches!(
            err,
            RhoodError::ChallengeRequired(ChallengeType::Sms)
        ));
        assert!(matches!(
            client.auth_state().await,
            AuthState::Challenged {
                challenge_type: ChallengeType::Sms,
                challenge_id,
            } if challenge_id == "ch-login-1"
        ));
    }

    #[tokio::test]
    async fn login_headless_rejects_non_success_retry_with_access_token() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/oauth2/token/"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "verification_workflow": {
                    "id": "wf-1",
                    "workflow_status": "issued"
                }
            })))
            .up_to_n_times(1)
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/pathfinder/user_machine/"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "machine-1"
            })))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/pathfinder/inquiries/machine-1/user_view/"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "context": {
                    "sheriff_challenge": {
                        "id": "challenge-1",
                        "type": "prompt",
                        "status": "validated"
                    }
                },
                "type_context": null
            })))
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/pathfinder/inquiries/machine-1/user_view/"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "context": null,
                "type_context": {
                    "result": "workflow_status_approved"
                }
            })))
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/oauth2/token/"))
            .respond_with(ResponseTemplate::new(502).set_body_json(serde_json::json!({
                "access_token": "retry-error-token"
            })))
            .mount(&server)
            .await;
        let (_dir, client) = client_for_server(&server.uri()).await;

        let err = client
            .login_headless("user", "pass", None)
            .await
            .unwrap_err();

        assert!(matches!(
            err,
            RhoodError::Api {
                status: 502,
                message
            } if message.contains("Login failed with no actionable response")
                && !message.contains("retry-error-token")
        ));
        assert!(!client.is_authenticated().await);
    }

    #[tokio::test]
    async fn login_headless_extracts_tokens_on_successful_password_grant() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/oauth2/token/"))
            .and(body_string_contains("grant_type=password"))
            .and(body_string_contains("username=user"))
            .and(body_string_contains("password=pass"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "access_token": "login-access",
                "token_type": "Bearer",
                "refresh_token": "login-refresh"
            })))
            .mount(&server)
            .await;
        let (_dir, client) = client_for_server(&server.uri()).await;

        client.login_headless("user", "pass", None).await.unwrap();

        assert_eq!(
            client.auth_state().await.authorization_header().as_deref(),
            Some("Bearer login-access")
        );
    }

    #[tokio::test]
    async fn respond_to_challenge_validated_resets_to_unauthenticated() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/challenge/ch-1/respond/"))
            .and(body_string_contains("response=123456"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "status": "validated"
            })))
            .mount(&server)
            .await;
        let (_dir, client) = client_for_server(&server.uri()).await;
        *client.auth_state.write().await = AuthState::Challenged {
            challenge_type: ChallengeType::Sms,
            challenge_id: "ch-1".into(),
        };

        client.respond_to_challenge("123456").await.unwrap();

        assert!(matches!(
            client.auth_state().await,
            AuthState::Unauthenticated
        ));
    }

    #[tokio::test]
    async fn submit_challenge_response_rejects_unvalidated_status_before_retrying_login() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/challenge/ch-1/respond/"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "status": "pending"
            })))
            .mount(&server)
            .await;
        let (_dir, client) = client_for_server(&server.uri()).await;

        let err = client
            .submit_challenge_response("ch-1", "123456", "user", "pass", None)
            .await
            .unwrap_err();

        assert!(matches!(
            err,
            RhoodError::Api {
                status: 400,
                message
            } if message == "Challenge response not validated"
        ));
    }

    #[tokio::test]
    async fn handle_login_response_email_challenge() {
        let dir = tempfile::tempdir().unwrap();
        let client = RobinhoodClient::with_config(test_config_with_tempdir(&dir)).unwrap();
        let data = OAuthResponse {
            challenge: Some(ChallengeDetail {
                id: "ch-email-1".into(),
                challenge_type: "email".into(),
                _status: Some("issued".into()),
            }),
            ..default_oauth_response()
        };
        let err = client.handle_login_response(&data, true).await.unwrap_err();
        assert!(matches!(
            err,
            RhoodError::ChallengeRequired(ChallengeType::Email)
        ));
        assert!(matches!(
            client.auth_state().await,
            AuthState::Challenged {
                challenge_type: ChallengeType::Email,
                challenge_id,
            } if challenge_id == "ch-email-1"
        ));
    }

    #[tokio::test]
    async fn handle_login_response_prompt_challenge() {
        let dir = tempfile::tempdir().unwrap();
        let client = RobinhoodClient::with_config(test_config_with_tempdir(&dir)).unwrap();
        let data = OAuthResponse {
            challenge: Some(ChallengeDetail {
                id: "ch-prompt-1".into(),
                challenge_type: "prompt".into(),
                _status: Some("issued".into()),
            }),
            ..default_oauth_response()
        };
        let err = client.handle_login_response(&data, true).await.unwrap_err();
        assert!(matches!(
            err,
            RhoodError::ChallengeRequired(ChallengeType::Prompt)
        ));
    }

    #[tokio::test]
    async fn extract_tokens_success() {
        let dir = tempfile::tempdir().unwrap();
        let cache_path = dir.path().join("tokens.json");
        let client =
            RobinhoodClient::with_config(test_config(cache_path.to_str().unwrap())).unwrap();

        let data = OAuthResponse {
            access_token: Some("access123".into()),
            token_type: Some("Bearer".into()),
            refresh_token: Some("refresh456".into()),
            ..default_oauth_response()
        };
        client.extract_tokens(&data).await.unwrap();

        assert!(client.is_authenticated().await);
        assert_eq!(
            client.auth_state().await.authorization_header().unwrap(),
            "Bearer access123"
        );
        // Verify token was cached to disk
        assert!(cache_path.exists());
    }

    #[tokio::test]
    async fn extract_tokens_missing_access_token() {
        let dir = tempfile::tempdir().unwrap();
        let client = RobinhoodClient::with_config(test_config_with_tempdir(&dir)).unwrap();
        let data = default_oauth_response();
        let err = client.extract_tokens(&data).await.unwrap_err();
        assert!(matches!(err, RhoodError::Api { status: 401, .. }));
    }

    #[tokio::test]
    async fn extract_tokens_default_token_type() {
        let dir = tempfile::tempdir().unwrap();
        let cache_path = dir.path().join("tokens.json");
        let client =
            RobinhoodClient::with_config(test_config(cache_path.to_str().unwrap())).unwrap();

        let data = OAuthResponse {
            access_token: Some("tok".into()),
            token_type: None, // Should default to "Bearer"
            refresh_token: Some("ref".into()),
            ..default_oauth_response()
        };
        client.extract_tokens(&data).await.unwrap();
        assert_eq!(
            client.auth_state().await.authorization_header().unwrap(),
            "Bearer tok"
        );
    }
}