bitwarden-auth 3.0.0

Internal crate for the bitwarden crate. Do not use.
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
use bitwarden_core::Client;
#[cfg(feature = "wasm")]
use wasm_bindgen::prelude::*;

use crate::send_access::{
    SendAccessTokenError, SendAccessTokenRequest, SendAccessTokenResponse,
    access_token_response::UnexpectedIdentityError,
    api::{
        SendAccessTokenApiErrorResponse, SendAccessTokenApiSuccessResponse,
        SendAccessTokenRequestPayload,
    },
};

/// The `SendAccessClient` is used to interact with the Bitwarden API to get send access tokens.
#[derive(Clone)]
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub struct SendAccessClient {
    pub(crate) client: Client,
}

impl SendAccessClient {
    pub(crate) fn new(client: Client) -> Self {
        Self { client }
    }
}

#[cfg_attr(feature = "wasm", wasm_bindgen)]
impl SendAccessClient {
    /// Requests a new send access token.
    pub async fn request_send_access_token(
        &self,
        request: SendAccessTokenRequest,
    ) -> Result<SendAccessTokenResponse, SendAccessTokenError> {
        // Convert the request to the appropriate format for sending.
        let payload: SendAccessTokenRequestPayload = request.into();

        // When building other identity token requests, we used to send credentials: "include" on
        // non-web clients or if the env had a base URL. See client's
        // apiService.getCredentials() for example. However, it doesn't seem necessary for
        // this request, so we are not including it here. If needed, we can revisit this and
        // add it back in.

        let configurations = self.client.internal.get_api_configurations();

        // save off url in variable for re-use
        let url = format!(
            "{}/connect/token",
            &configurations.identity_config.base_path
        );

        let request: reqwest_middleware::RequestBuilder = configurations
            .identity_config
            .client
            .post(&url)
            .header(reqwest::header::ACCEPT, "application/json")
            .header(reqwest::header::CACHE_CONTROL, "no-store")
            .form(&payload);

        // Because of the ? operator, any errors from sending the request are automatically
        // wrapped in SendAccessTokenError::Unexpected as an UnexpectedIdentityError::Reqwest
        // variant and returned.
        // note: we had to manually built a trait to map reqwest::Error to SendAccessTokenError.
        let response: reqwest::Response = request.send().await?;

        let response_status = response.status();

        // handle success and error responses
        // If the response is 2xx, we can deserialize it into SendAccessToken
        if response_status.is_success() {
            let send_access_token: SendAccessTokenApiSuccessResponse = response.json().await?;
            return Ok(send_access_token.into());
        }

        let err_response = match response.json::<SendAccessTokenApiErrorResponse>().await {
            // If the response is a 400 with a specific error type, we can deserialize it into
            // SendAccessTokenApiErrorResponse and then convert it into
            // SendAccessTokenError::Expected later on.
            Ok(err) => err,
            Err(_) => {
                // This handles any 4xx that aren't specifically handled above
                // as well as any other non-2xx responses (5xx, etc).

                let error_string = format!(
                    "Received response status {} against {}",
                    response_status, url
                );

                return Err(SendAccessTokenError::Unexpected(UnexpectedIdentityError(
                    error_string,
                )));
            }
        };

        Err(SendAccessTokenError::Expected(err_response))
    }
}

#[cfg(test)]
mod tests {
    use bitwarden_core::{Client as CoreClient, ClientSettings, DeviceType};
    use bitwarden_test::start_api_mock;
    use wiremock::{
        Mock, MockServer, ResponseTemplate,
        matchers::{self, body_string_contains},
    };

    use crate::{
        AuthClientExt,
        api::enums::{GrantType, Scope},
        send_access::{
            SendAccessClient, SendAccessCredentials, SendAccessTokenError, SendAccessTokenRequest,
            SendAccessTokenResponse, SendEmailCredentials, SendEmailOtpCredentials,
            SendPasswordCredentials, UnexpectedIdentityError,
            api::{
                SendAccessTokenApiErrorResponse, SendAccessTokenInvalidGrantError,
                SendAccessTokenInvalidRequestError,
            },
        },
    };

