Skip to content

fix(auth): add webauthn tests and fix fallback naming - #1763

Merged
mandarini merged 4 commits into
masterfrom
bewinxed/webauthn-add-tests
Jan 28, 2026
Merged

mandarini merged 4 commits into
masterfrom
bewinxed/webauthn-add-tests

Conversation

@mandarini

@mandarini mandarini commented Oct 10, 2025 •

Copy link
Copy Markdown
Contributor

Moved from: supabase/auth-js#1127
Author: @Bewinxed

What kind of change does this PR introduce?

Enhancement + Small bug fix

  • Add comprehensive tests for the webauthn factorType and its (de)serialization/merging helpers
  • Fix fallback naming for the credential when no friendlyName is provided (maintains backward compatibility)
  • Sanitize test fixtures to remove potentially sensitive WebAuthn artifacts

What is the current behavior?

  • No tests for factorType webauthn
  • When friendlyName is null during WebAuthn credential creation, the code would fail to properly set the credential name
  • Test fixtures contained real WebAuthn data that could be mistaken for actual credentials

What is the new behavior?

  • Added comprehensive test coverage:
    • WebAuthn serialization/deserialization tests
    • WebAuthn helper tests to validate merge operations
    • Tests for credential creation and assertion flows
  • Fixed null friendlyName handling while preserving the original ${user.id}:${friendlyName} format (backward compatible)
  • Sanitized test fixtures: replaced all real WebAuthn artifacts with clearly synthetic test values
  • Configured docker-compose.yml with WebAuthn environment variables for local testing

Additional context

  • No breaking changes - all fixes maintain backward compatibility
  • Test fixtures now use synthetic data (e.g., SYNTHETIC-TEST-CREDENTIAL-ID-..., MOCK-SIGNATURE-...) to avoid confusion with real credentials

Note: The factorId parameter optimization (removing it from request body) will be addressed in a separate PR as it's a breaking change that requires proper versioning.

@mandarini
mandarini requested review from a team as code owners October 10, 2025 14:24
@mandarini mandarini added the auth-js Related to the auth-js library. label Oct 13, 2025
@mandarini mandarini added do-not-merge Do not merge this PR. and removed do-not-merge Do not merge this PR. labels Nov 6, 2025

@fadymak fadymak left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice work @Bewinxed 👏 Thanks for getting those tests added!

Do we need to bump the auth version here for docker-compose?

@Bewinxed

Copy link
Copy Markdown
Contributor

Nice work @Bewinxed 👏 Thanks for getting those tests added!

Do we need to bump the auth version here for docker-compose?

Thank you! Yes we'll need to have a version of auth that has the webauthn changes merged

@fadymak

fadymak commented Nov 10, 2025

Copy link
Copy Markdown
Contributor

Thank you! Yes we'll need to have a version of auth that has the webauthn changes merged

I believe v2.181.0 should have all the changes we're after right? cc: @hf

@mandarini
mandarini force-pushed the bewinxed/webauthn-add-tests branch from 20f51f8 to c518c50 Compare January 22, 2026 10:11
@mandarini
mandarini requested a review from fadymak January 22, 2026 10:12
@mandarini

Copy link
Copy Markdown
Contributor Author

@fadymak i think this should be good to go now, right?

@coveralls

coveralls commented Jan 22, 2026 •

Copy link
Copy Markdown

Coverage Status

coverage: 82.915% (+1.1%) from 81.864%
when pulling b22229a on bewinxed/webauthn-add-tests
into a575212 on master.

@mandarini mandarini self-assigned this Jan 22, 2026
@mandarini
mandarini force-pushed the bewinxed/webauthn-add-tests branch from c518c50 to 753a0ec Compare January 22, 2026 12:26
fadymak
fadymak previously approved these changes Jan 27, 2026
@coderabbitai

coderabbitai Bot commented Jan 28, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Enables WebAuthn MFA via Docker Compose and server config, changes MFA challenge routing to include factorId in the request URL, adds async fallback name resolution in WebAuthn challenge creation, and introduces WebAuthn fixtures and extensive tests for enrollment, challenge, verification, helpers, and serialization.

Changes

