Repository navigation
feat: Add legacy client support for email auth migrations - #4712
marcelomendoncasoares merged 13 commits into
Conversation
1c66cc7 to
d3c3811
Compare
|
@coderabbitai full review |
✅ Actions performedFull review triggered. |
📝 WalkthroughWalkthroughAdds 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
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)
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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: byIndexis fragile for future changes — acceptable if intentional for legacy compatibility.Using
byIndexmeans 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:listTokensalways 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
_nameMappingis 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:requireLoginis not overridden — sign-out / user-info methods silently no-op for unauthenticated callers.
isSignedInintentionally works without login, butsignOutDevice,signOutAllDevices, andgetUserInfosilently skip or return null when unauthenticated. Compare withLegacyUserEndpoint, which overridesrequireLogin => true. If the legacy client always sends a session key for these calls, consider addingrequireLogin => truehere too —isSignedIncan 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: Blanketcatch (_)swallows all exceptions — consider logging.All four methods silently return
falseon 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 returningfalse.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: Genericcatch (_)swallows all exceptions — consider logging before returninginternalError.Same concern as in
LegacyUserEndpoint. An unexpected error (e.g., DB connectivity) will silently returninternalErrorwith 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 onlegacySession.idbefore passing to response.While
insertRowis documented to populate theidfield, the returned object'sidis still typed asint?. SinceLegacyAuthenticationResponse.keyIdalso acceptsint?, the code is type-safe but passes a nullable value. A null-check (e.g.,keyId: legacySession.id!orassert(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 forcreateAccountandresetPasswordstubs.The "disabled registration and password operations" group tests
createAccountRequest,changePassword, andinitiatePasswordResetstubs, but omitscreateAccount(returnsnull) andresetPassword(returnsfalse).
d3c3811 to
bbc6387
Compare
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
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 idonly.One minor observation: on Line 99,
legacyRow[0] as intwill throw aTypeErrorat runtime if the underlying DB driver returns theidcolumn as a different type (e.g.,BigIntfor 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
authKeySaltis 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:_LegacyAdminEndpointconstructor params are unused.Unlike all other endpoint classes (e.g.,
_LegacyAppleEndpoint,_LegacyEmailEndpoint),_LegacyAdminEndpointaccepts 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.
100c19f to
9685f5f
Compare
a51c694 to
f6371d3
Compare
marcelomendoncasoares
left a comment
There was a problem hiding this comment.
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.
…client-support # Conflicts: # tests/serverpod_auth_test/serverpod_auth_test_server/pubspec.yaml
marcelomendoncasoares
left a comment
There was a problem hiding this comment.
Nice improvement! A few last comments and we're good to go.
…on` in legacy admin endpoint
fbf1d1b to
40c4af9
Compare
…he `Caller` directly
Pre-launch Checklist
///), and made sure that the documentation follows the same style as other Serverpod documentation. I checked spelling and grammar.If you need help, consider asking for advice on the discussion board.
Breaking changes
None
Summary by CodeRabbit
New Features
Tests