Skip to content

feat: Add legacy client support for email auth migrations - #4712

Merged
marcelomendoncasoares merged 13 commits into
serverpod:mainfrom
exaby73:fix/migrations/old-client-support
Mar 17, 2026
Merged

marcelomendoncasoares merged 13 commits into
serverpod:mainfrom
exaby73:fix/migrations/old-client-support

Conversation

@exaby73

@exaby73 exaby73 commented Feb 10, 2026 •

Copy link
Copy Markdown
Contributor

Pre-launch Checklist

  • I read the Contribute page and followed the process outlined there for submitting PRs.
  • This update contains only one single feature or bug fix and nothing else. (If you are submitting multiple fixes, please make multiple PRs.)
  • I read and followed the Dart Style Guide and formatted the code with dart format.
  • I listed at least one issue that this PR fixes in the description above.
  • I updated/added relevant documentation (doc comments with ///), and made sure that the documentation follows the same style as other Serverpod documentation. I checked spelling and grammar.
  • I added new tests to check the change I am making.
  • All existing and new tests are passing.
  • Any breaking changes are documented below.

If you need help, consider asking for advice on the discussion board.

Breaking changes

None

Summary by CodeRabbit

  • New Features

    • Backward-compatible legacy client support with endpoint name mapping.
    • Legacy session token manager and builder for legacy sessions.
    • Legacy user profile operations (image, username, full name).
    • Legacy email, Google, Firebase, and admin authentication endpoints (stubs where unsupported).
    • Legacy session status, sign-out, and session revocation endpoints.
    • Public legacy data types and protocol exports.
  • Tests

    • Comprehensive integration tests covering legacy client flows and migrations.

@exaby73
exaby73 force-pushed the fix/migrations/old-client-support branch 2 times, most recently from 1c66cc7 to d3c3811 Compare February 10, 2026 18:59
@exaby73

exaby73 commented Feb 10, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Feb 10, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Full review triggered.

@coderabbitai

coderabbitai Bot commented Feb 10, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds legacy-client compatibility to the serverpod_auth_bridge: new legacy endpoints, legacy session token manager and builder, data models, an enableLegacyClientSupport initializer, tests, and expanded public exports to surface legacy types.

Changes

Cohort / File(s) Summary
Public API Exports
modules/serverpod_auth/serverpod_auth_bridge/serverpod_auth_bridge_server/lib/serverpod_auth_bridge_server.dart
Exported legacy helpers and expanded protocol exports to include legacy types (LegacyAuthenticationFailReason, LegacyAuthenticationResponse, LegacySession, LegacyUserInfo, LegacyUserSettingsConfig).
Legacy Support Enablement
modules/serverpod_auth/serverpod_auth_bridge/serverpod_auth_bridge_server/lib/src/business/enable_legacy_client_support.dart
Adds enableLegacyClientSupport(pod) that registers a legacy endpoint dispatcher and maps legacy endpoint names to bridge connectors.
Token Manager & Builder
modules/serverpod_auth/.../lib/src/business/legacy_session_token_manager.dart, .../legacy_session_token_manager_builder.dart
Introduces LegacySessionTokenManager (implements TokenManager) with validate/revoke/revokeAll/listTokens stubs (issueToken unsupported) and a builder for registration.
Legacy Endpoints (stubs)
modules/serverpod_auth/.../lib/src/endpoints/legacy_admin_endpoint.dart, .../legacy_apple_endpoint.dart, .../legacy_firebase_endpoint.dart, .../legacy_google_endpoint.dart
Adds endpoint classes enforcing access control or returning deterministic failure responses for unsupported social auth methods.
Legacy Email Endpoint (full flow)
modules/serverpod_auth/.../lib/src/endpoints/legacy_email_endpoint.dart
Implements legacy email authenticate flow: delegates to new auth, maps exceptions to legacy fail reasons, creates/stores LegacySession (SHA‑256 with salt), returns LegacyAuthenticationResponse; other account/password methods stubbed.
Status & User Endpoints
modules/serverpod_auth/.../lib/src/endpoints/legacy_status_endpoint.dart, .../legacy_user_endpoint.dart
Adds status operations (isSignedIn, signOutDevice/All, getUserInfo, getUserSettingsConfig) and user profile operations (remove/set image, changeUserName/fullName) delegating to AuthServices.
Data Models
modules/serverpod_auth/.../lib/src/models/legacy_authentication_fail_reason.spy.yaml, legacy_authentication_response.spy.yaml, legacy_user_info.spy.yaml, legacy_user_settings_config.spy.yaml
Defines LegacyAuthenticationFailReason enum and models: LegacyAuthenticationResponse, LegacyUserInfo, LegacyUserSettingsConfig.
Test Harness Updates
modules/serverpod_auth/serverpod_auth_bridge/serverpod_auth_bridge_server/test/integration/test_tools/serverpod_test_tools.dart
Adds private legacy endpoint implementations for tests, exposes them on TestEndpoints, and updates _SessionMigrationEndpoint.convertSession to new AuthSuccess type.
Integration Tests
tests/serverpod_auth_test/serverpod_auth_test_server/test/integration/legacy_client_support_test.dart
Adds comprehensive integration tests for legacy client support, test helpers (MutableAuthKeyProvider, _createClient), wiring, and DB cleanup helpers.
Test deps & minor cleanup
modules/serverpod_auth/serverpod_auth_migration/.../auth_migrations_test.dart, templates/pubspecs/.../pubspec.yaml, tests/.../pubspec.yaml
Removed an unused legacy_session import in a migration test and added dev_dependencies for test clients in test pubspecs.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Legacy Client
    participant Endpoint as LegacyEmailEndpoint
    participant AuthSvc as AuthServices
    participant DB as Database
    participant TokenMgr as LegacySessionTokenManager

    Client->>Endpoint: authenticate(email,password)
    Endpoint->>AuthSvc: delegate to email auth
    AuthSvc->>DB: lookup/validate AuthUser & credentials
    DB-->>AuthSvc: user / validation result
    AuthSvc-->>Endpoint: auth result
    Endpoint->>DB: query legacy mapping / insert LegacySession (hash secret)
    DB-->>Endpoint: session created
    Endpoint-->>Client: LegacyAuthenticationResponse(success,key,keyId,userInfo)

    Client->>TokenMgr: validateToken(sessionKey)
    TokenMgr->>DB: lookup LegacySession by key
    DB-->>TokenMgr: session row
    TokenMgr-->>Client: AuthenticationInfo(userId,scopes,authId)
Loading
sequenceDiagram
    participant Server as Server Setup
    participant Support as enableLegacyClientSupport
    participant Bridge as Bridge Module
    participant Dispatch as LegacyEndpointDispatch
    participant Connector as Bridge Connector

    Server->>Support: enableLegacyClientSupport(pod)
    Support->>Bridge: get bridge module instance
    Bridge-->>Support: module
    Support->>Dispatch: create legacy dispatch
    loop for each legacy name mapping
        Support->>Bridge: get connector(mappedName)
        Bridge-->>Support: connector
        Support->>Connector: initialize(connector, server, mappedName, namespace)
        Support->>Dispatch: store connector
    end
    Support->>Server: register dispatch as "serverpod_auth"
    Server-->>Support: registration complete
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description includes only the checklist with all items marked complete, but lacks the required initial summary paragraph describing what the PR changes and which issues it fixes. Add a summary paragraph at the beginning describing the feature and listing at least one issue that this PR fixes.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main feature: adding legacy client support for email auth migrations, which is the primary objective of this PR.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

Issue Planner is now in beta. Read the docs and try it out! Share your feedback on Discord.


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
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🤖 Fix all issues with AI agents
In
`@modules/serverpod_auth/serverpod_auth_bridge/serverpod_auth_bridge_server/lib/src/endpoints/legacy_email_endpoint.dart`:
- Around line 66-76: The SQL in the legacy email lookup selects unused columns;
change the call to session.db.unsafeQuery in the legacy email authentication
flow (the legacyRows query) to only select the id column (e.g., "SELECT id FROM
serverpod_user_info WHERE email = $1 LIMIT 1") so it matches what
LegacyStatusEndpoint.getUserInfo needs and avoids fetching "userIdentifier",
"userName", "fullName", "imageUrl" unnecessarily; keep the same
QueryParameters.positional([email]) and preserve the existing handling that
returns LegacyAuthenticationResponse with
LegacyAuthenticationFailReason.internalError when legacyRows.isEmpty.

In
`@modules/serverpod_auth/serverpod_auth_bridge/serverpod_auth_bridge_server/lib/src/endpoints/legacy_status_endpoint.dart`:
- Around line 48-52: The code runs a raw SQL query using profile?.email which
can be null, then constructs a LegacyUserInfo with many null fields; to fix,
avoid passing null into the SQL and avoid returning a mostly-empty
LegacyUserInfo: check profile for null up front (or explicitly validate
profile.email) and either return null/an appropriate absent response or
short-circuit before querying (use the existing symbols legacyRows and legacyId
to locate the query and return path), or populate LegacyUserInfo with safe
defaults and clear metadata indicating missing profile so downstream clients
(LegacyUserInfo) can reliably detect and handle absent data.

In
`@tests/serverpod_auth_test/serverpod_auth_test_server/test/integration/legacy_client_support_test.dart`:
- Around line 505-514: _update the _cleanUpDatabase(Session session) to also
remove LegacySession rows and ensure deletions occur in the right order: delete
LegacySession entries first (using LegacySession.db.deleteWhere with a where
that matches all rows or relevant authUserId), then delete
RateLimitedRequestAttempt, and finally delete AuthUser to avoid foreign key
violations; reference the existing uses of AuthUser.db.deleteWhere and
RateLimitedRequestAttempt.db.deleteWhere to mirror the deletion pattern and
session parameter.
- Around line 475-482: The tests create a TestSession via sessionBuilder just to
read session.server.port but leave the session open until teardown; update
_createClient and _configurePublicLegacySupport to build the session, read the
base port (session.server.port), then immediately close the session (call the
session's close/stop method) before returning/continuing so the temporary
session isn't left alive — locate sessionBuilder.build(), session.server.port,
and the functions _createClient and _configurePublicLegacySupport to apply this
change.
🧹 Nitpick comments (8)
modules/serverpod_auth/serverpod_auth_bridge/serverpod_auth_bridge_server/lib/src/models/legacy_authentication_fail_reason.spy.yaml (1)

1-8: serialized: byIndex is fragile for future changes — acceptable if intentional for legacy compatibility.

Using byIndex means any future insertion or reorder of values will break serialization compatibility. Since this mirrors a legacy enum, this is likely intentional to match the existing wire format. Just be aware that values must remain in their current order going forward.

modules/serverpod_auth/serverpod_auth_bridge/serverpod_auth_bridge_server/lib/src/business/legacy_session_token_manager.dart (1)

58-67: listTokens always returns an empty list — consider adding a doc comment explaining why.

The empty implementation is a deliberate design choice (legacy sessions aren't enumerable here), but without a comment, future maintainers may think this is a stub waiting to be implemented.

📝 Suggested doc comment
  `@override`
+ /// Legacy sessions are not enumerable through this token manager.
+ /// Returns an empty list by design.
  Future<List<TokenInfo>> listTokens(
    final Session session, {
    required final UuidValue? authUserId,
    final String? method,
    final String? tokenIssuer,
    final Transaction? transaction,
  }) async {
    return [];
  }
modules/serverpod_auth/serverpod_auth_bridge/serverpod_auth_bridge_server/lib/src/business/enable_legacy_client_support.dart (1)

30-36: Missing connectors are silently skipped — consider logging a warning.

If a connector listed in _nameMapping is absent from the bridge module (e.g., due to a misconfiguration or code-gen issue), the loop silently skips it. A debug/warning log would help diagnose why a legacy endpoint isn't reachable.

modules/serverpod_auth/serverpod_auth_bridge/serverpod_auth_bridge_server/lib/src/endpoints/legacy_status_endpoint.dart (1)

7-11: requireLogin is not overridden — sign-out / user-info methods silently no-op for unauthenticated callers.

isSignedIn intentionally works without login, but signOutDevice, signOutAllDevices, and getUserInfo silently skip or return null when unauthenticated. Compare with LegacyUserEndpoint, which overrides requireLogin => true. If the legacy client always sends a session key for these calls, consider adding requireLogin => true here too — isSignedIn can be moved to a separate unauthenticated endpoint, or handled by checking auth state before the framework-level login gate.

If the current behaviour is intentional (the old client indeed calls status.isSignedIn() without a key), then this is fine as-is, but worth a note.

modules/serverpod_auth/serverpod_auth_bridge/serverpod_auth_bridge_server/lib/src/endpoints/legacy_user_endpoint.dart (1)

12-19: Blanket catch (_) swallows all exceptions — consider logging.

All four methods silently return false on any failure, including unexpected errors (e.g., database connection issues, serialization bugs). While this matches the legacy client contract, it makes debugging production issues very difficult. Consider logging the exception at warning/error level before returning false.

Example for removeUserImage (apply similarly to the other three)
   Future<bool> removeUserImage(final Session session) async {
     try {
       final uuid = UuidValue.fromString(session.authenticated!.userIdentifier);
       await AuthServices.instance.userProfiles.removeUserImage(session, uuid);
       return true;
-    } catch (_) {
+    } catch (e, st) {
+      session.log('Failed to remove user image', level: LogLevel.warning, exception: e, stackTrace: st);
       return false;
     }
   }
modules/serverpod_auth/serverpod_auth_bridge/serverpod_auth_bridge_server/lib/src/endpoints/legacy_email_endpoint.dart (2)

51-56: Generic catch (_) swallows all exceptions — consider logging before returning internalError.

Same concern as in LegacyUserEndpoint. An unexpected error (e.g., DB connectivity) will silently return internalError with no server-side trace for debugging.

Proposed fix
-    } catch (_) {
+    } catch (e, st) {
+      session.log(
+        'Unexpected error during legacy email authentication',
+        level: LogLevel.warning,
+        exception: e,
+        stackTrace: st,
+      );
       return LegacyAuthenticationResponse(
         success: false,
         failReason: LegacyAuthenticationFailReason.internalError,
       );
     }

82-93: Consider adding a null-check or assertion on legacySession.id before passing to response.

While insertRow is documented to populate the id field, the returned object's id is still typed as int?. Since LegacyAuthenticationResponse.keyId also accepts int?, the code is type-safe but passes a nullable value. A null-check (e.g., keyId: legacySession.id! or assert(legacySession.id != null); keyId: legacySession.id) would provide explicit safety that the insert operation succeeded before responding to the client.

tests/serverpod_auth_test/serverpod_auth_test_server/test/integration/legacy_client_support_test.dart (1)

384-430: Missing test coverage for createAccount and resetPassword stubs.

The "disabled registration and password operations" group tests createAccountRequest, changePassword, and initiatePasswordReset stubs, but omits createAccount (returns null) and resetPassword (returns false).

@exaby73
exaby73 force-pushed the fix/migrations/old-client-support branch from d3c3811 to bbc6387 Compare February 10, 2026 19:23
@exaby73

exaby73 commented Feb 10, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Feb 10, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In
`@modules/serverpod_auth/serverpod_auth_bridge/serverpod_auth_bridge_server/lib/src/endpoints/legacy_status_endpoint.dart`:
- Around line 24-34: Replace UuidValue.fromString(userIdentifier) with
UuidValue.withValidation(userIdentifier) in both signOutAllDevices and
getUserInfo to ensure the UUID string is validated before use; call
UuidValue.withValidation(session.authenticated!.userIdentifier) (after the null
check) and handle the potential validation error consistently with other
endpoints in the codebase (e.g., propagate or convert the thrown FormatException
into the same error response used elsewhere).
🧹 Nitpick comments (3)
modules/serverpod_auth/serverpod_auth_bridge/serverpod_auth_bridge_server/lib/src/endpoints/legacy_email_endpoint.dart (2)

16-109: Authenticate flow looks well-structured with correct error mapping.

The exception-to-failure-reason mapping, blocked-user check, and session creation logic are clean. The SQL query was already simplified per the previous review to SELECT id only.

One minor observation: on Line 99, legacyRow[0] as int will throw a TypeError at runtime if the underlying DB driver returns the id column as a different type (e.g., BigInt for large serial IDs). Consider a defensive cast:

id: (legacyRow[0] as num).toInt(),

This is unlikely to be an issue with standard Serverpod PostgreSQL drivers but worth noting for robustness.


81-83: Hardcoded 'salty' fallback for the session hash salt.

The default 'salty' is presumably mirroring legacy Serverpod auth behavior for backwards compatibility. If so, this is fine as-is.

However, if no authKeySalt is configured in a deployment, all session hashes will use a well-known salt, weakening offline brute-force resistance against leaked hashes. Consider logging a warning when the fallback is used to nudge operators toward configuring a proper salt.

modules/serverpod_auth/serverpod_auth_bridge/serverpod_auth_bridge_server/test/integration/test_tools/serverpod_test_tools.dart (1)

192-197: _LegacyAdminEndpoint constructor params are unused.

Unlike all other endpoint classes (e.g., _LegacyAppleEndpoint, _LegacyEmailEndpoint), _LegacyAdminEndpoint accepts constructor arguments but doesn't store them as fields. This is generated code, so it may be intentional if the admin endpoint currently has no callable methods. If methods are added later, the generator should regenerate this class.

@exaby73
exaby73 marked this pull request as ready for review February 10, 2026 20:01
@exaby73
exaby73 requested a review from a team February 10, 2026 20:01
@exaby73
exaby73 force-pushed the fix/migrations/old-client-support branch from 100c19f to 9685f5f Compare February 25, 2026 11:37
@exaby73
exaby73 force-pushed the fix/migrations/old-client-support branch from a51c694 to f6371d3 Compare February 25, 2026 12:20
@exaby73
exaby73 requested review from a team and removed request for a team February 25, 2026 12:41

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

Implementation is very clean, now! I have skipped reviewing all test cases for now to focus on the other discussion/suggestions first. Once we're done with the comments on the tests abstraction and implementation I'll jump on the test cases.

exaby73 added 2 commits March 12, 2026 08:34
…client-support

# Conflicts:
#	tests/serverpod_auth_test/serverpod_auth_test_server/pubspec.yaml

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

Nice improvement! A few last comments and we're good to go.

@exaby73
exaby73 force-pushed the fix/migrations/old-client-support branch from fbf1d1b to 40c4af9 Compare March 13, 2026 22:24
@exaby73 exaby73 mentioned this pull request Mar 13, 2026
8 tasks done
@marcelomendoncasoares
marcelomendoncasoares merged commit 2446a63 into serverpod:main Mar 17, 2026
77 checks passed
@github-actions github-actions Bot locked and limited conversation to collaborators Mar 17, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants