Skip to content

feat(auth): Add passwordless authentication provider - #4699

Open
Metaildust wants to merge 51 commits into
serverpod:mainfrom
Metaildust:feat/auth-passwordless-provider
Open

Metaildust wants to merge 51 commits into
serverpod:mainfrom
Metaildust:feat/auth-passwordless-provider

Conversation

@Metaildust

@Metaildust Metaildust commented Feb 5, 2026 •

Copy link
Copy Markdown

Closes: #2100

Summary

  • Add a generic passwordless (OTP) identity provider built on SecretChallenge.
  • Introduce PasswordlessLoginRequest (server-only) and client-serializable PasswordlessLoginException/Reason.
  • Add base endpoint, configurable callbacks, and database migrations.
  • Fix rate limiting to align with RateLimitedRequestAttemptUtil semantics (timeframe + avoid double-counting).

Test plan

  • util/run_tests_update_pubspecs
  • util/run_tests_serverpod_generate
  • dart format --output=none --set-exit-if-changed .
  • dart analyze --fatal-infos --fatal-warnings (serverpod_auth_idp_server + serverpod_auth_idp_client)
  • dart run melos lint

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.

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.
@Metaildust
Metaildust force-pushed the feat/auth-passwordless-provider branch 2 times, most recently from c27d0cf to f244346 Compare February 6, 2026 05:32
@Metaildust

Metaildust commented Feb 6, 2026 •

Copy link
Copy Markdown
Author

Self-Review Notes

Overall Design

This PR adds a passwordless authentication provider to serverpod_auth_idp, following a three-step login flow: startLogin → verifyLoginCode → finishLogin. The architecture is fully aligned with the existing SMS provider pattern (SecretChallengeUtil + DatabaseRateLimitedRequestAttemptUtil + exception mapping layer).

Key Design Decisions

1. Three-Step Flow & Challenge Model

  • Reuses the framework's SecretChallengeUtil; verification and completion each have their own challenge and rate limit.
  • verifyLoginCode returns a completion token (not the final auth token); finishLogin exchanges it for an AuthSuccess.

2. Nonce vs. Handle Separation

  • handle is the user input (email, phone, etc.); nonce is the identifier stored in the DB.
  • The default buildNonce returns the normalized handle as-is. Integrators can customize it (e.g., hash) to meet privacy requirements. This is intentional — keeping the module generic without assuming a specific handle type.

3. Exception Mapping Strategy

  • Internally the server distinguishes Invalid / NotFound / Expired / TooManyAttempts.
  • When serialized to the client, Invalid and NotFound are unified into PasswordlessLoginExceptionReason.invalid to avoid leaking whether a request exists (enumeration prevention).

4. sendLoginVerificationCode Is Optional

  • When set to null, startLogin still creates a request and returns a requestId, but does not deliver the verification code. This is intentional — it allows integrators to deliver codes through other channels, or to use the flow in testing.

5. enableLogin Only Gates start/finish

  • verifyLoginCode is not gated by enableLogin. The semantics: after login is disabled, already-issued verification codes can still be verified, but finishLogin will be blocked.

6. linkCompletionToken Uses Atomic updateWhere

  • Unlike the SMS provider's TOCTOU (check-then-update) pattern, the passwordless provider uses updateWhere with a loginChallengeId.equals(null) condition, ensuring concurrency safety.

7. Rate Limiting — hasTooManyAttempts Is Self-Recording

  • DatabaseRateLimitedRequestAttemptUtil.hasTooManyAttempts internally performs an atomic record + count + rollback-on-exceed cycle, so no separate recordAttempt call is needed (calling both would double-count).
  • The login_verify and login_complete rate limit configs include timeframe: loginVerificationCodeLifetime to match the SMS provider's pattern.

Follow-Up Commits

Commit Description
fix: unblock CI for passwordless auth provider Added missing test-server migration, fixed Windows analyzer issue, handled melos publish --dry-run exit code 65.
fix(auth): enforce passwordless rate limits Added timeframe to login_verify / login_complete rate limit configs.
fix(auth): remove redundant recordAttempt call Removed the extra recordAttempt that was double-counting (hasTooManyAttempts already records internally).

Known Limitations (Out of Scope)

  • Concurrent startLogin: Concurrent requests with the same nonce may trigger a unique index violation (500). The SMS provider has the same pattern; a framework-level fix is suggested as a follow-up.
  • DB uuid_v7 function: The migration uses CREATE OR REPLACE FUNCTION gen_random_uuid_v7() at the database level, shared with other migrations. This follows the existing framework convention.

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]>
@Metaildust

Metaildust commented Feb 6, 2026 •

Copy link
Copy Markdown
Author

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 marcelomendoncasoares left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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).

Comment thread .github/workflows/dart-tests.yaml Resolved
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.
@Metaildust

Copy link
Copy Markdown
Author

What changed

  1. Introduced a configurable persistence abstraction:

    • PasswordlessLoginRequestStore
    • internal DTO: PasswordlessLoginRequestData
    • default implementation: DefaultDbPasswordlessLoginRequestStore
  2. Refactored passwordless flow to use the store instead of direct PasswordlessLoginRequest.db.* access.

  3. Added PasswordlessIdpConfig.loginRequestStore (optional).

    • If not provided, behavior falls back to the default DB-backed store.