    fn make_send_client(mock_server: &MockServer) -> SendAccessClient {
        let settings = ClientSettings {
            identity_url: format!("http://{}/identity", mock_server.address()),
            api_url: format!("http://{}/api", mock_server.address()),
            user_agent: "Bitwarden Rust-SDK [TEST]".into(),
            device_type: DeviceType::SDK,
            device_identifier: None,
            bitwarden_client_version: None,
            bitwarden_package_type: None,
        };
        let core_client = CoreClient::new(Some(settings));
        core_client.auth_new().send_access()
    }

    mod request_send_access_token_success_tests {

        use super::*;

        #[tokio::test]
        async fn request_send_access_token_anon_send_success() {
            let scope_value = serde_json::to_value(Scope::ApiSendAccess).unwrap();
            let scope_str = scope_value.as_str().unwrap();

            let grant_type_value = serde_json::to_value(GrantType::SendAccess).unwrap();
            let grant_type_str = grant_type_value.as_str().unwrap();

            // Create a mock success response
            let raw_success = serde_json::json!({
                "access_token": "token",
                "token_type": "bearer",
                "expires_in":   3600,
                "scope": scope_str
            });

            // Construct the real Request type
            let req = SendAccessTokenRequest {
                send_id: "test_send_id".into(),
                send_access_credentials: None, // No credentials for this test
            };

            let mock = Mock::given(matchers::method("POST"))
                .and(matchers::path("identity/connect/token"))
                // expect the headers we set in the client
                .and(matchers::header(
                    reqwest::header::CONTENT_TYPE.as_str(),
                    "application/x-www-form-urlencoded",
                ))
                .and(matchers::header(
                    reqwest::header::ACCEPT.as_str(),
                    "application/json",
                ))
                .and(matchers::header(
                    reqwest::header::CACHE_CONTROL.as_str(),
                    "no-store",
                ))
                // expect the body to contain the fields we set in our payload object
                .and(body_string_contains("client_id=send"))
                .and(body_string_contains(format!(
                    "grant_type={}",
                    grant_type_str
                )))
                .and(body_string_contains(format!("scope={}", scope_str)))
                .and(body_string_contains(format!("send_id={}", req.send_id)))
                // respond with the mock success response
                .respond_with(ResponseTemplate::new(200).set_body_json(raw_success));

            // Spin up a server and register mock with it
            let (mock_server, _api_config) = start_api_mock(vec![mock]).await;

            // Create a send access client
            let send_access_client = make_send_client(&mock_server);

            let token: SendAccessTokenResponse = send_access_client
                .request_send_access_token(req)
                .await
                .unwrap();

            assert_eq!(token.token, "token");
            assert!(token.expires_at > 0);
        }

        #[tokio::test]
        async fn request_send_access_token_password_protected_send_success() {
            let scope_value = serde_json::to_value(Scope::ApiSendAccess).unwrap();
            let scope_str = scope_value.as_str().unwrap();

            let grant_type_value = serde_json::to_value(GrantType::SendAccess).unwrap();
            let grant_type_str = grant_type_value.as_str().unwrap();

            // Create a mock success response
            let raw_success = serde_json::json!({
                "access_token": "token",
                "token_type": "bearer",
                "expires_in":   3600,
                "scope": scope_str
            });

            let password_hash_b64 = "valid-hash";

            let password_credentials = SendPasswordCredentials {
                password_hash_b64: password_hash_b64.into(),
            };

            let req = SendAccessTokenRequest {
                send_id: "valid-send-id".into(),
                send_access_credentials: Some(SendAccessCredentials::Password(
                    password_credentials,
                )),
            };

            let mock = Mock::given(matchers::method("POST"))
                .and(matchers::path("identity/connect/token"))
                // expect the headers we set in the client
                .and(matchers::header(
                    reqwest::header::CONTENT_TYPE.as_str(),
                    "application/x-www-form-urlencoded",
                ))
                .and(matchers::header(
                    reqwest::header::ACCEPT.as_str(),
                    "application/json",
                ))
                .and(matchers::header(
                    reqwest::header::CACHE_CONTROL.as_str(),
                    "no-store",
                ))
                // expect the body to contain the fields we set in our payload object
                .and(body_string_contains("client_id=send"))
                .and(body_string_contains(format!(
                    "grant_type={}",
                    grant_type_str
                )))
                .and(body_string_contains(format!("scope={}", scope_str)))
                .and(body_string_contains(format!("send_id={}", req.send_id)))
                .and(body_string_contains(format!(
                    "password_hash_b64={}",
                    password_hash_b64
                )))
                // respond with the mock success response
                .respond_with(ResponseTemplate::new(200).set_body_json(raw_success));

            // Spin up a server and register mock with it
            let (mock_server, _api_config) = start_api_mock(vec![mock]).await;

            // Create a send access client
            let send_access_client = make_send_client(&mock_server);

            let token: SendAccessTokenResponse = send_access_client
                .request_send_access_token(req)
                .await
                .unwrap();

            assert_eq!(token.token, "token");
            assert!(token.expires_at > 0);
        }

