Repository navigation
feat(auth): Add passwordless authentication provider - #4699
Metaildust wants to merge 51 commits into
Conversation
Introduce a generic passwordless (OTP) authentication provider built on SecretChallenge. Includes login request storage, client exceptions, base endpoint, and migrations.
- Add missing auth test server migration for passwordless login requests. - Fix FutureCallsAnalyzer context rooting to avoid missing nested package files on Windows. - Treat melos publish --dry-run exit code 65 as warnings in CI publish check.
Record login request attempts and apply timeframes for verification and completion rate limits to prevent unlimited retries.
c27d0cf to
f244346
Compare
Self-Review NotesOverall DesignThis PR adds a passwordless authentication provider to Key Design Decisions1. Three-Step Flow & Challenge Model
2. Nonce vs. Handle Separation
3. Exception Mapping Strategy
4.
5.
6.
7. Rate Limiting —
Follow-Up Commits
Known Limitations (Out of Scope)
|
hasTooManyAttempts already records the attempt atomically (record + count + rollback-on-exceed), so an additional recordAttempt call double-counts and triggers the rate limit at half the configured maxAttempts threshold. Co-authored-by: Cursor <[email protected]>
|
If this PR looks good and gets merged, I’ll open a new one to complete the remaining SMS steps. The previous draft included too many historical commits, which didn’t align with the approach of this PR. This way, the overall roadmap will be cleaner. |
marcelomendoncasoares
left a comment
There was a problem hiding this comment.
Thanks again for your contribution to improve Serverpod auth and provider coverage on China, @Metaildust! Before digging in more details on the implementation, I have one major topic for us to discuss regarding the unified table approach (see on the comment below).
Add a configurable request store interface and default DB-backed implementation so passwordless request persistence can be customized without changing endpoint behavior.
Decouple passwordless login operations from direct table access and enforce single-consumption semantics before issuing tokens by validating request deletion through the configured store.
Expand passwordless login tests to lock in parity, concurrent token-consumption behavior, and failure-path handling for custom stores.
What changed
Safety / behavior notes
Test coverage added
All related passwordless login tests pass locally. |
marcelomendoncasoares
left a comment
There was a problem hiding this comment.
Excellent work with the changes, @Metaildust! The structure of the request store is very nice. Just a few more comments for discussion/improvement.
Finalize the passwordless generic store pipeline with explicit injection, namespaced nonce persistence, and synced model/migration renames to keep artifacts consistent. Add reviewer-requested and failure-path tests to lock behavior for concurrency, invalid configs, and edge-case request handling.
|
Implemented the requested updates in this PR:
Validation run locally:
|
Restore schema consistency after merging upstream migrations by adding new incremental snapshots for auth_idp and serverpod_auth_test_server. This ensures the generic passwordless request table exists in latest definitions used during fresh database initialization.
Update generated auth IDP repository models so their method signatures align with the current serverpod lockMode/lockBehavior API and pass the serverpod generate consistency check.
Guard the incremental fallback migrations so upgrading from earlier versions that already have the generic passwordless table no longer fails with duplicate table errors.
Revert the out-of-scope analyzer path filtering changes to match origin/main. This prevents empty future-call analysis results on Windows and unblocks Unit tests IO.
Remove the out-of-scope publish check exit-code override so this PR only carries passwordless-related changes.
Create an empty commit to retrigger CI after a transient Unit tests IO (3.38.4, windows-latest) failure.
|
Implemented the requested changes and finalized the PR scope. What changed:
CI context:
Current status:
|
74427a8 to
22d1e37
Compare
Trigger another GitHub Actions run after the previous retry failed on external Docker image pull issues.
Finalize the passwordless provider contract, cleanup semantics, generated artifacts, and regression coverage so typed handles and expired-request flows behave consistently. Sync the branch with the latest sign-in widget localization updates from main to keep the auth modules aligned with the current baseline.
Commit passwordless login requests before post-verification auth work so successful code verification cannot be retried after blocked-user or auth-resolution failures. Add regression coverage to lock the default finishLogin path to single-use behavior while keeping explicit transaction semantics unchanged.
…transaction docs, fix endpoint test teardown - Narrow _defaultDeserializeHandle to catch only FormatException, TypeError, and DeserializationTypeNotFoundException instead of catching all exceptions, so unexpected errors surface correctly. - Add test for unsupported default handle type verifying DeserializationTypeNotFoundException propagation. - Document finishLogin() transaction semantics: default path consumes request in isolated transaction for single-use guarantee; explicit transaction path delegates single-use responsibility to caller. - Add tearDown cleanup to endpoint tests to prevent rate-limit record accumulation across test cases.
…te-limit semantics - Reorder verifyAndCompleteLogin to reject expired requests before running the expensive Argon2 hash verification, reducing CPU/DoS surface on expired codes. - Add test: expired request with wrong verification code yields 'expired' (not 'invalid'). - Document that loginRequestRateLimit records attempts in a separate committed transaction; a subsequent sendLoginVerificationCode failure rolls back the login request but the attempt still counts toward the rate limit window. - Document that sendLoginVerificationCode runs inside the same transaction as the login request creation.
The merge from main interleaved migration 20260324085932263 (serverpod#4799) after our 20260325221209151, violating the required ascending timestamp order. Swap the last two entries to restore correct ordering.
- Count login_verify attempts before processing; record failures only for wrong code, missing request/challenge, unknown id, or concurrent delete. - Do not record attempts on successful verification or expired requests. - Document behavior on PasswordlessIdpConfig.loginVerificationCodeAllowedAttempts. - Add tests and _countPasswordlessLoginVerifyAttempts test helper.
Replace superseded passwordless migrations with a consolidated migration that defines generic_passwordless_login_request using the handle column and matching index. Regenerate protocol models, update PasswordlessLoginRequestStore and passwordless integration tests.
Add passwordless_test_config_defaults to mirror PasswordlessIdpConfig defaults in assertions. Cover sendLoginVerificationCode failures (rate limit still recorded, no pending rows), custom loginVerificationCodeAllowedAttempts, and merge overlapping SecretChallenge and startLogin rate-limit scenarios. Align rate-limit loops with config defaults in base endpoint and login tests.
marcelomendoncasoares
left a comment
There was a problem hiding this comment.
Another round of comments to improve/simplify the implementation. The main point might be removing the handle completely, since it is adding too much friction and we might not have clear use cases for such abstraction. But lets discuss it on the thread.
One request that I have for you is to review more carefully your changes after requesting the next review. We're having a several questions about things that look misplaced, and your answer is always that they are indeed misplaced - either by coming from your package or by copying from the Email IDP without judging. It is expected that you, as first reviewer of your own implementation, prevent these from leaking into the PR. Otherwise we'll be wasting a lot of time going back-and-forth without completing the feature.
I still haven't dig in the tests, which I'm reserving for when we finish with the design - hopefully right after this round.
I'm still on this yet, I apology for my attitude before. Once I'm done I'll request for review. I need there more time to be left this round. Thank you for letting me realize all this, it is really helpful. |
- Simplify finishLogin catch-then-rethrow to let exceptions propagate naturally - Restore PasswordlessIdpUtils with withReplacedServerPasswordlessException - Inline _deserializeHandle at its single call site - Remove passwordless_test_config_defaults.dart, read defaults from fixture - Revert unrelated formatting changes in email_idp_config and config tests - Trim verbose doc comments on passwordless library and endpoint - Rename model class to PasswordlessLoginRequest (drop Generic prefix)
ef525ed to
f31f426
Compare
Add optional `handleType` parameter throughout the passwordless login chain so integrators can distinguish delivery channels (email, sms, etc.) without parsing the handle string.
f31f426 to
3946bb3
Compare
|
Hi @marcelomendoncasoares — thanks for the thorough feedback. I've addressed all points in this round:
On On Point taken on self-review quality — I'll be more careful about catching misplaced patterns and other things I should’ve been aware of before requesting review. No need to do a detailed review yet — if you could just confirm the direction on |
marcelomendoncasoares
left a comment
There was a problem hiding this comment.
We made a good progress from last review, but there are still changes pending to completely remove the THandle generic. We also need to use the SecretChallengeUtil instead of duplicating a lot of its logic.
I took only a superficial look on the tests and noticed that we the main test file passwordless_idp_login_test.dart is about 2k LOC. One suggestion before review is that we should try our best to avoid redundant checks:
- No two tests can validate the exact same scenario.
- When validating an edge case of a previously tested case, we should only
expectincremental validations (not repeat allexpects from the previous tests). - Check that we're following the pattern described in the (in-progress) tests contribution guidelines.
We should also definitely split this file in other files that group related tests. If you look at the Email IDP tests, the max LOC we have is ~750 (and it's already too much). Once we remove all tests for serialization/deserialization of the handle, it will also contribute to reduce the file.
| final maxAttempts = _config.loginVerificationCodeAllowedAttempts; | ||
| final attemptCount = await _verifyRateLimiter.countAttempts( | ||
| session, | ||
| nonce: loginRequestId, | ||
| transaction: transaction, | ||
| ); | ||
| if (attemptCount >= maxAttempts) { | ||
| throw PasswordlessLoginTooManyAttemptsException(); | ||
| } | ||
|
|
||
| final request = await _requestStore.getRequestWithChallenge( | ||
| session, | ||
| requestId: loginRequestId, | ||
| transaction: transaction, | ||
| ); | ||
| final challenge = request?.challenge; | ||
| if (request == null || challenge == null) { | ||
| await _recordVerificationFailureAttempt( | ||
| session, | ||
| loginRequestId: loginRequestId, | ||
| ); | ||
| throw PasswordlessLoginNotFoundException(); | ||
| } | ||
|
|
||
| if (_isExpired(request)) { | ||
| await _requestStore.deleteById( | ||
| session, | ||
| requestId: request.id, | ||
| transaction: transaction, | ||
| ); | ||
| throw PasswordlessLoginExpiredException(); | ||
| } | ||
|
|
||
| if (!await _hashUtil.validateHashFromString( | ||
| secret: verificationCode, | ||
| hashString: challenge.challengeCodeHash, | ||
| )) { | ||
| await _recordVerificationFailureAttempt( | ||
| session, | ||
| loginRequestId: loginRequestId, | ||
| ); | ||
| throw PasswordlessLoginInvalidException(); | ||
| } |
There was a problem hiding this comment.
Question: Following up the same question above, why aren't we using SecretChallenge.verifyChallenge for this? There is also an error on the rate limiting: we're never incrementing the count. But it will be fixed if using verifyChallenge.
There was a problem hiding this comment.
Yes, the current implementation only records invalid / missing / concurrent-consume failures; successful verification and expired requests do not increment the verification attempt count. Counting every request that enters the verification flow is more consistent with the usual “attempt rate limit” semantics, and it also removes this passwordless-specific branch from the shared challenge flow. I’ll align passwordless with that behavior here.
There was a problem hiding this comment.
For discussion: I added verifyAndConsumeChallenge as a sibling one-step flow in SecretChallengeUtil, rather than making passwordless use the existing completion-token flow.
This leaves two possible abstraction shapes:
-
Keep the scoped shared utility approach used here:
SecretChallengeUtilowns shared challenge creation, hash verification, expiration checks, and rate-limit semantics.- Email continues to use the existing completion-token flow.
- Passwordless uses the new consume-immediately flow.
- Trade-off: the util supports multiple flow shapes, so it needs separate configs and runtime guards for invalid method/config combinations.
-
Split into stricter flow-specific abstractions:
- one shared helper for low-level challenge creation / hash validation
- one completion-token flow utility for Email-style flows
- one consume-immediately flow utility for passwordless-style flows
- Benefit: the type system exposes only valid methods for each flow, avoiding nullable internal configs / runtime misuse guards.
- Trade-off: broader refactor and more API surface in the SecretChallenge layer.
Remove THandle and handle serialization from the passwordless provider so handles are consistently modeled as String plus handleType. This commit is limited to the THandle-related API, schema, generated, and test adjustments; broader passwordless test cleanup remains for a follow-up.
…geUtil Add a one-step challenge consumption flow to SecretChallengeUtil and use it for passwordless login so challenge creation, verification, consumption, and rate limiting share the common implementation. Update passwordless docs and tests for the count-every-verification-attempt semantics, including resolver-created AuthUser coverage and fixture cleanup.
Group passwordless login tests by start, finish, verification, and admin cleanup behavior so each file has a narrower review scope. Keep shared rate-limit assertions in a thin helper while preserving the existing scenario coverage.
Refresh the passwordless migrations after incorporating upstream schema changes so the PR carries a clean migration set.
Tighten passwordless handleType across the auth IDP flow and keep generated endpoint defaults aligned so uniqueness, rate limiting, and client signatures all use the same non-null namespace key.
Closes: #2100
Summary
SecretChallenge.PasswordlessLoginRequest(server-only) and client-serializablePasswordlessLoginException/Reason.RateLimitedRequestAttemptUtilsemantics (timeframe + avoid double-counting).Test plan
Context
Refs #2050. This is Step 1 (passwordless-only). Step 2 will refactor the SMS provider to build on this provider (OTP-only), per the issue discussion.