alibi-plugins 0.7.0

Built-in authentication plugins and API metadata for Alibi
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
pub(super) mod handlers;
pub(super) mod types;
mod update;

use alibi_core::wire::UserView;
use alibi_core::{
    AuthContext, AuthError, AuthPlugin, AuthRequest, AuthResponse, AuthResult, AuthRoute,
    HttpMethod,
};
use async_trait::async_trait;
use chrono::Duration;
use handlers::{change_email_core, delete_user_callback_core, delete_user_core};
use std::sync::Arc;
pub use types::{ChangeEmailRequest, DeleteUserCallbackQuery, DeleteUserRequest};
pub use update::{
    BuiltinUserEndpoints, error_endpoint, handle_update_user, ok_endpoint, update_user_endpoint,
};

/// The initialized user's full snapshot passed to application lifecycle hooks.
pub type UserInfo = UserView;

/// Custom callback for sending change-email confirmation emails.
///
/// If set on [`ChangeEmailConfig`], this callback is invoked instead of the
/// default [`EmailProvider`](alibi_core::EmailProvider). This allows callers to customise the email
/// subject, template, and delivery mechanism.
#[async_trait]
pub trait SendChangeEmailConfirmation: Send + Sync {
    async fn send(
        &self,
        user: &UserInfo,
        new_email: &str,
        url: &str,
        token: &str,
    ) -> AuthResult<()>;
}

/// Application delivery of an issued account-deletion proof. The original
/// request is available through `current_request_hook_context` during delivery.
#[async_trait]
pub trait SendDeleteAccountVerification: Send + Sync {
    async fn send(&self, user: &UserInfo, url: &str, token: &str) -> AuthResult<()>;
}

/// Hook invoked **before** a user is deleted.
///
/// Return `Err(...)` from [`before_delete`](BeforeDeleteUser::before_delete) to
/// abort the deletion.
#[async_trait]
pub trait BeforeDeleteUser: Send + Sync {
    async fn before_delete(&self, user: &UserInfo) -> AuthResult<()>;
}

/// Hook invoked **after** a user has been deleted.
#[async_trait]
pub trait AfterDeleteUser: Send + Sync {
    async fn after_delete(&self, user: &UserInfo) -> AuthResult<()>;
}

/// Configuration for the change-email feature.
#[derive(Clone, Default)]
pub struct ChangeEmailConfig {
    /// Whether the change-email endpoints are enabled. Default: `false`.
    pub enabled: bool,
    /// If `true`, the new email is updated immediately without sending a
    /// verification email. Default: `false`.
    pub update_without_verification: bool,
    /// Optional custom callback for sending the confirmation email.
    pub send_change_email_confirmation: Option<Arc<dyn SendChangeEmailConfirmation>>,
}

impl std::fmt::Debug for ChangeEmailConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ChangeEmailConfig")
            .field("enabled", &self.enabled)
            .field(
                "update_without_verification",
                &self.update_without_verification,
            )
            .field(
                "send_change_email_confirmation",
                &self.send_change_email_confirmation.is_some(),
            )
            .finish()
    }
}

/// Configuration for the delete-user feature.
#[derive(Clone)]
pub struct DeleteUserConfig {
    /// Whether the delete-user endpoints are enabled. Default: `false`.
    pub enabled: bool,
    /// How long a delete-confirmation token remains valid. Default: 1 day.
    pub delete_token_expires_in: Duration,
    /// If `true`, a verification email must be confirmed before the account is
    /// deleted using the configured `EmailProvider`. Default: `false`.
    pub require_verification: bool,
    /// Custom delivery of an account-deletion proof. A configured callback
    /// selects verification before the session-freshness check.
    pub send_delete_account_verification: Option<Arc<dyn SendDeleteAccountVerification>>,
    /// Hook called before the user record is removed.
    pub before_delete: Option<Arc<dyn BeforeDeleteUser>>,
    /// Hook called after the user record has been removed.
    pub after_delete: Option<Arc<dyn AfterDeleteUser>>,
}

impl std::fmt::Debug for DeleteUserConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DeleteUserConfig")
            .field("enabled", &self.enabled)
            .field("delete_token_expires_in", &self.delete_token_expires_in)
            .field("require_verification", &self.require_verification)
            .field(
                "send_delete_account_verification",
                &self.send_delete_account_verification.is_some(),
            )
            .field("before_delete", &self.before_delete.is_some())
            .field("after_delete", &self.after_delete.is_some())
            .finish()
    }
}

impl Default for DeleteUserConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            delete_token_expires_in: Duration::hours(24),
            require_verification: false,
            send_delete_account_verification: None,
            before_delete: None,
            after_delete: None,
        }
    }
}