        #[tokio::test]
        async fn request_send_access_token_email_otp_protected_send_success() {
            let scope_value = serde_json::to_value(Scope::ApiSendAccess).unwrap();
            let scope_str = scope_value.as_str().unwrap();

            let grant_type_value = serde_json::to_value(GrantType::SendAccess).unwrap();
            let grant_type_str = grant_type_value.as_str().unwrap();

            // Create a mock success response
            let raw_success = serde_json::json!({
                "access_token": "token",
                "token_type": "bearer",
                "expires_in":   3600,
                "scope": scope_str
            });

            let email = "valid@email.com";
            let otp: &str = "valid_otp";

            let email_otp_credentials = SendEmailOtpCredentials {
                email: email.into(),
                otp: otp.into(),
            };

            let req = SendAccessTokenRequest {
                send_id: "valid-send-id".into(),
                send_access_credentials: Some(SendAccessCredentials::EmailOtp(
                    email_otp_credentials,
                )),
            };

            let mock = Mock::given(matchers::method("POST"))
                .and(matchers::path("identity/connect/token"))
                // expect the headers we set in the client
                .and(matchers::header(
                    reqwest::header::CONTENT_TYPE.as_str(),
                    "application/x-www-form-urlencoded",
                ))
                .and(matchers::header(
                    reqwest::header::ACCEPT.as_str(),
                    "application/json",
                ))
                .and(matchers::header(
                    reqwest::header::CACHE_CONTROL.as_str(),
                    "no-store",
                ))
                // expect the body to contain the fields we set in our payload object
                .and(body_string_contains("client_id=send"))
                .and(body_string_contains(format!(
                    "grant_type={}",
                    grant_type_str
                )))
                .and(body_string_contains(format!("scope={}", scope_str)))
                .and(body_string_contains(format!("send_id={}", req.send_id)))
                .and(body_string_contains("email=valid%40email.com"))
                .and(body_string_contains(format!("otp={}", otp)))
                // respond with the mock success response
                .respond_with(ResponseTemplate::new(200).set_body_json(raw_success));

            // Spin up a server and register mock with it
            let (mock_server, _api_config) = start_api_mock(vec![mock]).await;

            // Create a send access client
            let send_access_client = make_send_client(&mock_server);

            let token: SendAccessTokenResponse = send_access_client
                .request_send_access_token(req)
                .await
                .unwrap();

            assert_eq!(token.token, "token");
            assert!(token.expires_at > 0);
        }
    }

    mod request_send_access_token_invalid_request_tests {
        use super::*;

        #[tokio::test]
        async fn request_send_access_token_invalid_request_send_id_required_error() {
            // Create a mock error response
            let error_description = "send_id is required.".into();
            let raw_error = serde_json::json!({
                "error": "invalid_request",
                "error_description": error_description,
                "send_access_error_type": "send_id_required"
            });

            // Register the mock for the request
            let mock = Mock::given(matchers::method("POST"))
                .and(matchers::path("identity/connect/token"))
                .respond_with(ResponseTemplate::new(400).set_body_json(raw_error));

            // Spin up a server and register mock with it
            let (mock_server, _api_config) = start_api_mock(vec![mock]).await;

            // Create a send access client
            let send_access_client = make_send_client(&mock_server);

            // Construct the request without a send_id to trigger an error
            let req = SendAccessTokenRequest {
                send_id: "".into(),
                send_access_credentials: None, // No credentials for this test
            };

            let result = send_access_client.request_send_access_token(req).await;

            assert!(result.is_err());

            let err = result.unwrap_err();
            match err {
                SendAccessTokenError::Expected(api_err) => {
                    assert_eq!(
                        api_err,
                        SendAccessTokenApiErrorResponse::InvalidRequest {
                            send_access_error_type: Some(
                                SendAccessTokenInvalidRequestError::SendIdRequired
                            ),
                            error_description: Some(error_description),
                        }
                    );
                }
                other => panic!("expected Response variant, got {:?}", other),
            }
        }

