better-auth 0.10.0

The most comprehensive authentication framework for Rust
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
//! Snapshot tests for endpoint response shapes using the `insta` crate.
//!
//! These tests capture the *structure* of each endpoint's JSON response as a
//! YAML snapshot.  Dynamic values (IDs, timestamps, tokens) are redacted so
//! that snapshots are deterministic across runs.
//!
//! When the response shape changes, `cargo insta review` presents a diff and
//! lets maintainers accept or reject it — replacing dozens of manual
//! `assert!(json["field"].is_string())` lines.
//!
//! ## Comparison with TypeScript better-auth (v1.4.19)
//!
//! Snapshots were validated against the TypeScript reference implementation.
//! The Rust responses are a **superset** of the TS responses: every field
//! returned by TS is present in Rust with the same camelCase name and
//! compatible type.  The following *additional* fields appear because
//! `create_test_auth()` registers plugins (admin, organization, two-factor):
//!
//! - **User object**: `banned`, `banReason`, `banExpires`, `role`,
//!   `twoFactorEnabled`, `username`, `displayUsername` (all nullable/default)
//! - **Session object**: `activeOrganizationId`, `impersonatedBy` (nullable)
//! - **Signin response**: extra `url: ~` field (redirect URL, always null)
//!
//! ### Known implementation gaps vs TypeScript better-auth
//!
//! | Area | TypeScript | Rust | Tracking |
//! |------|-----------|------|----------|
//! | Error responses | `{code, message}` | `{message}` only | Missing `code` field |
//! | `/list-accounts` | Returns account objects with `scopes` | Returns `[]` | Not yet implemented |
//! | `/forget-password` | Empty 200 body | `{status: true}` | Acceptable deviation |
//! | `/delete-user` | Disabled by default | `{message, success}` | TS requires opt-in |

mod compat;

use compat::helpers::*;
use insta::{assert_yaml_snapshot, with_settings};
use serde_json::Value;
use uuid::Uuid;

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Redact dynamic values from a JSON response so snapshots are stable.
///
/// Replaces UUIDs, session tokens, ISO-8601 timestamps, and hashed keys
/// with deterministic placeholder strings.
fn redact(value: &Value) -> Value {
    match value {
        Value::String(s) => {
            // UUID v4/v7 pattern
            if is_uuid(s) {
                return Value::String("[uuid]".to_string());
            }
            // Session tokens: session_<base64>
            if s.starts_with("session_") && s.len() > 20 && !s.contains('@') {
                return Value::String("[session_token]".to_string());
            }
            // ISO-8601 timestamps (e.g. 2024-01-01T00:00:00Z or with fractional seconds)
            if is_iso_timestamp(s) {
                return Value::String("[timestamp]".to_string());
            }
            // API key hashes (SHA-256 hex, 64 chars)
            if s.len() == 64 && s.chars().all(|c| c.is_ascii_hexdigit()) {
                return Value::String("[sha256_hash]".to_string());
            }
            // API key tokens: ba_<...>
            if s.starts_with("ba_") && s.len() > 10 {
                return Value::String("[api_key_token]".to_string());
            }
            Value::String(s.clone())
        }
        Value::Array(arr) => Value::Array(arr.iter().map(redact).collect()),
        Value::Object(map) => {
            Value::Object(map.iter().map(|(k, v)| (k.clone(), redact(v))).collect())
        }
        other => other.clone(),
    }
}

fn is_uuid(s: &str) -> bool {
    Uuid::parse_str(s).is_ok()
}

fn is_iso_timestamp(s: &str) -> bool {
    chrono::DateTime::parse_from_rfc3339(s).is_ok()
        || chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S%.f").is_ok()
}

// ---------------------------------------------------------------------------
// Snapshot tests
// ---------------------------------------------------------------------------

/// POST /sign-up/email response shape
#[tokio::test]
async fn snapshot_signup_response() {
    let auth = create_test_auth().await;
    let req = post_json(
        "/sign-up/email",
        serde_json::json!({
            "name": "Snapshot User",
            "email": "snap@example.com",
            "password": "password123"
        }),
    );
    let (status, body) = send_request(&auth, req).await;
    assert_eq!(status, 200);

    with_settings!({snapshot_suffix => "signup"}, {
        assert_yaml_snapshot!(redact(&body));
    });
}