/// Combined configuration for the [`UserManagementPlugin`].
#[derive(Debug, Clone, Default)]
pub struct UserManagementConfig {
    pub change_email: ChangeEmailConfig,
    pub delete_user: DeleteUserConfig,
}

/// User self-service management plugin (change email & delete account).
#[derive(Default)]
pub struct UserManagementPlugin {
    config: UserManagementConfig,
}

impl std::fmt::Debug for UserManagementPlugin {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("UserManagementPlugin")
            .finish_non_exhaustive()
    }
}

impl UserManagementPlugin {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub const fn with_config(config: UserManagementConfig) -> Self {
        Self { config }
    }

    #[must_use]
    pub const fn change_email_enabled(mut self, enabled: bool) -> Self {
        self.config.change_email.enabled = enabled;
        self
    }

    #[must_use]
    pub const fn update_without_verification(mut self, flag: bool) -> Self {
        self.config.change_email.update_without_verification = flag;
        self
    }

    #[must_use]
    pub fn send_change_email_confirmation(
        mut self,
        cb: Arc<dyn SendChangeEmailConfirmation>,
    ) -> Self {
        self.config.change_email.send_change_email_confirmation = Some(cb);
        self
    }

    #[must_use]
    pub const fn delete_user_enabled(mut self, enabled: bool) -> Self {
        self.config.delete_user.enabled = enabled;
        self
    }

    #[must_use]
    pub const fn delete_token_expires_in(mut self, duration: Duration) -> Self {
        self.config.delete_user.delete_token_expires_in = duration;
        self
    }

    #[must_use]
    pub const fn require_delete_verification(mut self, require: bool) -> Self {
        self.config.delete_user.require_verification = require;
        self
    }

    #[must_use]
    pub fn send_delete_account_verification(
        mut self,
        sender: Arc<dyn SendDeleteAccountVerification>,
    ) -> Self {
        self.config.delete_user.send_delete_account_verification = Some(sender);
        self
    }

    #[must_use]
    pub fn before_delete(mut self, hook: Arc<dyn BeforeDeleteUser>) -> Self {
        self.config.delete_user.before_delete = Some(hook);
        self
    }

    #[must_use]
    pub fn after_delete(mut self, hook: Arc<dyn AfterDeleteUser>) -> Self {
        self.config.delete_user.after_delete = Some(hook);
        self
    }
}

impl UserManagementPlugin {
    /// Start an authenticated mailbox change through the public server API.
    pub fn change_email_endpoint(
        body: &ChangeEmailRequest,
    ) -> AuthResult<alibi_core::endpoint::ServerEndpoint<alibi_core::StatusResponse>> {
        alibi_core::endpoint::ServerEndpoint::new("user-management", "changeEmail").with_body(body)
    }

    /// Complete a delivered deletion proof through the public server API.
    pub fn delete_user_callback_endpoint(
        query: &DeleteUserCallbackQuery,
    ) -> AuthResult<alibi_core::endpoint::ServerEndpoint<alibi_core::SuccessMessageResponse>> {
        alibi_core::endpoint::ServerEndpoint::new("user-management", "deleteUserCallback")
            .with_query(query)
    }

    /// Delete the authenticated owner through the public server API.
    pub fn delete_user_endpoint(
        body: &DeleteUserRequest,
    ) -> AuthResult<alibi_core::endpoint::ServerEndpoint<alibi_core::SuccessMessageResponse>> {
        alibi_core::endpoint::ServerEndpoint::new("user-management", "deleteUser").with_body(body)
    }

    async fn handle_delete_user_callback_endpoint(
        &self,
        call: &alibi_core::endpoint::EndpointCall,
        ctx: &AuthContext<impl alibi_core::AuthSchema>,
    ) -> AuthResult<alibi_core::endpoint::EndpointResponse> {
        let query: DeleteUserCallbackQuery = call.query_as()?;
        if call.request().is_some()
            && let Some(url) = query.callback_url.as_deref().filter(|url| !url.is_empty())
            && !ctx.config.current_origin_check_disabled()
            && !ctx.config.is_redirect_target_trusted(url)
        {
            return Err(AuthError::forbidden("Invalid callbackURL"));
        }
        if !self.config.delete_user.enabled {
            return Err(AuthError::Upstream {
                status: 404,
                code: "NOT_FOUND",
                message: "Not found",
            });
        }
        // Source keeps an already established context session, otherwise its
        // nested getter bypasses cookie cache when server-side authority exists.
        let mut input = call.clone();
        if ctx.config.session.has_server_session_store() {
            alibi_core::endpoint::EndpointContextPatch {
                query: Some(alibi_core::utils::json::parse_value(
                    r#"{"disableCookieCache":true}"#,
                )?),
                ..Default::default()
            }
            .apply(&mut input);
        }
        let read = alibi_core::session::cookie_cache::runtime::authenticated(ctx, &input, false)
            .await
            .ok()
            .flatten()
            .ok_or(AuthError::Upstream {
                status: 404,
                code: "FAILED_TO_GET_USER_INFO",
                message: "Failed to get user info",
            })?;
        call.record_authenticated_session(ctx.user_view(&read.user), read.session.clone());
        let response =
            delete_user_callback_core(&query.token, &read.user, call, true, &self.config, ctx)
                .await?;
        alibi_core::session::cookie_cache::runtime::clear_session_cookies(ctx, call)?;
        if let Some(url) = query.callback_url.filter(|url| !url.is_empty()) {
            return Ok(alibi_core::endpoint::EndpointResponse::redirect(url));
        }
        alibi_core::endpoint::EndpointResponse::json(&response)
    }

    /// `POST /change-email`
    async fn handle_change_email(
        &self,
        req: &AuthRequest,
        ctx: &AuthContext<impl alibi_core::AuthSchema>,
    ) -> AuthResult<AuthResponse> {
        let (user, session) = handlers::authoritative_session(req, ctx).await?;
        let body: ChangeEmailRequest = match alibi_core::validate_request_body(req) {
            Ok(v) => v,
            Err(resp) => return Ok(resp),
        };
        if !self.config.change_email.enabled {
            return Err(AuthError::bad_request("Change email is disabled"));
        }
        let projection = change_email_core(&body, &user, &session, &self.config, ctx).await?;
        let mut response = AuthResponse::json(200, &alibi_core::StatusResponse { status: true })?;
        if projection.is_some() {
            append_session_cookie(&mut response, req, &session.token, &ctx.config)?;
        }
        Ok(response)
    }

    /// `POST /delete-user`
    async fn handle_delete_user(
        &self,
        req: &AuthRequest,
        ctx: &AuthContext<impl alibi_core::AuthSchema>,
    ) -> AuthResult<AuthResponse> {
        let (user, session) = handlers::authoritative_session(req, ctx).await?;
        let body: DeleteUserRequest = match alibi_core::validate_request_body(req) {
            Ok(v) => v,
            Err(resp) => return Ok(resp),
        };
        if !self.config.delete_user.enabled {
            return Ok(AuthResponse::new(404).with_header("Content-Type", "application/json"));
        }
        let response = delete_user_core(&body, &user, &session, req, &self.config, ctx).await?;
        let deleted =
            response.message == "User deleted" && body.token.as_deref().is_none_or(str::is_empty);
        let mut response = AuthResponse::json(200, &response)?;
        if deleted {
            append_clear_session_cookies(&mut response, &ctx.config)?;
        }
        Ok(response)
    }

    /// `GET /delete-user/callback`
    async fn handle_delete_user_callback(
        &self,
        req: &AuthRequest,
        ctx: &AuthContext<impl alibi_core::AuthSchema>,
    ) -> AuthResult<AuthResponse> {
        if !self.config.delete_user.enabled {
            return Err(AuthError::Api {
                status: 404,
                code: Some("NOT_FOUND".into()),
                message: "Not found".into(),
            });
        }
        let (user, _) = handlers::authoritative_session(req, ctx)
            .await
            .map_err(|_error| AuthError::not_found("Failed to get user info"))?;
        let query: DeleteUserCallbackQuery = serde_json::from_value(serde_json::json!({
            "token": req.query.get("token").cloned(),
            "callbackURL": req.query.get("callbackURL").cloned(),
        }))
        .map_err(|_error| AuthError::bad_request("Verification token is required"))?;
        let response =
            delete_user_callback_core(&query.token, &user, req, true, &self.config, ctx).await?;
        if let Some(callback_url) = query.callback_url.filter(|url| !url.is_empty()) {
            let mut headers = alibi_core::Headers::new();
            _ = headers.insert("Location", callback_url);
            _ = headers.insert("Content-Type", "application/json");
            let mut redirect = AuthResponse {
                status: 302,
                headers,
                body: Vec::new(),
            };
            append_clear_session_cookies(&mut redirect, &ctx.config)?;
            return Ok(redirect);
        }

        let mut response = AuthResponse::json(200, &response)?;
        append_clear_session_cookies(&mut response, &ctx.config)?;
        Ok(response)
    }
}

#[async_trait]
impl<S: alibi_core::AuthSchema> AuthPlugin<S> for UserManagementPlugin {
    route_openapi_metadata!(S);