Cohort / File(s) Summary
Configuration
packages/core/auth-js/infra/docker-compose.yml
Adds GOTRUE_MFA_WEB_AUTHN_ENROLL_ENABLED=true and GOTRUE_MFA_WEB_AUTHN_VERIFY_ENABLED=true to multiple gotrue-related service environments.
Server config
packages/core/auth-js/test/supabase/config.toml
Un-comments [auth.mfa.web_authn] and sets enroll_enabled = true and verify_enabled = true.
Client — MFA challenge routing
packages/core/auth-js/src/GoTrueClient.ts
Destructures factorId from params, uses it in the request path /factors/{factorId}/challenge, and sends remaining params as the request body.
Client — WebAuthn naming fallback
packages/core/auth-js/src/lib/webauthn.ts
When user.name or user.displayName are missing, asynchronously fetches current user and derives a fallback from user_metadata.name, email, id, or 'User', then populates missing fields.
Test fixtures
packages/core/auth-js/test/webauthn.fixtures.ts
New exports with deterministic creation/assertion fixtures and mock credential objects: webauthnAssertionCredentialResponse, webauthnAssertionMockCredential, webauthnCreationCredentialResponse, webauthnCreationMockCredential.
Tests — GoTrueClient WebAuthn MFA
packages/core/auth-js/test/GoTrueClient.test.ts
Adds WebAuthn MFA test suite covering enrollment, challenge, verify, unenroll, session/no-session cases, and WebAuthn API mocks/serialization helpers.
Tests — WebAuthn helpers
packages/core/auth-js/test/webauthn.helpers.test.ts
New comprehensive tests for deserialize/serialize and merge utilities (creation/request options, responses, defaults, ArrayBuffer handling, native vs polyfill paths).

Sequence Diagram(s)

(omitted)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main changes: adding WebAuthn tests and fixing fallback naming for credentials.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@packages/core/auth-js/test/webauthn.helpers.test.ts`:
- Around line 9-15: The test file is missing the AuthenticatorAttachment type
import, causing a TS error where the code casts 'cross-platform' as
AuthenticatorAttachment; update the import statement in
packages/core/auth-js/test/webauthn.helpers.test.ts (the same block that imports
AuthenticationCredential, AuthenticatorTransportFuture,
PublicKeyCredentialCreationOptionsFuture,
PublicKeyCredentialRequestOptionsFuture, RegistrationCredential) to also import
AuthenticatorAttachment from '../src/lib/webauthn.dom' so the cast is valid.
🧹 Nitpick comments (2)
packages/core/auth-js/src/lib/webauthn.ts (1)

641-653: LGTM! Robust fallback logic for WebAuthn user naming.

The implementation correctly fetches user data to derive sensible fallback values when user.name or user.displayName are missing from the server response. The fallback chain (user_metadata.name → email → id → 'User') provides good coverage for various user states.

💡 Optional: Cache fallbackName result to avoid duplicate evaluation
         if (!user.name || !user.displayName) {
           const currentUser = await this.client.getUser()
           const userData = currentUser.data.user
-          const fallbackName = () =>
+          const fallbackName =
             userData?.user_metadata?.name || userData?.email || userData?.id || 'User'

           if (!user.name) {
-            user.name = friendlyName || fallbackName()
+            user.name = friendlyName || fallbackName
           }
           if (!user.displayName) {
-            user.displayName = friendlyName || fallbackName()
+            user.displayName = friendlyName || fallbackName
           }
         }
packages/core/auth-js/test/GoTrueClient.test.ts (1)

1707-1849: Well-structured WebAuthn MFA test coverage.

The tests comprehensively cover:

  • Error cases (no session, invalid factorId)
  • Enrollment with various friendlyName values
  • Unenrollment flow

The setTimeout delay at line 1828 follows the existing pattern from other MFA tests (line 1417), but polling for state change or using Jest's fake timers could make tests more deterministic and faster.

🔧 Optional: Replace setTimeout with polling for more deterministic tests
// Instead of fixed delay:
await new Promise((resolve) => setTimeout(resolve, 1000))

// Consider polling for the expected state:
const waitForUnenroll = async (maxAttempts = 10) => {
  for (let i = 0; i < maxAttempts; i++) {
    const { data } = await authWithSession.mfa.listFactors()
    const webauthnFactors = data?.all.filter((f) => f.factor_type === 'webauthn') || []
    if (webauthnFactors.length === 0) return
    await new Promise((r) => setTimeout(r, 100))
  }
  throw new Error('Unenroll did not complete in time')
}

@mandarini
mandarini force-pushed the bewinxed/webauthn-add-tests branch from 2e83a2d to 858d00c Compare January 28, 2026 15:47

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@packages/core/auth-js/test/webauthn.fixtures.ts`:
- Around line 76-100: The fixture webauthnCreationCredentialResponse contains
real-looking attestation/public-key payloads (attestationObject, publicKey,
clientDataJSON, authenticatorData) that must be sanitized; replace those fields
with synthetic or generated test values (e.g., use a test helper to produce a
fake RegistrationResponseJSON or static benign base64 strings) so the
RegistrationResponseJSON in webauthnCreationCredentialResponse no longer
contains sensitive/real data; update any test helpers that construct creation
responses to return these synthetic values consistently.
- Around line 10-48: The fixture webauthnAssertionCredentialResponse contains
captured/real WebAuthn artifacts (fields like credentialId, rawId,
credentialResponse.response.signature,
credentialResponse.response.clientDataJSON,
credentialResponse.response.authenticatorData, and authenticatorDataParsed) that
may be device‑identifying or flagged as secrets; replace these with clearly
synthetic or deterministic test values (or redact them) so they cannot be
mistaken for real credentials, and update any dependent tests to accept the
synthetic placeholders (e.g., use fixed base64 strings or "REDACTED" tokens for
credentialId/rawId/signature/clientDataJSON/authenticatorData while preserving
shape and types).
🧹 Nitpick comments (1)
packages/core/auth-js/test/GoTrueClient.test.ts (1)