        #[tokio::test]
        async fn request_send_access_token_invalid_request_password_hash_required_error() {
            // Create a mock error response
            let error_description = "password_hash_b64 is required.".into();
            let raw_error = serde_json::json!({
                "error": "invalid_request",
                "error_description": error_description,
                "send_access_error_type": "password_hash_b64_required"
            });

            // Register the mock for the request
            let mock = Mock::given(matchers::method("POST"))
                .and(matchers::path("identity/connect/token"))
                .respond_with(ResponseTemplate::new(400).set_body_json(raw_error));

            // Spin up a server and register mock with it
            let (mock_server, _api_config) = start_api_mock(vec![mock]).await;

            // Create a send access client
            let send_access_client = make_send_client(&mock_server);

            // Construct the request with a send_id but no credentials to trigger the error
            let req = SendAccessTokenRequest {
                send_id: "test_send_id".into(),
                send_access_credentials: None, // No credentials for this test
            };

            let result = send_access_client.request_send_access_token(req).await;

            assert!(result.is_err());

            let err = result.unwrap_err();
            match err {
                SendAccessTokenError::Expected(api_err) => {
                    assert_eq!(
                        api_err,
                        SendAccessTokenApiErrorResponse::InvalidRequest {
                            send_access_error_type: Some(
                                SendAccessTokenInvalidRequestError::PasswordHashB64Required
                            ),
                            error_description: Some(error_description),
                        }
                    );
                }
                other => panic!("expected Response variant, got {:?}", other),
            }
        }

        #[tokio::test]
        async fn request_send_access_token_invalid_request_email_required_error() {
            // Create a mock error response
            let error_description = "email is required.".into();
            let raw_error = serde_json::json!({
                "error": "invalid_request",
                "error_description": error_description,
                "send_access_error_type": "email_required"
            });

            // Register the mock for the request
            let mock = Mock::given(matchers::method("POST"))
                .and(matchers::path("identity/connect/token"))
                .respond_with(ResponseTemplate::new(400).set_body_json(raw_error));

            // Spin up a server and register mock with it
            let (mock_server, _api_config) = start_api_mock(vec![mock]).await;

            // Create a send access client
            let send_access_client = make_send_client(&mock_server);

            // Construct the request with a send_id but no credentials to trigger the error
            let req = SendAccessTokenRequest {
                send_id: "test_send_id".into(),
                send_access_credentials: None, // No credentials for this test
            };

            let result = send_access_client.request_send_access_token(req).await;

            assert!(result.is_err());

            let err = result.unwrap_err();
            match err {
                SendAccessTokenError::Expected(api_err) => {
                    assert_eq!(
                        api_err,
                        SendAccessTokenApiErrorResponse::InvalidRequest {
                            send_access_error_type: Some(
                                SendAccessTokenInvalidRequestError::EmailRequired
                            ),
                            error_description: Some(error_description),
                        }
                    );
                }
                other => panic!("expected Response variant, got {:?}", other),
            }
        }