    fn name(&self) -> &'static str {
        "user-management"
    }

    fn server_endpoints(&self) -> Vec<alibi_core::endpoint::EndpointDefinition> {
        vec![
            crate::endpoint::definition(
                "changeEmail",
                "changeEmail",
                Some("/change-email"),
                HttpMethod::Post,
            ),
            crate::endpoint::definition(
                "deleteUserCallback",
                "deleteUserCallback",
                Some("/delete-user/callback"),
                HttpMethod::Get,
            ),
            crate::endpoint::definition(
                "deleteUser",
                "deleteUser",
                Some("/delete-user"),
                HttpMethod::Post,
            ),
        ]
    }

    fn validate_endpoint(
        &self,
        call: &alibi_core::endpoint::EndpointCall,
        _: &AuthContext<S>,
    ) -> AuthResult<alibi_core::endpoint::EndpointInput> {
        use crate::authentication_helpers::RequestBody;
        if call.operation_id() == "deleteUserCallback" {
            return Ok(alibi_core::endpoint::EndpointInput {
                body: call.body().cloned(),
                query: Some(crate::endpoint::validate_fields(
                    call.query(),
                    "query",
                    DeleteUserCallbackQuery::FIELDS,
                )?),
            });
        }
        Ok(alibi_core::endpoint::EndpointInput {
            body: Some(crate::endpoint::validate_fields(
                call.body(),
                "body",
                if call.operation_id() == "changeEmail" {
                    ChangeEmailRequest::FIELDS
                } else {
                    DeleteUserRequest::FIELDS
                },
            )?),
            query: call.query().cloned(),
        })
    }

    async fn on_endpoint(
        &self,
        call: &alibi_core::endpoint::EndpointCall,
        ctx: &AuthContext<S>,
    ) -> AuthResult<alibi_core::endpoint::EndpointResponse> {
        if call.operation_id() == "deleteUserCallback" {
            return self.handle_delete_user_callback_endpoint(call, ctx).await;
        }
        let (user, session) = ctx
            .require_authoritative_session_record(call)
            .await
            .map_err(|_| AuthError::Upstream {
                status: 401,
                code: "UNAUTHORIZED",
                message: "Unauthorized",
            })?;
        call.record_authenticated_session(ctx.user_view(&user), session.clone());
        if call.operation_id() == "changeEmail" {
            if !self.config.change_email.enabled {
                return Err(AuthError::bad_request("Change email is disabled"));
            }
            let body: ChangeEmailRequest = call.body_as()?;
            let projection = change_email_core(&body, &user, &session, &self.config, ctx).await?;
            let mut response =
                alibi_core::endpoint::EndpointResponse::json(&alibi_core::StatusResponse {
                    status: true,
                })?;
            if projection.is_some() {
                response.merge_headers(crate::authentication_helpers::session_cookie_headers(
                    &ctx.config,
                    &session.token,
                    ctx.session_manager().has_dont_remember_cookie(call),
                )?);
            }
            return Ok(response);
        }
        if !self.config.delete_user.enabled {
            return Ok(
                alibi_core::endpoint::EndpointResponse::error(AuthError::Api {
                    status: 404,
                    code: None,
                    message: String::new(),
                })
                .without_error_body(),
            );
        }
        let body: DeleteUserRequest = call.body_as()?;
        let response = delete_user_core(&body, &user, &session, call, &self.config, ctx).await?;
        let deleted =
            response.message == "User deleted" && body.token.as_deref().is_none_or(str::is_empty);
        if deleted {
            alibi_core::session::cookie_cache::runtime::clear_session_cookies(ctx, call)?;
        }
        alibi_core::endpoint::EndpointResponse::json(&response)
    }

    fn routes(&self) -> Vec<AuthRoute> {
        vec![
            AuthRoute::post("/change-email", "change_email"),
            AuthRoute::post("/delete-user", "delete_user"),
            AuthRoute::get("/delete-user/callback", "delete_user_callback"),
        ]
    }

    async fn on_request(
        &self,
        req: &AuthRequest,
        ctx: &AuthContext<S>,
    ) -> AuthResult<Option<AuthResponse>> {
        let response = match (req.method(), req.path()) {
            (HttpMethod::Post, "/change-email") => self.handle_change_email(req, ctx).await?,
            (HttpMethod::Post, "/delete-user") => self.handle_delete_user(req, ctx).await?,
            (HttpMethod::Get, "/delete-user/callback") => {
                self.handle_delete_user_callback(req, ctx).await?
            }
            _ => return Ok(None),
        };
        Ok(Some(response))
    }
}

pub(super) fn append_clear_session_cookies(
    response: &mut AuthResponse,
    config: &alibi_core::AuthConfig,
) -> AuthResult<()> {
    response.headers.append(
        "Set-Cookie",
        alibi_core::utils::cookie_utils::create_clear_session_cookie(config)?,
    );
    response.headers.append(
        "Set-Cookie",
        alibi_core::utils::cookie_utils::create_clear_cookie(
            &related_cookie_name(config, "session_data"),
            config,
        )?,
    );
    response.headers.append(
        "Set-Cookie",
        alibi_core::utils::cookie_utils::create_clear_cookie(
            &related_cookie_name(config, "dont_remember"),
            config,
        )?,
    );
    if config.account.store_account_cookie {
        response.headers.append(
            "Set-Cookie",
            alibi_core::utils::cookie_utils::create_clear_cookie(
                &related_cookie_name(config, "account_data"),
                config,
            )?,
        );
    }
    Ok(())
}

pub(crate) fn append_session_cookie(
    response: &mut AuthResponse,
    req: &AuthRequest,
    token: &str,
    config: &alibi_core::AuthConfig,
) -> AuthResult<()> {
    use alibi_core::utils::cookie_utils::{
        create_session_cookie_with_max_age, verify_cookie_value,
    };
    let dont_remember =
        super::helpers::get_cookie(req, &related_cookie_name(config, "dont_remember"))
            .and_then(|value| verify_cookie_value(&value, config.current_secret()))
            .is_some_and(|value| !value.is_empty());
    response.headers.append(
        "Set-Cookie",
        create_session_cookie_with_max_age(
            Some(token),
            (!dont_remember).then(|| config.session.expires_in.num_seconds()),
            config,
        )?,
    );
    Ok(())
}

fn related_cookie_name(config: &alibi_core::AuthConfig, suffix: &str) -> String {
    config
        .session
        .cookie_name
        .strip_suffix("session_token")
        .map_or_else(
            || format!("better-auth.{suffix}"),
            |prefix| format!("{prefix}{suffix}"),
        )
}