1634-1705: Restore original globals after WebAuthn mocks.

The block deletes global.navigator/global.PublicKeyCredential without restoring prior values, which can affect later tests (especially in jsdom). Store originals and restore them instead.

♻️ Recommended refactor
 describe('WebAuthn MFA', () => {
+  let originalNavigator: Navigator | undefined
+  let originalPublicKeyCredential: any
+
   beforeEach(() => {
+    originalNavigator = (global as any).navigator
+    originalPublicKeyCredential = (global as any).PublicKeyCredential
+
     // Setup navigator.credentials mock
     if (!global.navigator) {
       global.navigator = {} as Navigator
     }
@@
   afterAll(() => {
-    // `@ts-ignore`
-    delete global.navigator
-    // `@ts-ignore`
-    delete global.PublicKeyCredential
+    if (originalNavigator) {
+      ;(global as any).navigator = originalNavigator
+    } else {
+      // `@ts-ignore`
+      delete global.navigator
+    }
+    if (originalPublicKeyCredential) {
+      ;(global as any).PublicKeyCredential = originalPublicKeyCredential
+    } else {
+      // `@ts-ignore`
+      delete global.PublicKeyCredential
+    }
   })

fadymak
fadymak previously approved these changes Jan 28, 2026
@mandarini mandarini changed the title chore(auth): add webauthn tests fix(auth): add webauthn tests and fix fallback naming Jan 28, 2026
@mandarini
mandarini requested a review from fadymak January 28, 2026 16:38
@mandarini
mandarini merged commit f99a58c into master Jan 28, 2026
20 checks passed
@mandarini
mandarini deleted the bewinxed/webauthn-add-tests branch January 28, 2026 16:54
spydon added a commit to supabase/supabase-flutter that referenced this pull request Jul 9, 2026
## Summary

SDK-701 tracks a supabase-js bug fix (PR supabase/supabase-js#1763,
commit f99a58c) in the WebAuthn MFA enrollment flow:
`mfa.webauthn.enroll` runs the WebAuthn ceremony inline in the browser
and patches the credential creation options' `user.name` before calling
`navigator.credentials.create()`. The fix corrects the fallback naming
so a provided `friendlyName` is used, falling back to user data only
when it is absent.

## Outcome: not_applicable

The Dart SDK does not perform the client-side WebAuthn ceremony inline.
It:

- exposes only the server side of the ceremony through the `passkey` API
in `gotrue` (get options / verify credential), which never touches
`user.name`;
- delegates the device ceremony to a platform passkey plugin, with
`supabase_flutter`'s `passkey_options_mapper.dart` handing the raw
server options to the plugin;
- rejects `webauthn` in `mfa.enroll` (already documented on
`auth.mfa.enroll`), routing WebAuthn through the passkey API instead;
- has no `friendlyName` parameter on passkey registration, as the server
generates the friendly name.

There is therefore no client-side option-patching step where the SDK-701
bug could exist, and the `friendlyName` fallback cannot be reproduced
faithfully in the passkey idiom. This is a JS/browser-ceremony concern
with no meaningful Dart equivalent.

## Compliance matrix

Added `auth.mfa.webauthn_enroll` → `not_applicable` with a note
explaining the divergence, and documented the `not_applicable` status in
the header comment block.

Ref: SDK-701
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

auth-js Related to the auth-js library.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants