better-auth-api 1.0.0-alpha.5

Plugin implementations for better-auth
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
use std::collections::HashMap;
use std::sync::Arc;

use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use chrono::Duration;

use super::*;
use crate::plugins::test_helpers;
use better_auth_core::{CreatePasskey, CreateUser, HttpMethod};

#[path = "descriptor_tests.rs"]
mod descriptor_tests;

pub(super) fn assert_verification_error(
    result: AuthResult<AuthResponse>,
    status: &str,
    http_status: u16,
    expected: FieldMap,
) -> AuthResult<AuthResponse> {
    let error = result
        .err()
        .ok_or_else(|| AuthError::internal("Passkey verification must throw an APIError"))?;
    assert!(error.is_api_error_instance(better_auth_core::ApiErrorClass::BetterAuth));
    assert_eq!(error.status_value()?, FieldValue::from(status));
    assert_eq!(error.status_code()?, http_status);
    let body = error
        .body_value()?
        .as_object()
        .ok_or_else(|| AuthError::internal("Passkey APIError body must be an object"))?
        .snapshot_fields()?;
    assert_eq!(
        body.keys().collect::<Vec<_>>(),
        expected.keys().collect::<Vec<_>>()
    );
    assert_eq!(body, expected);
    let response = error.to_http_response()?;
    assert_eq!(response.status, http_status);
    assert_eq!(
        serde_json::from_slice::<serde_json::Value>(&response.body.bytes()?)?,
        serde_json::Value::Object(expected.json()?)
    );
    assert!(!response.headers.contains_key("Set-Cookie"));
    Ok(response)
}

#[test]
fn verification_catch_preserves_only_better_auth_instances() -> AuthResult<()> {
    use better_auth_core::{ApiErrorClass, ApiErrorInit};

    for registration in [false, true] {
        for class in [ApiErrorClass::BetterAuth, ApiErrorClass::BetterCall] {
            let error = AuthError::try_api_error(ApiErrorInit {
                class,
                status: "CONFLICT".into(),
                body: FieldMap::from([("message".into(), "callback rejected".into())]).into(),
                ..Default::default()
            })?;
            let original = error.raw_value().cloned();
            let error = super::registration::verification_error(error, registration);
            if class == ApiErrorClass::BetterAuth {
                assert!(
                    error
                        .raw_value()
                        .zip(original.as_ref())
                        .is_some_and(|(value, original)| value.strict_equals(original))
                );
            } else {
                let (status, http_status, code, message) = if registration {
                    (
                        "INTERNAL_SERVER_ERROR",
                        500,
                        "FAILED_TO_VERIFY_REGISTRATION",
                        "Failed to verify registration",
                    )
                } else {
                    (
                        "BAD_REQUEST",
                        400,
                        "AUTHENTICATION_FAILED",
                        "Authentication failed",
                    )
                };
                test_helpers::assert_coded_api_error(&error, status, http_status, code, message);
            }
        }
        let structural = AuthError::from_thrown(
            FieldMap::from([
                ("name".into(), "APIError".into()),
                ("statusCode".into(), 409.0.into()),
            ])
            .into(),
        );
        let error = super::registration::verification_error(structural, registration);
        assert_eq!(error.status_code()?, if registration { 500 } else { 400 });
    }
    Ok(())
}

#[tokio::test]
async fn verification_catch_retains_original_error_and_logger_failure() -> AuthResult<()> {
    use better_auth_core::{
        FieldFunction,
        store::{EphemeralStore, StatelessSchema},
    };
    use std::sync::atomic::{AtomicUsize, Ordering};

    for registration in [false, true] {
        for logger_fails in [false, true] {
            let original: FieldValue =
                FieldMap::from([("cause".into(), "verification".into())]).into();
            let logger_error: FieldValue =
                FieldMap::from([("cause".into(), "logger".into())]).into();
            let calls = Arc::new(AtomicUsize::new(0));
            let logger: better_auth_core::FieldObject = FieldMap::from([
                ("level".into(), "error".into()),
                (
                    "log".into(),
                    FieldFunction::contextual({
                        let original = original.clone();
                        let logger_error = logger_error.clone();
                        let calls = calls.clone();
                        move |_, arguments| {
                            assert_eq!(arguments.len(), 3);
                            assert!(
                                arguments
                                    .first()
                                    .is_some_and(|value| value.strict_equals(&"error".into()))
                            );
                            assert!(arguments.get(1).is_some_and(|value| value.strict_equals(
                                &if registration {
                                    "Failed to verify registration".into()
                                } else {
                                    "Failed to verify authentication".into()
                                }
                            )));
                            assert!(
                                arguments
                                    .get(2)
                                    .is_some_and(|value| value.strict_equals(&original))
                            );
                            calls.fetch_add(1, Ordering::SeqCst);
                            if logger_fails {
                                Err(AuthError::from_thrown(logger_error.clone()))
                            } else {
                                Ok(FieldValue::Undefined)
                            }
                        }
                    })
                    .into(),
                ),
            ])
            .into();
            let mut config = test_helpers::create_test_config();
            config.logger = logger.into();
            let config = Arc::new(config);
            let ctx: AuthContext<StatelessSchema> =
                AuthContext::new(config.clone(), Arc::new(EphemeralStore::new(config)))?;
            let error = ctx
                .with_native_context(Default::default(), |_| async move {
                    Ok(super::registration::verification_error(
                        AuthError::from_thrown(original),
                        registration,
                    ))
                })
                .await?;
            assert_eq!(calls.load(Ordering::SeqCst), 1);
            if logger_fails {
                assert!(
                    error
                        .raw_value()
                        .is_some_and(|value| value.strict_equals(&logger_error))
                );
            } else {
                assert_eq!(error.status_code()?, if registration { 500 } else { 400 });
            }
        }
    }
    Ok(())
}

fn passkey_plugin() -> PasskeyPlugin {
    PasskeyPlugin::new()
        .rp_id("localhost")
        .rp_name("Better Auth Test")
        .origin("http://localhost:3000")
}

#[tokio::test]
async fn native_session_relationship_uses_missing_id_semantics_at_each_passkey_boundary() {
    use better_auth_core::{
        CreateSession,
        store::{EphemeralStore, StatelessSchema},
        user_fields::{UserFieldConfig, UserFieldReference},
    };
    let plugin = passkey_plugin();
    let mut config = test_helpers::create_test_config();
    let _ = config.user.fields_mut().insert(
        "image".into(),
        UserFieldConfig {
            references: Some(UserFieldReference {
                model: "session".into(),
                field: "id".into(),
                ..Default::default()
            }),
            ..Default::default()
        },
    );
    let config = Arc::new(config);
    let ctx: AuthContext<StatelessSchema> = test_helpers::initialize_test_context(
        config.clone(),
        Arc::new(EphemeralStore::new(config)),
        &[&plugin],
    )
    .await
    .unwrap();
    let session = ctx
        .database
        .create_session(CreateSession {
            inherited_fields: Default::default(),
            additional_fields: Default::default(),
            user_id: "canonical-owner".into(),
            expires_at: (chrono::Utc::now() + Duration::hours(1)).into(),
            ip_address: None,
            user_agent: None,
            impersonated_by: None,
            active_organization_id: None,
        })
        .await
        .unwrap();
    let mut user = CreateUser::new()
        .with_email("many-passkey@example.test")
        .with_name("Selected");
    user.image = Some(session.id.typed().unwrap().clone()).into();
    ctx.database.create_user(user).await.unwrap();
    let request = test_helpers::create_auth_request_no_query(
        HttpMethod::Get,
        "/passkey/generate-register-options",
        Some(session.token.typed().unwrap()),
        None,
    );
    let error = plugin
        .handle_generate_register_options(&request, &ctx)
        .await
        .unwrap_err();
    crate::plugins::test_helpers::assert_coded_api_error(
        &error,
        "UNAUTHORIZED",
        401,
        "SESSION_REQUIRED",
        "Passkey registration requires an authenticated session",
    );
    let response = plugin
        .handle_list_user_passkeys(&request, &ctx)
        .await
        .unwrap();
    assert_eq!(response.status, 200);
    assert_eq!(response.body.bytes().unwrap().as_ref(), b"[]");
    let response = plugin
        .handle_generate_authenticate_options(&request, &ctx)
        .await
        .unwrap();
    assert_eq!(response.status, 200);
    let body: serde_json::Value = serde_json::from_slice(&response.body.bytes().unwrap()).unwrap();
    assert!(body.get("allowCredentials").is_none());
}

fn cookie_header(response: &better_auth_core::AuthResponse) -> &str {
    response
        .headers
        .get("Set-Cookie")
        .expect("response should include a Set-Cookie header")
}

fn credential_id(label: &str) -> String {
    URL_SAFE_NO_PAD.encode(label.as_bytes())
}

#[tokio::test]
async fn test_generate_register_options_sets_cookie_and_uses_query_name() {
    let plugin = passkey_plugin();
    let (ctx, user, session) = test_helpers::create_test_context_with_user(
        CreateUser::new()
            .with_email("passkey-test@example.com")
            .with_name("Passkey Tester"),
        Duration::hours(1),
    )
    .await;

    ctx.database
        .create_passkey(CreatePasskey {
            additional_fields: Default::default(),
            user_id: user.id.clone(),
            name: Some("Existing Key".to_string()).into(),
            credential_id: credential_id("cred-existing"),
            public_key: "public-key".to_string(),
            counter: 0,
            device_type: "singleDevice".to_string(),
            backed_up: false,
            transports: Some("usb,nfc".to_string()),
            credential: better_auth_core::PasskeyCredentialState::Legacy(
                "unused by options".into(),
            ),
            aaguid: Some("00000000-0000-0000-0000-000000000000".to_string()).into(),
        })
        .await
        .unwrap();

    let req = test_helpers::create_auth_request(
        HttpMethod::Get,
        "/passkey/generate-register-options",
        Some(session.token.typed().unwrap()),
        None,
        HashMap::from([
            ("name".to_string(), "Custom Account Label".to_string()),
            (
                "authenticatorAttachment".to_string(),
                "cross-platform".to_string(),
            ),
        ]),
    );

    let response = plugin
        .handle_generate_register_options(&req, &ctx)
        .await
        .unwrap();
    assert_eq!(response.status, 200);
    assert!(cookie_header(&response).contains("better-auth-passkey="));

    let body: serde_json::Value = serde_json::from_slice(&response.body.bytes().unwrap()).unwrap();
    assert!(body["challenge"].is_string());
    assert_eq!(body["user"]["name"], "Custom Account Label");
    assert_eq!(
        body["authenticatorSelection"]["authenticatorAttachment"],
        "cross-platform"
    );
    assert_eq!(
        body["excludeCredentials"][0]["id"],
        credential_id("cred-existing")
    );
    assert_eq!(body["excludeCredentials"][0]["transports"][0], "usb");
}

#[tokio::test]
async fn test_generate_authenticate_options_is_get_and_sets_cookie_without_auth() {
    let plugin = passkey_plugin();
    let ctx = test_helpers::create_test_context().await;
    let req = test_helpers::create_auth_request_no_query(
        HttpMethod::Get,
        "/passkey/generate-authenticate-options",
        None,
        None,
    );

    let response = plugin
        .handle_generate_authenticate_options(&req, &ctx)
        .await
        .unwrap();
    assert_eq!(response.status, 200);
    assert!(cookie_header(&response).contains("better-auth-passkey="));

    let body: serde_json::Value = serde_json::from_slice(&response.body.bytes().unwrap()).unwrap();
    assert!(body["challenge"].is_string());
    assert!(body.get("allowCredentials").is_none());
}

#[tokio::test]
async fn test_generate_authenticate_options_with_auth_lists_allow_credentials() {
    let plugin = passkey_plugin();
    let (ctx, user, session) = test_helpers::create_test_context_with_user(
        CreateUser::new()
            .with_email("passkey-test@example.com")
            .with_name("Passkey Tester"),
        Duration::hours(1),
    )
    .await;

    ctx.database
        .create_passkey(CreatePasskey {
            additional_fields: Default::default(),
            user_id: user.id.clone(),
            name: Some("Authenticator".to_string()).into(),
            credential_id: credential_id("cred-auth"),
            public_key: "public-key".to_string(),
            counter: 0,
            device_type: "singleDevice".to_string(),
            backed_up: false,
            transports: Some("internal".to_string()),
            credential: better_auth_core::PasskeyCredentialState::Legacy(
                "unused by options".into(),
            ),
            aaguid: None.into(),
        })
        .await
        .unwrap();

    let req = test_helpers::create_auth_request_no_query(
        HttpMethod::Get,
        "/passkey/generate-authenticate-options",
        Some(session.token.typed().unwrap()),
        None,
    );

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

    let body: serde_json::Value = serde_json::from_slice(&response.body.bytes().unwrap()).unwrap();
    assert_eq!(
        body["allowCredentials"][0]["id"],
        credential_id("cred-auth")
    );
    assert_eq!(body["allowCredentials"][0]["transports"][0], "internal");
}

#[tokio::test]
async fn test_verify_registration_without_challenge_cookie_returns_challenge_not_found() {
    let plugin = passkey_plugin();
    let (ctx, _user, session) = test_helpers::create_test_context_with_user(
        CreateUser::new()
            .with_email("passkey-test@example.com")
            .with_name("Passkey Tester"),
        Duration::hours(1),
    )
    .await;

    let body = serde_json::json!({
        "response": {
            "id": "fake-credential-id",
            "rawId": "ZmFrZS1yYXctaWQ",
            "response": {
                "attestationObject": "ZmFrZS1hdHRlc3RhdGlvbg",
                "clientDataJSON": "ZmFrZS1jbGllbnQtZGF0YQ"
            },
            "type": "public-key"
        }
    });
    let mut req = test_helpers::create_auth_json_request_no_query(
        HttpMethod::Post,
        "/passkey/verify-registration",
        Some(session.token.typed().unwrap()),
        Some(body),
    );
    req.headers
        .insert("origin".to_string(), "http://localhost:3000".to_string());

    assert_verification_error(
        plugin.handle_verify_registration(&req, &ctx).await,
        "BAD_REQUEST",
        400,
        FieldMap::from([
            ("message".into(), "Challenge not found".into()),
            ("code".into(), "CHALLENGE_NOT_FOUND".into()),
        ]),
    )
    .unwrap();
}

#[tokio::test]
async fn test_verify_authentication_without_challenge_cookie_returns_challenge_not_found() {
    let plugin = passkey_plugin();
    let ctx = test_helpers::create_test_context().await;

    let body = serde_json::json!({
        "response": {
            "id": credential_id("cred-auth"),
            "rawId": credential_id("cred-auth"),
            "response": {
                "authenticatorData": "ZmFrZS1hdXRoLWRhdGE",
                "clientDataJSON": "ZmFrZS1jbGllbnQtZGF0YQ",
                "signature": "ZmFrZS1zaWduYXR1cmU"
            },
            "type": "public-key"
        }
    });
    let mut req = test_helpers::create_auth_json_request_no_query(
        HttpMethod::Post,
        "/passkey/verify-authentication",
        None,
        Some(body),
    );
    req.headers
        .insert("origin".to_string(), "http://localhost:3000".to_string());

    assert_verification_error(
        plugin.handle_verify_authentication(&req, &ctx).await,
        "BAD_REQUEST",
        400,
        FieldMap::from([
            ("message".into(), "Challenge not found".into()),
            ("code".into(), "CHALLENGE_NOT_FOUND".into()),
        ]),
    )
    .unwrap();
}

#[tokio::test]
async fn test_list_user_passkeys_matches_upstream_optional_fields() {
    let plugin = passkey_plugin();
    let (ctx, user, session) = test_helpers::create_test_context_with_user(
        CreateUser::new()
            .with_email("passkey-test@example.com")
            .with_name("Passkey Tester"),
        Duration::hours(1),
    )
    .await;

    ctx.database
        .create_passkey(CreatePasskey {
            additional_fields: Default::default(),
            user_id: user.id.clone(),
            name: None.into(),
            credential_id: credential_id("cred-list"),
            public_key: "public-key".to_string(),
            counter: 0,
            device_type: "singleDevice".to_string(),
            backed_up: false,
            transports: None,
            credential: better_auth_core::PasskeyCredentialState::Legacy(
                "unused by options".into(),
            ),
            aaguid: Some("00000000-0000-0000-0000-000000000000".to_string()).into(),
        })
        .await
        .unwrap();

    let req = test_helpers::create_auth_request_no_query(
        HttpMethod::Get,
        "/passkey/list-user-passkeys",
        Some(session.token.typed().unwrap()),
        None,
    );
    let response = plugin.handle_list_user_passkeys(&req, &ctx).await.unwrap();
    assert_eq!(response.status, 200);

    let body: serde_json::Value = serde_json::from_slice(&response.body.bytes().unwrap()).unwrap();
    assert!(body[0].get("updatedAt").is_none());
    assert_eq!(body[0]["aaguid"], "00000000-0000-0000-0000-000000000000");
    assert_eq!(body[0].get("name"), Some(&serde_json::Value::Null));
}

#[tokio::test]
async fn test_delete_passkey_non_owner_is_forbidden() {
    let plugin = passkey_plugin();
    let (ctx, _user, session) = test_helpers::create_test_context_with_user(
        CreateUser::new()
            .with_email("owner@example.com")
            .with_name("Owner"),
        Duration::hours(1),
    )
    .await;
    let other = test_helpers::create_user(
        &ctx,
        CreateUser::new()
            .with_email("other@example.com")
            .with_name("Other"),
    )
    .await;

    let passkey = ctx
        .database
        .create_passkey(CreatePasskey {
            additional_fields: Default::default(),
            user_id: other.id.clone(),
            name: Some("Other Key".to_string()).into(),
            credential_id: credential_id("cred-other-delete"),
            public_key: "public-key".to_string(),
            counter: 0,
            device_type: "singleDevice".to_string(),
            backed_up: false,
            transports: None,
            credential: better_auth_core::PasskeyCredentialState::Legacy(
                "unused by options".into(),
            ),
            aaguid: None.into(),
        })
        .await
        .unwrap();

    let req = test_helpers::create_auth_json_request_no_query(
        HttpMethod::Post,
        "/passkey/delete-passkey",
        Some(session.token.typed().unwrap()),
        Some(serde_json::json!({ "id": passkey.id })),
    );

    let err = plugin.handle_delete_passkey(&req, &ctx).await.unwrap_err();
    assert!(err.is_api_error_instance(better_auth_core::ApiErrorClass::BetterAuth));
    assert_eq!(err.status_value().unwrap(), "UNAUTHORIZED".into());
    assert_eq!(err.status_code().unwrap(), 401);
    assert!(err.body_value().unwrap().is_undefined());
    assert!(
        better_auth_core::ResponseBody::Native(err.body_value().unwrap())
            .bytes()
            .unwrap()
            .is_empty()
    );
    assert_eq!(
        ctx.database
            .get_passkey_by_id(passkey.id.typed().unwrap())
            .await
            .unwrap(),
        Some(passkey)
    );
}

#[tokio::test]
async fn test_update_passkey_non_owner_uses_ts_error_message() {
    let plugin = passkey_plugin();
    let (ctx, _user, session) = test_helpers::create_test_context_with_user(
        CreateUser::new()
            .with_email("owner@example.com")
            .with_name("Owner"),
        Duration::hours(1),
    )
    .await;
    let other = test_helpers::create_user(
        &ctx,
        CreateUser::new()
            .with_email("other@example.com")
            .with_name("Other"),
    )
    .await;

    let passkey = ctx
        .database
        .create_passkey(CreatePasskey {
            additional_fields: Default::default(),
            user_id: other.id.clone(),
            name: Some("Other Key".to_string()).into(),
            credential_id: credential_id("cred-other-update"),
            public_key: "public-key".to_string(),
            counter: 0,
            device_type: "singleDevice".to_string(),
            backed_up: false,
            transports: None,
            credential: better_auth_core::PasskeyCredentialState::Legacy(
                "unused by options".into(),
            ),
            aaguid: None.into(),
        })
        .await
        .unwrap();

    let req = test_helpers::create_auth_json_request_no_query(
        HttpMethod::Post,
        "/passkey/update-passkey",
        Some(session.token.typed().unwrap()),
        Some(serde_json::json!({
            "id": passkey.id,
            "name": "Hijacked",
        })),
    );

    let err = plugin.handle_update_passkey(&req, &ctx).await.unwrap_err();
    test_helpers::assert_coded_api_error(
        &err,
        "UNAUTHORIZED",
        401,
        "YOU_ARE_NOT_ALLOWED_TO_REGISTER_THIS_PASSKEY",
        "You are not allowed to register this passkey",
    );
}