Skip to content

feat!: Introduce shared AuthSuccess for all authentication strategies. - #3904

Merged
marcelomendoncasoares merged 11 commits into
serverpod:mainfrom
SandPod:3856-create-common-auth-success
Aug 20, 2025
Merged

marcelomendoncasoares merged 11 commits into
serverpod:mainfrom
SandPod:3856-create-common-auth-success

Conversation

@SandPod

@SandPod SandPod commented Aug 20, 2025 •

Copy link
Copy Markdown
Contributor

This PR introduces a shared AuthSuccess class for all authentication strategies in the new authentication package. This change aims to standardize the response structure for successful authentication across different login mechanisms, making it easier for clients and backend services to consume and handle authentication results consistently.

This work is done in preparation for adding a shared configuration to switch authentication strategy on the Server for all providers.

Relates to: #3856

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

Two breaking changes:

  • AuthSuccess class is updated with a new required fields and has renamed the sessionKey field to token.
  • AuthenticationTokens.createTokens now returns an AuthSuccess object instead of a TokenPair.

Summary by CodeRabbit

  • New Features

    • Added support for multiple authentication strategies (jwt, session) via a new AuthStrategy.
    • Unified auth response as AuthSuccess with fields: authStrategy, token, and optional refreshToken.
    • Session and JWT flows now return token in AuthSuccess.
  • Refactor

    • Replaced sessionKey with token across the SDK and persisted storage.
    • Replaced TokenPair with AuthSuccess; refreshToken is now nullable.
    • Updated public exports to include AuthSuccess.
  • Tests

    • Updated integration and unit tests to use AuthSuccess.token and nullable refreshToken.

@coderabbitai

coderabbitai Bot commented Aug 20, 2025 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

Replaces sessionKey with token across auth flows and introduces AuthStrategy. AuthSuccess now carries authStrategy, token, optional refreshToken, authUserId, and scopeNames. Token generation and session creation return AuthSuccess. Client SessionManager stores token. Tests and exports updated accordingly; TokenPair replaced in JWT paths.

Changes

