Repository navigation
fix(auth): add webauthn tests and fix fallback naming - #1763
Conversation
Thank you! Yes we'll need to have a version of auth that has the webauthn changes merged |
20f51f8 to
c518c50
Compare
|
@fadymak i think this should be good to go now, right? |
c518c50 to
753a0ec
Compare
753a0ec to
2e83a2d
Compare
📝 WalkthroughWalkthroughEnables WebAuthn MFA via Docker Compose and server config, changes MFA challenge routing to include Changes
Sequence Diagram(s)(omitted) Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
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. Comment |
There was a problem hiding this comment.
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.nameoruser.displayNameare missing from the server response. The fallback chain (user_metadata.name→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
setTimeoutdelay 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') }
2e83a2d to
858d00c
Compare
There was a problem hiding this comment.
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.PublicKeyCredentialwithout 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 + } })
## 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
Moved from: supabase/auth-js#1127
Author: @Bewinxed
What kind of change does this PR introduce?
Enhancement + Small bug fix
webauthnfactorType and its (de)serialization/merging helpersWhat is the current behavior?
webauthnfriendlyNameis null during WebAuthn credential creation, the code would fail to properly set the credential nameWhat is the new behavior?
${user.id}:${friendlyName}format (backward compatible)Additional context
SYNTHETIC-TEST-CREDENTIAL-ID-...,MOCK-SIGNATURE-...) to avoid confusion with real credentialsNote: The
factorIdparameter optimization (removing it from request body) will be addressed in a separate PR as it's a breaking change that requires proper versioning.