Safety / behavior notes

  • Endpoint and client protocol are unchanged.
  • Existing default behavior remains table-backed through the default store.
  • finishLogin now enforces single-consumption semantics by requiring successful request deletion before issuing a token (prevents duplicate token issuance in concurrent finish attempts).
  • Custom-store contract failure paths now map to controlled passwordless exceptions instead of surfacing as server errors.

Test coverage added

  • Default-store parity scenario.
  • Custom-store happy path (without default table usage).
  • Custom-store failure paths:
    • atomic completion-link failure
    • missing verification challenge
    • expiration cleanup
  • Concurrent finishLogin on the same token: only one succeeds.

All related passwordless login tests pass locally.

@marcelomendoncasoares marcelomendoncasoares left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.
@Metaildust

Copy link
Copy Markdown
Author

Implemented the requested updates in this PR:

  • Reverted out-of-scope changes (.github/workflows/dart-tests.yaml and tools/serverpod_cli/lib/src/analyzer/dart/future_calls_analyzer.dart) to keep this PR focused on passwordless only. Any CI/tooling follow-up will be handled in a separate PR.
  • Completed the passwordless genericization end-to-end (PasswordlessIdpConfig, buildNonce, resolveAuthUserId, login flow, and store contract).
  • Renamed the default store to GenericPasswordlessLoginRequestStore and made store wiring explicit.
  • Added fixed nonce namespacing ($domain::$source::$encodedNonce) with strict validation and boundary coverage.
  • Renamed model/table and synchronized generated artifacts + migration snapshots (module and auth test snapshots).
  • Unified duplicated default code generators (passwordless/email) into a shared implementation.
  • Added/refined tests requested in review: scopes propagation, blocked-user behavior, failure paths, concurrency, expiration cleanup, and namespacing edge cases.
  • Refactored tests to clearer Given/When structure, split mixed assertions, and replaced flag-driven fakes with callback/scenario-driven setup.

Validation run locally:

  • dart format --set-exit-if-changed
  • dart analyze --fatal-infos --fatal-warnings
  • serverpod generate
  • dart test test/passwordless
    All passed.

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.
@Metaildust

Metaildust commented Feb 18, 2026 •

Copy link
Copy Markdown
Author

Implemented the requested changes and finalized the PR scope.

What changed:

  • Reverted out-of-scope files from this PR (.github/workflows/dart-tests.yaml, tools/serverpod_cli/lib/src/analyzer/dart/future_calls_analyzer.dart).
  • Completed passwordless genericization end-to-end (generic store contract, explicit store wiring, namespaced nonce format, model/table rename, generated artifacts + migration snapshots).
  • Added incremental and idempotent migrations to cover both fresh setup and upgrade paths.
  • Expanded tests for failure paths, concurrency, scopes propagation, blocked-user behavior, and namespacing boundaries; reorganized tests to scenario-first structure.

CI context:

  • One transient failure occurred on Unit tests IO (3.38.4, windows-latest) in serverpod_cli future-call validation tests.
  • No functional changes were added for that; an empty commit was used only to retrigger CI.

Current status:

@Metaildust
Metaildust force-pushed the feat/auth-passwordless-provider branch from 74427a8 to 22d1e37 Compare February 19, 2026 11:52
Metaildust and others added 15 commits March 26, 2026 03:04
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 marcelomendoncasoares left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

@Metaildust

Metaildust commented Apr 3, 2026 •

Copy link
Copy Markdown
Author

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)
@Metaildust
Metaildust force-pushed the feat/auth-passwordless-provider branch from ef525ed to f31f426 Compare April 5, 2026 08:14
Add optional `handleType` parameter throughout the passwordless login
chain so integrators can distinguish delivery channels (email, sms, etc.)
without parsing the handle string.
@Metaildust
Metaildust force-pushed the feat/auth-passwordless-provider branch from f31f426 to 3946bb3 Compare April 5, 2026 08:25
@Metaildust

Metaildust commented Apr 5, 2026 •

Copy link
Copy Markdown
Author

Hi @marcelomendoncasoares — thanks for the thorough feedback. I've addressed all points in this round:

  • Simplified _consumeLoginRequest — exceptions propagate naturally, no more catch-then-rethrow
  • Restored PasswordlessIdpUtils with withReplacedServerPasswordlessException (matching EmailIdpUtils pattern)
  • Renamed GenericPasswordlessLoginRequest → PasswordlessLoginRequest (class, table, index, migration)
  • Added handleType: String? — threaded through startLogin → DB → finishLogin, passed to both sendLoginVerificationCode and resolveAuthUserId callbacks
  • Trimmed verbose endpoint doc comments to match Email IDP style
  • Removed passwordless_test_config_defaults.dart, inlined from fixture
  • Reverted unrelated formatting changes
  • Inlined _createHashUtil into constructor initializer list (matching Email IDP style)

On THandle: Agreed it adds more complexity than value now that handleType handles channel routing. Happy to remove it in this round if you confirm.

On _consumeLoginRequest simplification: Removed the catch-then-rethrow — exceptions now propagate naturally. One trade-off: expired request cleanup happens inside the transaction, so it rolls back on failure. The admin.deleteExpiredRequests periodic cleanup handles this. Let me know if you'd prefer the cleanup to persist.

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 THandle, I'll make that change first so you can review the final state in one pass. Apologies for the back-and-forth.

@marcelomendoncasoares marcelomendoncasoares left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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:

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.

Comment on lines +163 to +205
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();
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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:

  1. Keep the scoped shared utility approach used here:

    • SecretChallengeUtil owns 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.
  2. 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add email and random number authentication

2 participants