/// POST /sign-in/email response shape
#[tokio::test]
async fn snapshot_signin_response() {
    let auth = create_test_auth().await;
    signup_user(
        &auth,
        "signin_snap@example.com",
        "password123",
        "Signin Snap",
    )
    .await;

    let req = post_json(
        "/sign-in/email",
        serde_json::json!({
            "email": "signin_snap@example.com",
            "password": "password123"
        }),
    );
    let (status, body) = send_request(&auth, req).await;
    assert_eq!(status, 200);

    with_settings!({snapshot_suffix => "signin"}, {
        assert_yaml_snapshot!(redact(&body));
    });
}

/// GET /get-session response shape
#[tokio::test]
async fn snapshot_get_session_response() {
    let auth = create_test_auth().await;
    let (token, _) = signup_user(
        &auth,
        "session_snap@example.com",
        "password123",
        "Session Snap",
    )
    .await;

    let (status, body) = send_request(&auth, get_with_auth("/get-session", &token)).await;
    assert_eq!(status, 200);

    with_settings!({snapshot_suffix => "get_session"}, {
        assert_yaml_snapshot!(redact(&body));
    });
}

/// GET /list-sessions response shape
#[tokio::test]
async fn snapshot_list_sessions_response() {
    let auth = create_test_auth().await;
    let (token, _) = signup_user(
        &auth,
        "listsess_snap@example.com",
        "password123",
        "ListSess Snap",
    )
    .await;

    let (status, body) = send_request(&auth, get_with_auth("/list-sessions", &token)).await;
    assert_eq!(status, 200);

    with_settings!({snapshot_suffix => "list_sessions"}, {
        assert_yaml_snapshot!(redact(&body));
    });
}

/// POST /sign-out response shape
#[tokio::test]
async fn snapshot_sign_out_response() {
    let auth = create_test_auth().await;
    let (token, _) = signup_user(
        &auth,
        "signout_snap@example.com",
        "password123",
        "Signout Snap",
    )
    .await;

    let (status, body) = send_request(
        &auth,
        post_json_with_auth("/sign-out", serde_json::json!({}), &token),
    )
    .await;
    assert_eq!(status, 200);

    with_settings!({snapshot_suffix => "sign_out"}, {
        assert_yaml_snapshot!(redact(&body));
    });
}

/// POST /change-password response shape
#[tokio::test]
async fn snapshot_change_password_response() {
    let auth = create_test_auth().await;
    let (token, _) = signup_user(
        &auth,
        "chgpwd_snap@example.com",
        "password123",
        "ChgPwd Snap",
    )
    .await;

    let (status, body) = send_request(
        &auth,
        post_json_with_auth(
            "/change-password",
            serde_json::json!({
                "currentPassword": "password123",
                "newPassword": "newpassword456",
                "revokeOtherSessions": "false"
            }),
            &token,
        ),
    )
    .await;
    assert_eq!(status, 200);

    with_settings!({snapshot_suffix => "change_password"}, {
        assert_yaml_snapshot!(redact(&body));
    });
}

/// POST /update-user response shape
#[tokio::test]
async fn snapshot_update_user_response() {
    let auth = create_test_auth().await;
    let (token, _) = signup_user(
        &auth,
        "updusr_snap@example.com",
        "password123",
        "UpdUsr Snap",
    )
    .await;

    let (status, body) = send_request(
        &auth,
        post_json_with_auth(
            "/update-user",
            serde_json::json!({ "name": "Updated Name" }),
            &token,
        ),
    )
    .await;
    assert_eq!(status, 200);

    with_settings!({snapshot_suffix => "update_user"}, {
        assert_yaml_snapshot!(redact(&body));
    });
}

/// POST /delete-user response shape
#[tokio::test]
async fn snapshot_delete_user_response() {
    let auth = create_test_auth().await;
    let (token, _) = signup_user(
        &auth,
        "delusr_snap@example.com",
        "password123",
        "DelUsr Snap",
    )
    .await;

    let (status, body) = send_request(
        &auth,
        post_json_with_auth("/delete-user", serde_json::json!({}), &token),
    )
    .await;
    assert_eq!(status, 200);

    with_settings!({snapshot_suffix => "delete_user"}, {
        assert_yaml_snapshot!(redact(&body));
    });
}

/// POST /change-email response shape
#[tokio::test]
async fn snapshot_change_email_response() {
    let auth = create_test_auth().await;
    let (token, _) = signup_user(
        &auth,
        "chgemail_snap@example.com",
        "password123",
        "ChgEmail Snap",
    )
    .await;

    let (status, body) = send_request(
        &auth,
        post_json_with_auth(
            "/change-email",
            serde_json::json!({ "newEmail": "newemail_snap@example.com" }),
            &token,
        ),
    )
    .await;
    assert_eq!(status, 200);

    with_settings!({snapshot_suffix => "change_email"}, {
        assert_yaml_snapshot!(redact(&body));
    });
}

/// POST /forget-password response shape
#[tokio::test]
async fn snapshot_forget_password_response() {
    let auth = create_test_auth().await;
    signup_user(
        &auth,
        "forgotpwd_snap@example.com",
        "password123",
        "ForgotPwd Snap",
    )
    .await;

    let (status, body) = send_request(
        &auth,
        post_json(
            "/forget-password",
            serde_json::json!({ "email": "forgotpwd_snap@example.com" }),
        ),
    )
    .await;
    assert_eq!(status, 200);

    with_settings!({snapshot_suffix => "forget_password"}, {
        assert_yaml_snapshot!(redact(&body));
    });
}

/// GET /list-accounts response shape
#[tokio::test]
async fn snapshot_list_accounts_response() {
    let auth = create_test_auth().await;
    let (token, _) = signup_user(
        &auth,
        "listacct_snap@example.com",
        "password123",
        "ListAcct Snap",
    )
    .await;

    let (status, body) = send_request(&auth, get_with_auth("/list-accounts", &token)).await;
    assert_eq!(status, 200);

    with_settings!({snapshot_suffix => "list_accounts"}, {
        assert_yaml_snapshot!(redact(&body));
    });
}

/// GET /ok response shape
#[tokio::test]
async fn snapshot_ok_response() {
    let auth = create_test_auth().await;
    let (status, body) = send_request(&auth, get_request("/ok")).await;
    assert_eq!(status, 200);

    with_settings!({snapshot_suffix => "ok"}, {
        assert_yaml_snapshot!(redact(&body));
    });
}

/// Error response shapes (400, 401, 409)
#[tokio::test]
async fn snapshot_error_responses() {
    let auth = create_test_auth().await;

    // 400: Missing required fields
    let (status_400, body_400) =
        send_request(&auth, post_json("/sign-up/email", serde_json::json!({}))).await;
    assert!(status_400 >= 400);

    with_settings!({snapshot_suffix => "error_400"}, {
        assert_yaml_snapshot!(redact(&body_400));
    });

    // 401: Invalid credentials
    let (status_401, body_401) = send_request(
        &auth,
        post_json(
            "/sign-in/email",
            serde_json::json!({
                "email": "nonexistent@example.com",
                "password": "password123"
            }),
        ),
    )
    .await;
    assert_eq!(status_401, 401);

    with_settings!({snapshot_suffix => "error_401"}, {
        assert_yaml_snapshot!(redact(&body_401));
    });

    // 409: Duplicate email
    signup_user(&auth, "dup_snap@example.com", "password123", "Dup User").await;

    let (status_409, body_409) = send_request(
        &auth,
        post_json(
            "/sign-up/email",
            serde_json::json!({
                "name": "Dup User 2",
                "email": "dup_snap@example.com",
                "password": "password456"
            }),
        ),
    )
    .await;
    assert_eq!(status_409, 409);

    with_settings!({snapshot_suffix => "error_409"}, {
        assert_yaml_snapshot!(redact(&body_409));
    });
}