Cohort / File(s) Summary
Auth models and exports
.../serverpod_auth_core_server/lib/src/common/models/auth_strategy.spy.yaml, .../serverpod_auth_core_server/lib/src/common/models/auth_success.spy.yaml, .../serverpod_auth_core_server/lib/src/jwt/jwt.dart
Added AuthStrategy enum. AuthSuccess now includes authStrategy, token, optional refreshToken; removed sessionKey. Export updated to include AuthSuccess.
JWT token creation API
.../serverpod_auth_core_server/lib/src/jwt/business/authentication_tokens.dart
AuthenticationTokens.createTokens now returns AuthSuccess; fields mapped to token and optional refreshToken; sets authStrategy to jwt.
Session creation API
.../serverpod_auth_core_server/lib/src/session/business/auth_sessions.dart
AuthSessions.createSession now returns AuthSuccess with authStrategy=session and token=buildSessionKey(...). Minor doc fix.
Flutter client session storage
.../serverpod_auth_core_flutter/lib/src/session_manager.dart
SessionManager.setLoggedIn writes token to secure storage (replacing sessionKey).
Flutter core tests
.../serverpod_auth_core_flutter/test/serverpod_auth_session_flutter_test.dart
Updated to new AuthSuccess shape (authStrategy, token); expectations and storage verifications adjusted.
JWT integration tests (server)
.../serverpod_auth_core_server/test/jwt/integration/*
Switched from TokenPair to AuthSuccess; use token instead of accessToken; refreshToken treated as nullable with non-null assertions where required.
Session integration tests (server)
.../serverpod_auth_core_server/test/session/integration/*
Adjusted to read returned token instead of sessionKey from AuthSessions.createSession.
Email account endpoint tests
tests/serverpod_new_auth_test/serverpod_new_auth_test_server/test/integration/email_account_endpoint_test.dart
Replaced authSuccess.sessionKey with authSuccess.token in handler calls and helpers.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Client
  participant Server as Auth Server
  participant JWT as JWT Service
  participant Store as SessionManager (Client)

  rect rgba(200,220,255,0.25)
    note over Client,Server: Authentication (Session-based)
    Client->>Server: Create session (credentials)
    Server-->>Client: AuthSuccess{authStrategy=session, token=sessionKey, authUserId, scopeNames}
    Client->>Store: setLoggedIn(AuthSuccess)
    Store-->>Store: Save token to secure storage
  end

  rect rgba(200,255,220,0.25)
    note over Client,JWT: Authentication (JWT-based)
    Client->>Server: Request tokens (credentials)
    Server->>JWT: createTokens(...)
    JWT-->>Server: AuthSuccess{authStrategy=jwt, token=accessJWT, refreshToken?}
    Server-->>Client: AuthSuccess
    Client->>Store: setLoggedIn(AuthSuccess)
    Store-->>Store: Save token to secure storage
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@SandPod

SandPod commented Aug 20, 2025

Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Aug 20, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Full review triggered.

@SandPod
SandPod marked this pull request as ready for review August 20, 2025 13:21
@SandPod
SandPod requested review from a team and marcelomendoncasoares August 20, 2025 13:22

@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: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_flutter/lib/src/session_manager.dart (1)

82-99: Missing refreshToken persistence in Flutter SessionManager

I searched the entire serverpod_auth_core_flutter package for any refreshToken references (via rg -n '\brefreshToken\b') and found none. The current SessionManager only stores:

  • token
  • authUserId
  • scopeNames

To properly support JWT flows with refresh tokens, please:

• In lib/src/session_manager.dart → setLoggedIn(AuthSuccess authSuccess), also persist the refresh token:

await _secureStorage.set(
  SessionManagerStorageKeys.refreshTokenKey.key,
  authSuccess.refreshToken,
);

(You’ll need to add a corresponding key in SessionManagerStorageKeys.)

• In _init() / your “current auth” getter, read the stored refreshToken and use it for silent renewal when the access token expires.

• In clearSession(), remove the persisted refreshToken alongside the other keys.

If you’re intentionally relying solely on short-lived JWTs (no refresh flow), please confirm that this omission is expected.

modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/session/business/auth_sessions.dart (1)

124-149: Breaking Change: Update .sessionKey to .token in Call Sites

Please update any places still accessing the old sessionKey property on the AuthSuccess returned by createSession, and document this in your PR’s “Breaking changes” section.

• tests/serverpod_new_auth_test/serverpod_new_auth_test_server/test/integration/email_account_endpoint_test.dart:329
Change:

- loginSessionKey = registrationResult.sessionKey;
+ loginSessionKey = registrationResult.token;

No other occurrences of .sessionKey on AuthSuccess were found.

modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/jwt/business/authentication_tokens.dart (1)

69-73: Typo: “paylaod” → “payload”

Small spelling fix in public docs.

Apply this diff:

-    /// These are added on the top level of the paylaod, so be sure not to conflict with the [registered claims](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1),
+    /// These are added on the top level of the payload, so be sure not to conflict with the [registered claims](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1),
🧹 Nitpick comments (27)
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/common/models/auth_strategy.spy.yaml (1)

1-1: Fix grammar in the top-level doc string.

“supported the” → “supported by the”.

Apply this diff:

-### Authentication strategies supported the Serverpod authentication core module
+### Authentication strategies supported by the Serverpod authentication core module
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/common/models/auth_success.spy.yaml (2)

3-4: Widen wording: not all successes are “sessions”.

JWT-based flows aren’t sessions. Suggest a neutral phrasing.

Apply this diff:

-  ### The authentication strategy used for this session.
+  ### The authentication strategy used for this authentication (e.g., JWT or session).

9-10: Document invariants between strategy and tokens.

  • If authStrategy == session, refreshToken should be null.
  • If authStrategy == jwt, token is the access token; refreshToken may be present depending on flow.

Would you like me to add these notes to the model comments and scan/create unit tests that assert these invariants in the business layer?

modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_flutter/lib/src/session_manager.dart (1)

45-51: Consider migrating the storage key from “sessionKey” to a neutral “authToken” with backward compatibility.

You’re now storing JWTs and session keys under a key named sessionKey; that’s confusing and makes future migrations harder. Suggest introducing a new key while continuing to read/write the legacy key for one release.

Apply these changes:

@@
   Future<void> _init() async {
-    final sessionKey = await _secureStorage.get(
-      SessionManagerStorageKeys.sessionKey.key,
-    );
+    // Prefer the new 'authToken' key, but support the legacy 'sessionKey' for backward compatibility.
+    var sessionKey = await _secureStorage.get(
+      SessionManagerStorageKeys.authToken.key,
+    );
+    sessionKey ??= await _secureStorage.get(
+      SessionManagerStorageKeys.sessionKey.key,
+    );
@@
   Future<void> setLoggedIn(AuthSuccess authSuccess) async {
     await _secureStorage.set(
-      SessionManagerStorageKeys.sessionKey.key,
-      authSuccess.token,
+      SessionManagerStorageKeys.authToken.key,
+      authSuccess.token,
     );
+    // Also write legacy key during transition period.
+    await _secureStorage.set(
+      SessionManagerStorageKeys.sessionKey.key,
+      authSuccess.token,
+    );
@@
   Future<void> setLoggedOut() async {
-    await _secureStorage.set(SessionManagerStorageKeys.sessionKey.key, null);
+    await _secureStorage.set(SessionManagerStorageKeys.authToken.key, null);
+    await _secureStorage.set(SessionManagerStorageKeys.sessionKey.key, null);
@@
 enum SessionManagerStorageKeys {
-  sessionKey('serverpod_auth_session.sessionKey'),
+  // New neutral key name for both JWT and session tokens.
+  authToken('serverpod_auth_session.token'),
+  // Legacy key kept for backward compatibility.
+  sessionKey('serverpod_auth_session.sessionKey'),

Follow-up: We should also update any docs/comments that reference “session key” to reflect that the value may be a JWT or a session key.

Also applies to: 84-87, 107-107, 136-144

modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/jwt/integration/authentication_tokens_admin_test.dart (1)

114-128: Avoid non-null assertion with a clearer test flow and rename for accuracy.

Rename tokenPair → authSuccess, assert refreshToken presence before parsing. This improves readability and diagnostics on failures.

Apply this diff:

-          final tokenPair = await AuthenticationTokens.createTokens(
+          final authSuccess = await AuthenticationTokens.createTokens(
             session,
             authUserId: authUserId,
             scopes: {},
           );
 
           refreshTokenIdsInOrderOfCreation.add(
             UuidValue.fromByteList(
-              base64Decode(tokenPair.refreshToken!.split(':')[1]),
+              () {
+                final refreshToken = authSuccess.refreshToken;
+                expect(refreshToken, isNotNull,
+                    reason:
+                        'createTokens() should produce a refreshToken in admin test setup');
+                return base64Decode(refreshToken!.split(':')[1]);
+              }(),
             ),
           );
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/session/integration/auth_sessions_authentication_handler_test.dart (1)

49-50: Optional: rename sessionKey variables to sessionToken for clarity.

Now that the value originates from AuthSuccess.token, naming it sessionToken (or simply token) reduces cognitive overhead in tests.

Do you want me to generate a follow-up patch to rename and update references in this file?

Also applies to: 122-123, 160-161, 221-222

modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/session/integration/auth_sessions_destroy_test.dart (3)

35-45: Assert non-null before dereferencing authInfo to improve test failure diagnostics

authenticationHandler can return null. Immediately dereferencing with ! can obscure the root cause when authentication unexpectedly fails. Add an explicit non-null expectation before using the value (consistent with team testing preferences).

Apply this diff:

         final authInfoABeforeRevocation =
             await AuthSessions.authenticationHandler(
           session,
           sessionKey,
         );
 
+        // Ensure we fail with a clear error if authentication unexpectedly returns null
+        expect(authInfoABeforeRevocation, isNotNull);
+
         final channelName =
             MessageCentralServerpodChannels.revokedAuthentication(
           authInfoABeforeRevocation!.userIdentifier,
         );

129-135: Avoid hand-parsing the token; prefer a stable parse helper or API

Manually splitting on ':' and base64-decoding couples the test to the current token format. If buildSessionKey(...) ever changes its serialization, this will silently break.

  • Prefer using a library/helper to parse the token (e.g., a tryParseSessionKey-like helper) to retrieve authSessionId, if accessible from tests.
  • If such helper isn’t publicly available, consider adding a small, test-only helper in the module to extract the authSessionId in a format-stable way.

If accessible, this is what the intent would look like:

final (:authSessionId, :secret) = tryParseSessionKey(session, destroyedSessionKey)!;
await AuthSessions.destroySession(
  session,
  authSessionId: authSessionId,
);

Please verify whether tryParseSessionKey (or an equivalent) is available to tests or can be exposed via a test-only export.


181-195: Naming consistency: consider renaming variables and descriptions from “session key” to “token”

You’ve correctly switched to .token, but the variables (sessionKey1, sessionKey2, etc.) and test descriptions still refer to “session key”. For clarity with the new unified AuthSuccess.token concept, consider renaming to “token” in variable names and test descriptions. This is cosmetic but helps future maintainers.

tests/serverpod_new_auth_test/serverpod_new_auth_test_server/test/integration/email_account_endpoint_test.dart (4)

113-115: Update test descriptions to say “token” instead of “session key”

The behavioral assertions now validate a token; update the user-facing test descriptions for clarity.

Example edits:

  • “...then it succeeds returning a valid session key.” → “...then it succeeds returning a valid token.”

Also applies to: 153-155, 289-291, 363-366


445-451: Avoid ! on authInfo for clearer failures

Similar to other tests, assert that authInfo is not null before using it. This yields more actionable failures when auth unexpectedly fails.

Apply this diff:

     final authInfo = await AuthSessions.authenticationHandler(
       sessionBuilder.build(),
       authSuccess.token,
     );
 
-    return (sessionKey: authSuccess.token, authUserId: authInfo!.authUserId);
+    expect(authInfo, isNotNull);
+    return (sessionKey: authSuccess.token, authUserId: authInfo!.authUserId);

487-489: Docstring still mentions “session key”; update to “token”

The helper returns a token now; adjust the docstring accordingly.

Apply this diff:

-  /// Returns the new session key after successful password change.
+  /// Returns the new token after a successful password change.

413-451: Optional: rename the returned record field from sessionKey to token for consistency

The extension returns ({String sessionKey, UuidValue authUserId}) but now populates it with authSuccess.token. Consider renaming to reduce confusion across tests.

Apply this diff within the helper:

-  Future<({String sessionKey, UuidValue authUserId})> _registerEmailAccount(
+  Future<({String token, UuidValue authUserId})> _registerEmailAccount(
...
-    return (sessionKey: authSuccess.token, authUserId: authInfo!.authUserId);
+    return (token: authSuccess.token, authUserId: authInfo!.authUserId);

You’ll need to adjust call sites in this file accordingly, e.g.:

// Before
loginSessionKey = registrationResult.sessionKey;

// After
loginSessionKey = registrationResult.token;
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/session/business/auth_sessions.dart (1)

120-122: Minor wording: remove double space and clarify sentence

Small polish to the doc comment.

Apply this diff:

-  /// Send the return value to the client to  use that to authenticate in future calls.
+  /// Send the return value to the client to authenticate future calls.
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/jwt/jwt.dart (1)

11-19: Export AuthStrategy alongside AuthSuccess in jwt.dart

Consumers handling AuthSuccess.authStrategy will commonly need the AuthStrategy enum. Exporting it here lets them pull both types from the JWT barrel without importing protocol.dart separately.

Apply this patch in
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/jwt/jwt.dart:

 export '../generated/protocol.dart'
     show
         AuthenticationTokenInfo,
+        AuthStrategy,
         AuthSuccess,
         RefreshTokenExpiredException,
         RefreshTokenInvalidSecretException,
         RefreshTokenMalformedException,
         RefreshTokenNotFoundException,
         TokenPair;
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/jwt/business/authentication_tokens.dart (2)

59-63: Docstring still says “Creates a new token pair” but method now returns AuthSuccess

Adjust the wording to reflect the AuthSuccess return type and the unified token concept.

Apply this diff:

-  /// Creates a new token pair for the given auth user.
+  /// Creates new JWT credentials (AuthSuccess) for the given auth user.
   ///
-  /// This is akin to creating a new session, and should be used after a successful login or registration.
+  /// This is akin to creating a new session, used after a successful login or registration.

110-192: API consistency: consider returning AuthSuccess from refresh rotation as well

rotateRefreshToken still returns TokenPair, whereas createTokens now returns AuthSuccess. Mixed return types complicate clients. Consider:

  • Adding a new rotateTokens(...) -> Future<AuthSuccess> and deprecating rotateRefreshToken (keeping it for back-compat), or
  • Changing rotateRefreshToken to return AuthSuccess (breaking change, document accordingly).

Example of an additive API to preserve back-compat:

@useResult
static Future<AuthSuccess> rotateTokens(
  final Session session, {
  required final String refreshToken,
  final Transaction? transaction,
}) async {
  final pair = await rotateRefreshToken(
    session,
    refreshToken: refreshToken,
    transaction: transaction,
  );
  // Note: No authUserId/scopeNames here without DB fetch; consider loading the row by id if needed.
  return AuthSuccess(
    authStrategy: AuthStrategy.jwt,
    token: pair.accessToken,
    refreshToken: pair.refreshToken,
    // Optionally populate these with a lookup if required for parity:
    // authUserId: ...,
    // scopeNames: ...,
  );
}
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/jwt/integration/authentication_handler_test.dart (3)

174-177: Add an explicit null-check before using refreshToken! to improve failure diagnostics.

In case createTokens returns an AuthSuccess without a refresh token (misconfiguration, future behavior changes), the test will throw with a less helpful null-assertion error. Add an expect to make failures clearer.

Apply this diff:

-      final newTokenPair = await AuthenticationTokens.rotateRefreshToken(
+      expect(authSuccess.refreshToken, isNotNull);
+      final newTokenPair = await AuthenticationTokens.rotateRefreshToken(
         session,
         refreshToken: authSuccess.refreshToken!,
       );

Consider applying the same pattern to other refreshToken! usages in this file.


51-56: Update stale test descriptions: replace “TokenPair” with neutral wording.

These tests no longer deal with a TokenPair object directly; they use AuthSuccess and then rotate tokens. Updating the description reduces confusion.

Apply this diff:

-  withServerpod(
-      'Given a valid `TokenPair` for a refresh token with scopes and extra claims,',
+  withServerpod(
+      'Given valid authentication tokens (access + refresh) with scopes and extra claims,',

And:

-  withServerpod(
-      'Given a valid `TokenPair` for a refresh token with scopes and extra claims,',
+  withServerpod(
+      'Given valid authentication tokens (access + refresh) with scopes and extra claims,',

Also applies to: 138-147


28-34: Grammar nit: “an non-JWT” → “a non-JWT”.

Tiny clarity fix for the test description.

Apply this diff:

-        'when calling the authentication handler with an non-JWT String, then it returns `null`.',
+        'when calling the authentication handler with a non-JWT String, then it returns `null`.',
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_flutter/test/serverpod_auth_session_flutter_test.dart (4)

38-39: Avoid asserting exact JSON string ordering for scopeNames; decode and compare as a set.

Scope serialization order can be brittle across runtimes. Decode JSON and compare as a set to prevent flaky tests.

Apply this diff:

-      expect(
-        storage.values,
-        {
-          SessionManagerStorageKeys.sessionKey.key: _authSuccess.token,
-          SessionManagerStorageKeys.authUserId.key:
-              _authSuccess.authUserId.toString(),
-          SessionManagerStorageKeys.scopeNames.key: '["test1","test2"]'
-        },
-      );
+      expect(
+        storage.values.length,
+        SessionManagerStorageKeys.values.length,
+      );
+      expect(
+        storage.values[SessionManagerStorageKeys.sessionKey.key],
+        _authSuccess.token,
+      );
+      expect(
+        storage.values[SessionManagerStorageKeys.authUserId.key],
+        _authSuccess.authUserId.toString(),
+      );
+      final scopesRaw =
+          storage.values[SessionManagerStorageKeys.scopeNames.key];
+      final scopes = (jsonDecode(scopesRaw!) as List).toSet();
+      expect(scopes, {'test1', 'test2'});

Also add this import at the top of the file:

import 'dart:convert';

Also applies to: 48-53


68-69: Same JSON-ordering concern in the “then all keys are present” test.

Mirror the safer assertions here too.

Apply this diff:

-      expect(
-        storage.values,
-        {
-          SessionManagerStorageKeys.sessionKey.key: _authSuccess.token,
-          SessionManagerStorageKeys.authUserId.key:
-              _authSuccess.authUserId.toString(),
-          SessionManagerStorageKeys.scopeNames.key: '["test1","test2"]'
-        },
-      );
+      expect(
+        storage.values.length,
+        SessionManagerStorageKeys.values.length,
+      );
+      expect(
+        storage.values[SessionManagerStorageKeys.sessionKey.key],
+        _authSuccess.token,
+      );
+      expect(
+        storage.values[SessionManagerStorageKeys.authUserId.key],
+        _authSuccess.authUserId.toString(),
+      );
+      final scopesRaw =
+          storage.values[SessionManagerStorageKeys.scopeNames.key];
+      final scopes = (jsonDecode(scopesRaw!) as List).toSet();
+      expect(scopes, {'test1', 'test2'});

Also applies to: 80-85


121-129: Split expectations across secure vs default storage; decode scopes as above.

Preserve the intent but avoid brittle string equality for JSON.

Apply this diff:

-      expect(
-        secureStorage.values,
-        {
-          SessionManagerStorageKeys.sessionKey.key: _authSuccess.token,
-        },
-      );
+      expect(
+        secureStorage.values[SessionManagerStorageKeys.sessionKey.key],
+        _authSuccess.token,
+      );
 
-      expect(
-        defaultStorage.values,
-        {
-          SessionManagerStorageKeys.authUserId.key:
-              _authSuccess.authUserId.toString(),
-          SessionManagerStorageKeys.scopeNames.key: '["test1","test2"]'
-        },
-      );
+      expect(
+        defaultStorage.values[SessionManagerStorageKeys.authUserId.key],
+        _authSuccess.authUserId.toString(),
+      );
+      final scopesRaw =
+          defaultStorage.values[SessionManagerStorageKeys.scopeNames.key];
+      final scopes = (jsonDecode(scopesRaw!) as List).toSet();
+      expect(scopes, {'test1', 'test2'});

Also applies to: 130-137


47-53: Optional: Consider aligning naming from “sessionKey” to “token”.

The storage key remains SessionManagerStorageKeys.sessionKey. If the public API has moved to token, consider a follow-up deprecation path and migration doc for renaming the storage key to reduce cognitive overhead. Not a blocker.

If you’d like, I can propose a migration plan and a staged deprecation PR for this rename.

Also applies to: 79-85, 131-137

modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/jwt/integration/authentication_tokens_test.dart (3)

137-139: Add an explicit null-check before using refreshToken!

Same rationale as other tests: prefer a clear assertion before using the null-assertion operator.

Apply this diff:

-        () => AuthenticationTokens.rotateRefreshToken(
-          session,
-          refreshToken: authSuccess.refreshToken!,
-        ),
+        () => AuthenticationTokens.rotateRefreshToken(
+          session,
+          refreshToken: authSuccess.refreshToken!,
+        ),

And insert above the withClock call:

+      expect(authSuccess.refreshToken, isNotNull);

Please replicate this pattern for other refreshToken! usages in this file.


93-100: Update test descriptions to remove “TokenPair” where not accurate anymore.

These tests now use AuthSuccess for initial issuance. Consider neutral phrasing.

Apply these diffs:

-    test('when requesting a new token pair, then one is returned.', () async {
+    test('when requesting new authentication tokens, then one is returned.', () async {
-  withServerpod('Given an initial `TokenPair` and its refreshed successor,', (
+  withServerpod('Given initial authentication tokens and their refreshed successor,', (

Also applies to: 255-263


174-175: Naming nit: Consider renaming newTokenPair to rotatedTokens.

It’s still a TokenPair, but the semantic intent is “rotated” rather than “new”. Readability only.

-      final newTokenPair = await AuthenticationTokens.rotateRefreshToken(
+      final rotatedTokens = await AuthenticationTokens.rotateRefreshToken(
         session,
         refreshToken: authSuccess.refreshToken!,
       );

And adjust subsequent references in the test accordingly.

Also applies to: 188-193

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 9023859 and 13e6b0c.

⛔ Files ignored due to path filters (6)
  • modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_client/lib/src/protocol/common/models/auth_strategy.dart is excluded by !**/lib/src/protocol/**
  • modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_client/lib/src/protocol/common/models/auth_success.dart is excluded by !**/lib/src/protocol/**
  • modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_client/lib/src/protocol/protocol.dart is excluded by !**/lib/src/protocol/**
  • modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/generated/common/models/auth_strategy.dart is excluded by !**/generated/**
  • modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/generated/common/models/auth_success.dart is excluded by !**/generated/**
  • modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/generated/protocol.dart is excluded by !**/generated/**
📒 Files selected for processing (13)
  • modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_flutter/lib/src/session_manager.dart (1 hunks)
  • modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_flutter/test/serverpod_auth_session_flutter_test.dart (8 hunks)
  • modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/common/models/auth_strategy.spy.yaml (1 hunks)
  • modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/common/models/auth_success.spy.yaml (1 hunks)
  • modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/jwt/business/authentication_tokens.dart (2 hunks)
  • modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/jwt/jwt.dart (1 hunks)
  • modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/session/business/auth_sessions.dart (2 hunks)
  • modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/jwt/integration/authentication_handler_test.dart (10 hunks)
  • modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/jwt/integration/authentication_tokens_admin_test.dart (1 hunks)
  • modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/jwt/integration/authentication_tokens_test.dart (13 hunks)
  • modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/session/integration/auth_sessions_authentication_handler_test.dart (4 hunks)
  • modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/session/integration/auth_sessions_destroy_test.dart (3 hunks)
  • tests/serverpod_new_auth_test/serverpod_new_auth_test_server/test/integration/email_account_endpoint_test.dart (6 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-06-18T14:49:11.263Z
Learnt from: tp
PR: serverpod/serverpod#3672
File: tests/serverpod_test_server/test_integration/test_tools/test_session_builder_test.dart:10-30
Timestamp: 2025-06-18T14:49:11.263Z
Learning: In Serverpod test files, tp prefers using nullable late variables for AuthenticationInfo in tests (e.g., `late AuthenticationInfo? authenticationInfo;`) rather than non-nullable ones to avoid using `!` operators and to get clearer error messages when authentication setup fails. This provides better diagnostics when `session.authenticated` returns null.

Applied to files:

  • modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/jwt/integration/authentication_tokens_admin_test.dart
  • modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/session/integration/auth_sessions_destroy_test.dart
  • modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/jwt/integration/authentication_handler_test.dart
  • tests/serverpod_new_auth_test/serverpod_new_auth_test_server/test/integration/email_account_endpoint_test.dart
  • modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/jwt/integration/authentication_tokens_test.dart
  • modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/session/integration/auth_sessions_authentication_handler_test.dart
  • modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_flutter/test/serverpod_auth_session_flutter_test.dart
📚 Learning: 2025-07-15T13:10:16.490Z
Learnt from: tp
PR: serverpod/serverpod#3787
File: modules/new_serverpod_auth/serverpod_auth_apple_account/serverpod_auth_apple_account_server/lib/src/business/apple_accounts.dart:65-67
Timestamp: 2025-07-15T13:10:16.490Z
Learning: In Serverpod Apple authentication, tp prefers adding a `lastRefreshed` field to the database model to track when refresh tokens were last validated, enabling periodic refresh token validation strategy for Apple Sign-In accounts.

Applied to files:

  • modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/common/models/auth_success.spy.yaml
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (35)
  • GitHub Check: Bootstrap tests (3.24.0, ubuntu-latest, tests/bootstrap_project)
  • GitHub Check: Module integration tests in modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server with Flutter 3.32.1
  • GitHub Check: Bootstrap tests (3.32.1, ubuntu-latest, tests/bootstrap_project)
  • GitHub Check: Bootstrap tests (3.24.0, windows-latest, tests/bootstrap_project)
  • GitHub Check: CLI e2e tests (3.32.1, ubuntu-latest, tests/serverpod_cli_e2e_test)
  • GitHub Check: Bootstrap tests (3.32.1, windows-latest, tests/bootstrap_project)
  • GitHub Check: Migration e2e tests (3.32.1)
  • GitHub Check: CLI e2e tests (3.24.0, ubuntu-latest, tests/serverpod_cli_e2e_test)
  • GitHub Check: Serverpod concurrent integration tests (server) (3.32.1)
  • GitHub Check: Migration e2e tests (3.24.0)
  • GitHub Check: Serverpod integration tests (server) (3.32.1)
  • GitHub Check: Serverpod integration tests (server) (3.24.0)
  • GitHub Check: Serverpod concurrent integration tests (server) (3.24.0)
  • GitHub Check: Module integration tests in tests/serverpod_test_nonvector/serverpod_test_nonvector_server with Flutter 3.24.0
  • GitHub Check: Module integration tests in tests/serverpod_test_nonvector/serverpod_test_nonvector_server with Flutter 3.32.1
  • GitHub Check: Module integration tests in modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server with Flutter 3.24.0
  • GitHub Check: dart analyze downgrade (3.32.1, ubuntu-latest)
  • GitHub Check: Flutter unit tests (3.32.1, windows-latest, packages/serverpod_flutter)
  • GitHub Check: dart analyze downgrade (3.24.0, windows-latest)
  • GitHub Check: Unit tests IO (3.24.0, ubuntu-latest)
  • GitHub Check: dart analyze downgrade (3.32.1, windows-latest)
  • GitHub Check: Unit tests IO (3.32.1, windows-latest)
  • GitHub Check: dart analyze downgrade (3.24.0, ubuntu-latest)
  • GitHub Check: Serverpod E2E IO tests (3.24.0)
  • GitHub Check: Unit tests IO (3.24.0, windows-latest)
  • GitHub Check: Unit tests IO (3.32.1, ubuntu-latest)
  • GitHub Check: Serverpod E2E web tests (3.24.0)
  • GitHub Check: Serverpod E2E web tests (3.32.1)
  • GitHub Check: Unit tests Web (3.32.1, windows-latest)
  • GitHub Check: Serverpod E2E IO tests (3.32.1)
  • GitHub Check: dart analyze latest (3.32.1, windows-latest)
  • GitHub Check: serverpod generate (3.32.1)
  • GitHub Check: serverpod generate (3.24.0)
  • GitHub Check: dart analyze (3.24.0, windows-latest)
  • GitHub Check: dart analyze latest (3.32.1, ubuntu-latest)
🔇 Additional comments (17)
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/common/models/auth_strategy.spy.yaml (2)

2-11: Enum definition looks solid and forward-compatible.

byName serialization with a stable, lowercase value set is a good choice. Defaulting to unknown is a safe baseline for extensibility.


3-4: No runtime emission of AuthStrategy.unknown
We’ve confirmed that outside of the generated enum fallback, there are no references to AuthStrategy.unknown in your business logic or serialization flows. All manual assignments in authentication and session code use only jwt or session. The unknown case remains solely a safe-generated default for malformed or unexpected values and will not appear in successful authentication responses.

modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/common/models/auth_success.spy.yaml (1)

2-19: Overall model shape LGTM.

Replacing sessionKey with a shared token plus authStrategy cleanly unifies the response across auth flows.

modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_flutter/lib/src/session_manager.dart (1)

84-87: LGTM: Persisting authSuccess.token to secure storage is correct.

This aligns the Flutter client with the unified AuthSuccess contract.

modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/session/integration/auth_sessions_authentication_handler_test.dart (4)

62-62: LGTM: Using .token from AuthSessions.createSession is correct.


135-135: LGTM: Using .token from AuthSessions.createSession is correct.


174-174: LGTM: Using .token from AuthSessions.createSession is correct.


235-235: LGTM: Using .token from AuthSessions.createSession is correct.

modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/session/integration/auth_sessions_destroy_test.dart (1)

23-30: Migration to AuthSuccess.token looks correct

Using .token from AuthSessions.createSession(...) aligns with the new AuthSuccess contract. No issues spotted.

tests/serverpod_new_auth_test/serverpod_new_auth_test_server/test/integration/email_account_endpoint_test.dart (1)

121-126: Token-based assertions: LGTM

All usages migrated to authSuccess.token and validated through AuthSessions.authenticationHandler(...). Looks consistent across registration, login, and password reset paths.

Also applies to: 161-166, 298-303, 372-377

modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/session/business/auth_sessions.dart (2)

118-118: Typo fix in docs: “decommissioned”

The correction reads well. Thanks for tightening the docs.


188-196: Returning AuthSuccess with authStrategy=AuthStrategy.session and token=buildSessionKey(): LGTM

The new return shape is coherent with the unified AuthSuccess model and keeps session semantics intact. Scope forwarding and user-blocked check are preserved.

modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/jwt/business/authentication_tokens.dart (2)

94-103: AuthSuccess payload construction: LGTM

  • authStrategy: AuthStrategy.jwt
  • token derived from the inserted refresh token
  • refreshToken string included
  • authUserId and scopeNames populated

This aligns with the unified token model.


62-75: Verification complete: createTokens → AuthSuccess is safe

All call sites of AuthenticationTokens.createTokens now bind to an AuthSuccess and use its .token/.refreshToken, not the old .accessToken. The only remaining TokenPair usages are in rotateRefreshToken, which still returns TokenPair as intended. No downstream code expects a TokenPair from createTokens.

modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/jwt/integration/authentication_handler_test.dart (1)

60-61: Solid migration to AuthSuccess; usages look consistent.

createTokens now returns AuthSuccess and the tests correctly read token and (later) refreshToken from it. Access-token validations via authenticationHandler(authSuccess.token) are coherent across tests.

Also applies to: 73-79, 90-91, 103-104, 116-118, 130-131, 206-207

modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_flutter/test/serverpod_auth_session_flutter_test.dart (1)

223-229: AuthSuccess usage in the client SessionManager tests looks correct.

Passing AuthSuccess to setLoggedIn and validating authInfo/authUserId/scopeNames aligns with the new shared type. The test helper _authSuccess is well-formed.

Also applies to: 317-320

modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/jwt/integration/authentication_tokens_test.dart (1)

49-57: AuthSuccess adoption for createTokens is correct; field access via token is consistent.

Decoding and verifying scopes/claims from authSuccess.token is aligned with the new API.

Also applies to: 65-73

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

Just one small variable name detail on a test!

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

Nice consistency!

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

LGTM!

@marcelomendoncasoares
marcelomendoncasoares merged commit a388791 into serverpod:main Aug 20, 2025
@github-actions github-actions Bot locked and limited conversation to collaborators Aug 20, 2025
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.

3 participants