        #[tokio::test]
        async fn request_send_access_token_invalid_request_email_otp_required_error() {
            // Create a mock error response
            let error_description =
                "email and otp are required. An OTP has been sent to the email address provided."
                    .into();
            let raw_error = serde_json::json!({
                "error": "invalid_request",
                "error_description": error_description,
                "send_access_error_type": "email_and_otp_required"
            });

            // Create the mock for the request
            let mock = Mock::given(matchers::method("POST"))
                .and(matchers::path("identity/connect/token"))
                .respond_with(ResponseTemplate::new(400).set_body_json(raw_error));

            // Spin up a server and register mock with it
            let (mock_server, _api_config) = start_api_mock(vec![mock]).await;

            // Create a send access client
            let send_access_client = make_send_client(&mock_server);

            // Construct the request with a send_id and email credential
            let email_credentials = SendEmailCredentials {
                email: "test@example.com".into(),
            };

            let req = SendAccessTokenRequest {
                send_id: "test_send_id".into(),
                send_access_credentials: Some(SendAccessCredentials::Email(email_credentials)),
            };

            let result = send_access_client.request_send_access_token(req).await;

            assert!(result.is_err());

            let err = result.unwrap_err();
            match err {
                SendAccessTokenError::Expected(api_err) => {
                    assert_eq!(
                        api_err,
                        SendAccessTokenApiErrorResponse::InvalidRequest {
                            send_access_error_type: Some(
                                SendAccessTokenInvalidRequestError::EmailAndOtpRequired
                            ),
                            error_description: Some(error_description),
                        }
                    );
                }
                other => panic!("expected Response variant, got {:?}", other),
            }
        }

        #[tokio::test]
        async fn request_send_access_token_invalid_request_email_credential_unrecognized_email_masked_as_otp_required()
         {
            // Create a mock error response
            let error_description = "email and otp are required.".into();
            let raw_error = serde_json::json!({
                "error": "invalid_request",
                "error_description": error_description,
                "send_access_error_type": "email_and_otp_required"
            });

            // Register the mock for the request
            let mock = Mock::given(matchers::method("POST"))
                .and(matchers::path("identity/connect/token"))
                .respond_with(ResponseTemplate::new(400).set_body_json(raw_error));

            // Spin up a server and register mock with it
            let (mock_server, _api_config) = start_api_mock(vec![mock]).await;

            // Create a send access client
            let send_access_client = make_send_client(&mock_server);

            // Construct the request
            let email_credentials = SendEmailCredentials {
                email: "invalid-email".into(),
            };
            let req = SendAccessTokenRequest {
                send_id: "valid-send-id".into(),
                send_access_credentials: Some(SendAccessCredentials::Email(email_credentials)),
            };

            let result = send_access_client.request_send_access_token(req).await;

            assert!(result.is_err());

            let err = result.unwrap_err();
            match err {
                SendAccessTokenError::Expected(api_err) => {
                    // Now assert the inner enum:
                    assert_eq!(
                        api_err,
                        SendAccessTokenApiErrorResponse::InvalidRequest {
                            send_access_error_type: Some(
                                SendAccessTokenInvalidRequestError::EmailAndOtpRequired
                            ),
                            error_description: Some(error_description),
                        }
                    );
                }
                other => panic!("expected Response variant, got {:?}", other),
            }
        }

        #[tokio::test]
        async fn request_send_access_token_invalid_request_email_otp_credential_invalid_otp_masked_as_otp_required()
         {
            // When an email+OTP is sent with an invalid OTP, the server returns
            // email_and_otp_required (not otp_invalid) to prevent email enumeration.
            let error_description = "email and otp are required.".into();
            let raw_error = serde_json::json!({
                "error": "invalid_request",
                "error_description": error_description,
                "send_access_error_type": "email_and_otp_required"
            });

            // Create the mock for the request
            let mock = Mock::given(matchers::method("POST"))
                .and(matchers::path("identity/connect/token"))
                .respond_with(ResponseTemplate::new(400).set_body_json(raw_error));

            // Spin up a server and register mock with it
            let (mock_server, _api_config) = start_api_mock(vec![mock]).await;

            // Create a send access client
            let send_access_client = make_send_client(&mock_server);

            // Construct the request
            let email_otp_credentials = SendEmailOtpCredentials {
                email: "valid@email.com".into(),
                otp: "invalid_otp".into(),
            };
            let req = SendAccessTokenRequest {
                send_id: "valid-send-id".into(),
                send_access_credentials: Some(SendAccessCredentials::EmailOtp(
                    email_otp_credentials,
                )),
            };

            let result = send_access_client.request_send_access_token(req).await;

            assert!(result.is_err());

            let err = result.unwrap_err();
            match err {
                SendAccessTokenError::Expected(api_err) => {
                    assert_eq!(
                        api_err,
                        SendAccessTokenApiErrorResponse::InvalidRequest {
                            send_access_error_type: Some(
                                SendAccessTokenInvalidRequestError::EmailAndOtpRequired
                            ),
                            error_description: Some(error_description),
                        }
                    );
                }
                other => panic!("expected Response variant, got {:?}", other),
            }
        }

        #[tokio::test]
        async fn request_send_access_token_invalid_request_email_otp_credential_unrecognized_email_masked_as_otp_required()
         {
            // When an email+OTP is sent where the email is not in the Send's allowed list,
            // the server returns email_and_otp_required (not email_invalid) to prevent email
            // enumeration. The server checks email validity before OTP, so even a valid OTP
            // paired with an unrecognized email returns the same generic response.
            let error_description = "email and otp are required.".into();
            let raw_error = serde_json::json!({
                "error": "invalid_request",
                "error_description": error_description,
                "send_access_error_type": "email_and_otp_required"
            });

            // Create the mock for the request
            let mock = Mock::given(matchers::method("POST"))
                .and(matchers::path("identity/connect/token"))
                .respond_with(ResponseTemplate::new(400).set_body_json(raw_error));

            // Spin up a server and register mock with it
            let (mock_server, _api_config) = start_api_mock(vec![mock]).await;

            // Create a send access client
            let send_access_client = make_send_client(&mock_server);

            // Construct the request with an email not in the Send's allowed list
            let email_otp_credentials = SendEmailOtpCredentials {
                email: "notallowed@example.com".into(),
                otp: "any_otp".into(),
            };
            let req = SendAccessTokenRequest {
                send_id: "valid-send-id".into(),
                send_access_credentials: Some(SendAccessCredentials::EmailOtp(
                    email_otp_credentials,
                )),
            };

            let result = send_access_client.request_send_access_token(req).await;

            assert!(result.is_err());

            let err = result.unwrap_err();
            match err {
                SendAccessTokenError::Expected(api_err) => {
                    assert_eq!(
                        api_err,
                        SendAccessTokenApiErrorResponse::InvalidRequest {
                            send_access_error_type: Some(
                                SendAccessTokenInvalidRequestError::EmailAndOtpRequired
                            ),
                            error_description: Some(error_description),
                        }
                    );
                }
                other => panic!("expected Response variant, got {:?}", other),
            }
        }
    }

    mod request_send_access_token_invalid_grant_tests {

        use super::*;

        #[tokio::test]
        async fn request_send_access_token_invalid_grant_invalid_send_id_error() {
            // Create a mock error response
            let error_description = "send_id is invalid.".into();
            let raw_error = serde_json::json!({
                "error": "invalid_grant",
                "error_description": error_description,
                "send_access_error_type": "send_id_invalid"
            });

            // Create the mock for the request
            let mock = Mock::given(matchers::method("POST"))
                .and(matchers::path("identity/connect/token"))
                .respond_with(ResponseTemplate::new(400).set_body_json(raw_error));

            // Spin up a server and register mock with it
            let (mock_server, _api_config) = start_api_mock(vec![mock]).await;

            // Create a send access client
            let send_access_client = make_send_client(&mock_server);

            // Construct the request with an invalid send_id to trigger an error
            let req = SendAccessTokenRequest {
                send_id: "invalid-send-id".into(),
                send_access_credentials: None, // No credentials for this test
            };

            let result = send_access_client.request_send_access_token(req).await;

            assert!(result.is_err());

            let err = result.unwrap_err();
            match err {
                SendAccessTokenError::Expected(api_err) => {
                    // Now assert the inner enum:
                    assert_eq!(
                        api_err,
                        SendAccessTokenApiErrorResponse::InvalidGrant {
                            send_access_error_type: Some(
                                SendAccessTokenInvalidGrantError::SendIdInvalid
                            ),
                            error_description: Some(error_description),
                        }
                    );
                }
                other => panic!("expected Response variant, got {:?}", other),
            }
        }

        #[tokio::test]
        async fn request_send_access_token_invalid_grant_invalid_password_hash_error() {
            // Create a mock error response
            let error_description = "password_hash_b64 is invalid.".into();
            let raw_error = serde_json::json!({
                "error": "invalid_grant",
                "error_description": error_description,
                "send_access_error_type": "password_hash_b64_invalid"
            });

            // Create the mock for the request
            let mock = Mock::given(matchers::method("POST"))
                .and(matchers::path("identity/connect/token"))
                .respond_with(ResponseTemplate::new(400).set_body_json(raw_error));

            // Spin up a server and register mock with it
            let (mock_server, _api_config) = start_api_mock(vec![mock]).await;

            // Create a send access client
            let send_access_client = make_send_client(&mock_server);

            // Construct the request
            let password_credentials = SendPasswordCredentials {
                password_hash_b64: "invalid-hash".into(),
            };

            let req = SendAccessTokenRequest {
                send_id: "valid-send-id".into(),
                send_access_credentials: Some(SendAccessCredentials::Password(
                    password_credentials,
                )),
            };

            let result = send_access_client.request_send_access_token(req).await;

            assert!(result.is_err());

            let err = result.unwrap_err();
            match err {
                SendAccessTokenError::Expected(api_err) => {
                    // Now assert the inner enum:
                    assert_eq!(
                        api_err,
                        SendAccessTokenApiErrorResponse::InvalidGrant {
                            send_access_error_type: Some(
                                SendAccessTokenInvalidGrantError::PasswordHashB64Invalid
                            ),
                            error_description: Some(error_description),
                        }
                    );
                }
                other => panic!("expected Response variant, got {:?}", other),
            }
        }
    }

    mod request_send_access_token_unexpected_error_tests {

        use super::*;

        async fn run_case(status_code: u16, reason: &str) {
            let mock = Mock::given(matchers::method("POST"))
                .and(matchers::path("identity/connect/token"))
                .respond_with(ResponseTemplate::new(status_code));

            let (mock_server, _api_config) = start_api_mock(vec![mock]).await;
            let send_access_client = make_send_client(&mock_server);

            let req = SendAccessTokenRequest {
                send_id: "test_send_id".into(),
                send_access_credentials: None,
            };

            let result = send_access_client.request_send_access_token(req).await;

            assert!(result.is_err());

            let err = result.expect_err(&format!(
                "expected Err for status {} {} against http://{}/identity/connect/token",
                status_code,
                reason,
                mock_server.address()
            ));

            match err {
                SendAccessTokenError::Unexpected(api_err) => {
                    let expected = UnexpectedIdentityError(format!(
                        "Received response status {} {} against http://{}/identity/connect/token",
                        status_code,
                        reason,
                        mock_server.address()
                    ));
                    assert_eq!(api_err, expected, "mismatch for status {}", status_code);
                }
                other => panic!("expected Unexpected variant, got {:?}", other),
            }
        }

        #[tokio::test]
        async fn request_send_access_token_unexpected_statuses() {
            let cases = [
                // 4xx (client errors) — excluding 400 Bad Request as we handle those as expected
                // errors.
                (401, "Unauthorized"),
                (402, "Payment Required"),
                (403, "Forbidden"),
                (404, "Not Found"),
                (405, "Method Not Allowed"),
                (406, "Not Acceptable"),
                (407, "Proxy Authentication Required"),
                (408, "Request Timeout"),
                (409, "Conflict"),
                (410, "Gone"),
                (411, "Length Required"),
                (412, "Precondition Failed"),
                (413, "Payload Too Large"),
                (414, "URI Too Long"),
                (415, "Unsupported Media Type"),
                (416, "Range Not Satisfiable"),
                (417, "Expectation Failed"),
                (421, "Misdirected Request"),
                (422, "Unprocessable Entity"),
                (423, "Locked"),
                (424, "Failed Dependency"),
                (425, "Too Early"),
                (426, "Upgrade Required"),
                (428, "Precondition Required"),
                (429, "Too Many Requests"),
                (431, "Request Header Fields Too Large"),
                (451, "Unavailable For Legal Reasons"),
                // 5xx (server errors)
                (500, "Internal Server Error"),
                (501, "Not Implemented"),
                (502, "Bad Gateway"),
                (503, "Service Unavailable"),
                (504, "Gateway Timeout"),
                (505, "HTTP Version Not Supported"),
                (506, "Variant Also Negotiates"),
                (507, "Insufficient Storage"),
                (508, "Loop Detected"),
                (510, "Not Extended"),
                (511, "Network Authentication Required"),
            ];

            for (code, reason) in cases {
                run_case(code, reason).await;
            }
        }
    }
}