// LCOV_EXCL_START
#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_helpers;
    use alibi_core::AuthUser;
    use alibi_core::{AccountConfig, CreateUser};
    use async_trait::async_trait;
    use chrono::Duration;
    use std::collections::HashMap;
    use std::sync::Arc;

    // -- change email tests ────────────────────────────────────────────

    // Upstream reference: packages/better-auth/src/api/routes/update-user.test.ts :: describe("updateUser") and packages/better-auth/src/api/routes/update-user.ts; adapted to the Rust user-management plugin.
    #[tokio::test]
    async fn test_change_email_success() {
        let plugin = UserManagementPlugin::new().change_email_enabled(true);
        let (mut ctx, _user, session) = test_helpers::create_test_context_with_user(
            CreateUser::new()
                .with_email("test@example.com")
                .with_name("Test User")
                .with_email_verified(true),
            Duration::hours(24),
        )
        .await;

        ctx.email_provider = Some(Arc::new(alibi_core::email::ConsoleEmailProvider));

        let body = serde_json::json!({ "newEmail": "new@example.com" });
        let req = test_helpers::create_auth_request(
            HttpMethod::Post,
            "/change-email",
            Some(&session.token),
            Some(body.to_string().into_bytes()),
            HashMap::new(),
        );

        let response = plugin.handle_change_email(&req, &ctx).await.unwrap();
        assert_eq!(response.status, 200);
    }

    // Upstream reference: packages/better-auth/src/api/routes/update-user.test.ts :: describe("updateUser") and packages/better-auth/src/api/routes/update-user.ts; adapted to the Rust user-management plugin.
    #[tokio::test]
    async fn test_change_email_same_email() {
        let plugin = UserManagementPlugin::new().change_email_enabled(true);
        let (ctx, _user, session) = test_helpers::create_test_context_with_user(
            CreateUser::new()
                .with_email("test@example.com")
                .with_name("Test User")
                .with_email_verified(true),
            Duration::hours(24),
        )
        .await;

        let body = serde_json::json!({ "newEmail": "test@example.com" });
        let req = test_helpers::create_auth_request(
            HttpMethod::Post,
            "/change-email",
            Some(&session.token),
            Some(body.to_string().into_bytes()),
            HashMap::new(),
        );

        let err = plugin.handle_change_email(&req, &ctx).await.unwrap_err();
        assert_eq!(err.status_code(), 400);
    }

    // Upstream reference: packages/better-auth/src/api/routes/update-user.test.ts :: describe("updateUser") and packages/better-auth/src/api/routes/update-user.ts; adapted to the Rust user-management plugin.
    #[tokio::test]
    async fn test_change_email_unauthenticated() {
        let plugin = UserManagementPlugin::new().change_email_enabled(true);
        let (ctx, _user, _session) = test_helpers::create_test_context_with_user(
            CreateUser::new()
                .with_email("test@example.com")
                .with_name("Test User")
                .with_email_verified(true),
            Duration::hours(24),
        )
        .await;

        let body = serde_json::json!({ "newEmail": "new@example.com" });
        let req = test_helpers::create_auth_request(
            HttpMethod::Post,
            "/change-email",
            None,
            Some(body.to_string().into_bytes()),
            HashMap::new(),
        );

        let err = plugin.handle_change_email(&req, &ctx).await.unwrap_err();
        assert_eq!(err.status_code(), 401);
    }

    // Upstream reference: packages/better-auth/src/api/routes/update-user.test.ts :: describe("updateUser") and packages/better-auth/src/api/routes/update-user.ts; adapted to the Rust user-management plugin.
    #[tokio::test]
    async fn test_change_email_immediate_when_update_without_verification() {
        let plugin = UserManagementPlugin::new()
            .change_email_enabled(true)
            .update_without_verification(true);
        let (ctx, user, session) = test_helpers::create_test_context_with_user(
            CreateUser::new()
                .with_email("test@example.com")
                .with_name("Test User")
                .with_email_verified(false),
            Duration::hours(24),
        )
        .await;

        // Initiate change -- should update immediately, no verification token
        let body = serde_json::json!({ "newEmail": "new@example.com" });
        let req = test_helpers::create_auth_request(
            HttpMethod::Post,
            "/change-email",
            Some(&session.token),
            Some(body.to_string().into_bytes()),
            HashMap::new(),
        );
        let response = plugin.handle_change_email(&req, &ctx).await.unwrap();
        assert_eq!(response.status, 200);

        // Email should be updated immediately
        let updated_user = ctx
            .database
            .get_user_by_id(&user.id)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(updated_user.email(), Some("new@example.com"));
        // email_verified should be false (no verification was performed)
        assert!(!updated_user.email_verified);

        // No verification token should have been created
        let identifier = format!("change_email:{}:new@example.com", user.id);
        let verification = ctx
            .database
            .get_verification_by_identifier(&identifier)
            .await
            .unwrap();
        assert!(
            verification.is_none(),
            "no verification token should be created when update_without_verification=true"
        );
    }

    // -- delete user tests ─────────────────────────────────────────────

    // Upstream reference: packages/better-auth/src/api/routes/update-user.test.ts :: describe("updateUser") and packages/better-auth/src/api/routes/update-user.ts; adapted to the Rust user-management plugin.
    #[tokio::test]
    async fn test_delete_user_immediate() {
        let plugin = UserManagementPlugin::new()
            .delete_user_enabled(true)
            .require_delete_verification(false);
        let (ctx, user, session) = test_helpers::create_test_context_with_user(
            CreateUser::new()
                .with_email("test@example.com")
                .with_name("Test User")
                .with_email_verified(true),
            Duration::hours(24),
        )
        .await;

        let req = test_helpers::create_auth_request(
            HttpMethod::Post,
            "/delete-user",
            Some(&session.token),
            Some(b"{}".to_vec()),
            HashMap::new(),
        );

        let response = plugin.handle_delete_user(&req, &ctx).await.unwrap();
        assert_eq!(response.status, 200);

        // User should be gone
        let deleted_user = ctx.database.get_user_by_id(&user.id).await.unwrap();
        assert!(deleted_user.is_none());
    }

    // Upstream reference: packages/better-auth/src/api/routes/update-user.ts :: deleteUser calls `deleteSessionCookie(ctx)`, which clears the account_data cookie when account.storeAccountCookie is enabled.
    #[tokio::test]
    async fn test_delete_user_immediate_clears_account_cookie_when_enabled() {
        let plugin = UserManagementPlugin::new()
            .delete_user_enabled(true)
            .require_delete_verification(false);
        let config = test_helpers::create_test_config().account(AccountConfig {
            store_account_cookie: true,
            ..Default::default()
        });
        let ctx = test_helpers::create_test_context_with_config(config).await;
        let (_user, session) = test_helpers::create_user_and_session(
            &ctx,
            CreateUser::new()
                .with_email("account-cookie@test.com")
                .with_name("Account Cookie")
                .with_email_verified(true),
            Duration::hours(24),
        )
        .await;

        let req = test_helpers::create_auth_request(
            HttpMethod::Post,
            "/delete-user",
            Some(&session.token),
            Some(b"{}".to_vec()),
            HashMap::new(),
        );

        let response = plugin.handle_delete_user(&req, &ctx).await.unwrap();
        let account_cookie_name = format!("{}=", related_cookie_name(&ctx.config, "account_data"));
        assert!(
            response
                .headers
                .get_all("Set-Cookie")
                .any(|cookie| cookie.starts_with(&account_cookie_name)),
            "delete-user should clear the account_data cookie when store_account_cookie is enabled"
        );
    }

    // Upstream reference: packages/better-auth/src/api/routes/update-user.test.ts :: describe("updateUser") and packages/better-auth/src/api/routes/update-user.ts; adapted to the Rust user-management plugin.
    #[tokio::test]
    async fn test_delete_user_with_verification() {
        let plugin = UserManagementPlugin::new()
            .delete_user_enabled(true)
            .require_delete_verification(true);
        let (ctx, user, session) = test_helpers::create_test_context_with_user(
            CreateUser::new()
                .with_email("test@example.com")
                .with_name("Test User")
                .with_email_verified(true),
            Duration::hours(24),
        )
        .await;

        // 1. Request deletion -- should return pending status
        let req = test_helpers::create_auth_request(
            HttpMethod::Post,
            "/delete-user",
            Some(&session.token),
            Some(b"{}".to_vec()),
            HashMap::new(),
        );

        let response = plugin.handle_delete_user(&req, &ctx).await.unwrap();
        assert_eq!(response.status, 200);

        // User should still exist
        let still_exists = ctx.database.get_user_by_id(&user.id).await.unwrap();
        assert!(still_exists.is_some());

        // 2. Seed and confirm the callback token
        let token = "delete-token-123";
        ctx.database
            .create_verification(alibi_core::CreateVerification {
                identifier: format!("delete-account-{token}"),
                value: user.id.clone(),
                expires_at: chrono::Utc::now() + Duration::hours(24),
            })
            .await
            .unwrap();

        let mut query = HashMap::new();
        query.insert("token".to_owned(), token.to_owned());
        let req_2 = test_helpers::create_auth_request(
            HttpMethod::Get,
            "/delete-user/callback",
            Some(&session.token),
            None,
            query,
        );
        let response_2 = plugin
            .handle_delete_user_callback(&req_2, &ctx)
            .await
            .unwrap();
        assert_eq!(response_2.status, 200);

        // User should now be gone
        let deleted = ctx.database.get_user_by_id(&user.id).await.unwrap();
        assert!(deleted.is_none());
    }

    // Upstream reference: packages/better-auth/src/api/routes/update-user.ts :: deleteUserCallback calls `deleteSessionCookie(ctx)`, which clears the account_data cookie when account.storeAccountCookie is enabled.
    #[tokio::test]
    async fn test_delete_user_callback_clears_account_cookie_when_enabled() {
        let plugin = UserManagementPlugin::new()
            .delete_user_enabled(true)
            .require_delete_verification(true);
        let config = test_helpers::create_test_config().account(AccountConfig {
            store_account_cookie: true,
            ..Default::default()
        });
        let ctx = test_helpers::create_test_context_with_config(config).await;
        let (user, session) = test_helpers::create_user_and_session(
            &ctx,
            CreateUser::new()
                .with_email("callback-cookie@test.com")
                .with_name("Callback Cookie")
                .with_email_verified(true),
            Duration::hours(24),
        )
        .await;

        let token = "delete-cookie-token";
        ctx.database
            .create_verification(alibi_core::CreateVerification {
                identifier: format!("delete-account-{token}"),
                value: user.id.clone(),
                expires_at: chrono::Utc::now() + Duration::hours(24),
            })
            .await
            .unwrap();

        let mut query = HashMap::new();
        query.insert("token".to_owned(), token.to_owned());
        query.insert(
            "callbackURL".to_owned(),
            "https://example.com/goodbye".to_owned(),
        );
        let req = test_helpers::create_auth_request(
            HttpMethod::Get,
            "/delete-user/callback",
            Some(&session.token),
            None,
            query,
        );

        let response = plugin
            .handle_delete_user_callback(&req, &ctx)
            .await
            .unwrap();
        assert_eq!(response.status, 302);
        let account_cookie_name = format!("{}=", related_cookie_name(&ctx.config, "account_data"));
        assert!(
            response
                .headers
                .get_all("Set-Cookie")
                .any(|cookie| cookie.starts_with(&account_cookie_name)),
            "delete-user callback should clear the account_data cookie when store_account_cookie is enabled"
        );
    }

    // Upstream reference: packages/better-auth/src/api/routes/update-user.test.ts :: describe("updateUser") and packages/better-auth/src/api/routes/update-user.ts; adapted to the Rust user-management plugin.
    #[tokio::test]
    async fn test_delete_user_unauthenticated() {
        let plugin = UserManagementPlugin::new()
            .delete_user_enabled(true)
            .require_delete_verification(false);
        let (ctx, _user, _session) = test_helpers::create_test_context_with_user(
            CreateUser::new()
                .with_email("test@example.com")
                .with_name("Test User")
                .with_email_verified(true),
            Duration::hours(24),
        )
        .await;

        let req = test_helpers::create_auth_request(
            HttpMethod::Post,
            "/delete-user",
            None,
            Some(b"{}".to_vec()),
            HashMap::new(),
        );

        let err = plugin.handle_delete_user(&req, &ctx).await.unwrap_err();
        assert_eq!(err.status_code(), 401);
    }

    // Upstream reference: packages/better-auth/src/api/routes/update-user.test.ts :: describe("updateUser") and packages/better-auth/src/api/routes/update-user.ts; adapted to the Rust user-management plugin.
    #[tokio::test]
    async fn test_delete_user_verify_invalid_token() {
        let plugin = UserManagementPlugin::new().delete_user_enabled(true);
        let (ctx, _user, fixture_session) = test_helpers::create_test_context_with_user(
            CreateUser::new()
                .with_email("test@example.com")
                .with_name("Test User")
                .with_email_verified(true),
            Duration::hours(24),
        )
        .await;

        let mut query = HashMap::new();
        query.insert("token".to_owned(), "invalid-token".to_owned());
        let req = test_helpers::create_auth_request(
            HttpMethod::Get,
            "/delete-user/callback",
            Some(&fixture_session.token),
            None,
            query,
        );

        let err = plugin
            .handle_delete_user_callback(&req, &ctx)
            .await
            .unwrap_err();
        assert_eq!(err.status_code(), 404);
    }

    // Upstream reference: packages/better-auth/src/api/routes/update-user.test.ts :: describe("updateUser") and packages/better-auth/src/api/routes/update-user.ts; adapted to the Rust user-management plugin.
    #[tokio::test]
    async fn test_delete_user_before_hook_abort() {
        use std::sync::atomic::{AtomicBool, Ordering};

        struct AbortHook;

        #[async_trait]
        impl BeforeDeleteUser for AbortHook {
            async fn before_delete(&self, _user: &UserInfo) -> AuthResult<()> {
                Err(AuthError::forbidden("Deletion blocked by policy"))
            }
        }

        struct AfterHook(Arc<AtomicBool>);

        #[async_trait]
        impl AfterDeleteUser for AfterHook {
            async fn after_delete(&self, _user: &UserInfo) -> AuthResult<()> {
                self.0.store(true, Ordering::SeqCst);
                Ok(())
            }
        }

        let called = Arc::new(AtomicBool::new(false));
        let called_clone = std::sync::Arc::clone(&called);

        let plugin = UserManagementPlugin::new()
            .delete_user_enabled(true)
            .require_delete_verification(false)
            .before_delete(Arc::new(AbortHook))
            .after_delete(Arc::new(AfterHook(called_clone)));
        let (ctx, user, session) = test_helpers::create_test_context_with_user(
            CreateUser::new()
                .with_email("test@example.com")
                .with_name("Test User")
                .with_email_verified(true),
            Duration::hours(24),
        )
        .await;

        let req = test_helpers::create_auth_request(
            HttpMethod::Post,
            "/delete-user",
            Some(&session.token),
            Some(b"{}".to_vec()),
            HashMap::new(),
        );

        let err = plugin.handle_delete_user(&req, &ctx).await.unwrap_err();
        assert_eq!(err.status_code(), 403);

        // User should still exist
        let still_exists = ctx.database.get_user_by_id(&user.id).await.unwrap();
        assert!(still_exists.is_some());

        // after_delete should NOT have been called
        assert!(!called.load(Ordering::SeqCst));
    }

    // The full-document SDK owner verifies default registration. This authenticated
    // native boundary independently proves disabled handlers cannot mutate storage.
    #[tokio::test]
    async fn disabled_user_management_rejects_authenticated_mutations() {
        let plugin = UserManagementPlugin::new();
        let (ctx, user, session) = test_helpers::create_test_context_with_user(
            CreateUser::new()
                .with_email("test@example.com")
                .with_name("Test User")
                .with_email_verified(true),
            Duration::hours(24),
        )
        .await;
        for (path, body, status) in [
            (
                "/change-email",
                serde_json::json!({"newEmail":"changed@example.com"}),
                400,
            ),
            ("/delete-user", serde_json::json!({}), 404),
        ] {
            let req = test_helpers::create_auth_request(
                HttpMethod::Post,
                path,
                Some(&session.token),
                Some(body.to_string().into_bytes()),
                HashMap::new(),
            );
            let result = plugin.on_request(&req, &ctx).await;
            match result {
                Ok(Some(response)) => assert_eq!(response.status, status),
                Err(error) => assert_eq!(error.status_code(), status),
                other => panic!("registered disabled handler did not reject: {other:?}"),
            }
            let stored = ctx
                .database
                .get_user_by_id(&user.id)
                .await
                .unwrap()
                .unwrap();
            assert_eq!(Some(stored.email), user.email);
            assert!(
                ctx.database
                    .get_session(&session.token)
                    .await
                    .unwrap()
                    .is_some()
            );
        }
    }
}
// LCOV_EXCL_STOP