Skip to content

feat: Manage and issue server side session tokens from AuthConfig. - #4127

Merged
SandPod merged 18 commits into
serverpod:mainfrom
SandPod:3856-add-server-side-sessions-to-auth-config
Oct 30, 2025
Merged

SandPod merged 18 commits into
serverpod:mainfrom
SandPod:3856-add-server-side-sessions-to-auth-config

Conversation

@SandPod

@SandPod SandPod commented Oct 29, 2025 •

Copy link
Copy Markdown
Contributor

This PR moves managing server-side sessions into the AuthConfig.
It exposes a simple server-side session TokenManager that can issue tokens. Later, additional configuration for that manager will be added later.

This move allows endpoints and administrators to be token agnostic about what tokens exists in the system.

Follow up:

  • Move JWT token provider into the AuthConfig.
  • Move all providers into AuthConfig and remove AuthServices (Possibly renaming AuthConfig to AuthServices as that seems to be a more fitting name).

Additional information:
When modifying the implementation of the fake token managers it revealed that the tests for multi token manager are dependent on implementation details (accessing the storage and internal state of the fake token manager). These tests need to be refactored so that they only depend on the public interface.

The tests were now only patched to work, but need to be overlooked: a413de4

Related issue: #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

If you have done any breaking changes, make sure to outline them here, so that they can be included in the notes for the next release.

Summary by CodeRabbit

  • Breaking Changes

    • Authentication configuration refactored: AuthConfig.set() now required for setup instead of direct handler initialization
    • Token manager now mandatory in authentication initialization
    • Session pepper configuration required during authentication setup
  • New Features

    • Token-based authentication system enables improved session handling
    • Transaction support added across token operations
    • Configurable token managers with support for multiple token sources

@coderabbitai

coderabbitai Bot commented Oct 29, 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

This PR migrates Serverpod's authentication session handling from static AuthSessions methods to an instance-based architecture with a token-manager abstraction layer. It introduces AuthSessionsTokenManager as a TokenManager implementation, updates core token/session interfaces with transaction parameters and signature changes, and wires token managers through identity providers and authentication endpoints. The static session API is replaced with instance-based calls throughout tests and implementations.

Changes

Cohort / File(s) Summary
AuthConfig & Token Manager Core
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/common/business/auth_config.dart, token_manager.dart, multi_token_manager.dart
Public constructor added to AuthConfig (replacing private ._); TokenIssuer.issueToken signature changed from named to mixed positional-named parameters (Session as first positional); TokenManager.listTokens extended with optional Transaction parameter; MultiTokenManager methods updated to match new signatures with transaction forwarding
AuthSessions Refactoring
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/session/business/auth_sessions.dart, auth_session_config.dart, auth_session_secrets.dart
AuthSessions converted from abstract static-style to concrete instantiable class; constructor now requires AuthSessionConfig; all static methods (createSession, destroySession, listSessions, etc.) become instance methods; AuthSessionConfig gains required sessionKeyHashPepper field; AuthSessionSecrets class removed
SessionKeyHash & Token Manager Adapter
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/session/util/session_key_hash.dart, business/auth_sessions_token_manager.dart, session/session.dart
SessionKeyHash constructor updated to accept saltLength and pepper parameters instead of secrets object; new factory fromConfig added; new AuthSessionsTokenManager class implements TokenManager interface delegating to AuthSessions instance; exported from session library
Admin & Endpoint Updates
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/session/business/auth_sessions_admin.dart, endpoints/status_endpoint.dart, session/endpoints/session_base_endpoint.dart
AuthSessionsAdmin.deleteSessions method added for filtered session deletion; StatusEndpoint gains tokenManager getter and replaces AuthSessions destruction calls with tokenManager.revokeToken/revokeAllTokens; SessionBaseEndpoint class removed
Unified Auth Handler
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/unified.dart
UnifiedAuthTokens gains tokenManager getter; authentication flow updated to try tokenManager.validateToken before falling back to AuthenticationTokens.authenticationHandler
IDP Integration
modules/new_serverpod_auth/serverpod_auth_idp/serverpod_auth_idp_server/lib/src/common/auth_services.dart, providers/{google,apple,email}/business/*
AuthServices gains required tokenManager field; initialize method requires tokenManager parameter; Google, Apple, Email IDPs accept TokenIssuer/TokenManager in constructors; IDPs delegate session creation to token issuers instead of AuthSessions
Passkey & Migration Updates
modules/new_serverpod_auth/serverpod_auth_idp/serverpod_auth_idp_server/lib/src/providers/passkey/endpoints/passkey_account_base_endpoint.dart, modules/new_serverpod_auth/serverpod_auth_bridge/serverpod_auth_bridge_server/lib/src/endpoints/session_migration_endpoint.dart, modules/new_serverpod_auth/serverpod_auth_migration/...
PasskeyAccountBaseEndpoint introduces tokenManager field and replaces AuthSessions.createSession with tokenManager.issueToken; SessionMigrationEndpoint gains tokenManager getter and uses tokenManager.issueToken; migration module tests updated to wire tokenManager into EmailIDP
Test Updates — Auth Core
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/common/business/{contract_tests/token_manager_contract_test.dart,fakes/fake_token_manager.dart}, test/session/integration/auth_sessions_*_test.dart
Contract test suite updated with required description parameter and test group annotation; FakeTokenManager signature matches new issueToken (Session positional); token encoding changed to base64; all session integration tests instantiate local AuthSessions with test pepper instead of using static API; transaction parameter added to listTokens
Test Setup & Example Server
tests/serverpod_new_auth_test/serverpod_new_auth_test_server/lib/server.dart, lib/src/endpoints/auth_test_endpoint.dart, test/integration/*_test.dart
Example server adds sessionKeyHashPepper constant and calls AuthConfig.set with AuthSessionsTokenManager; AuthServices.initialize wired with tokenManager; test endpoints create local AuthSessions instances; integration tests use token manager for validation instead of authentication handler
Backwards Compatibility Tests
modules/new_serverpod_auth/serverpod_auth_bridge/serverpod_auth_bridge_server/test/integration/backwards_compatibility_test.dart, modules/new_serverpod_auth/serverpod_auth_migration/serverpod_auth_migration_server/test/integration/*_test.dart
EmailIDP constructor updated to accept tokenManager parameter; test fixtures initialize AuthSessionsTokenManager with test pepper and pass to EmailIDP

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Endpoint
    participant TokenManager
    participant AuthSessions
    participant Database

    rect rgb(200, 220, 255)
    Note over Client,Database: Old Flow (Static AuthSessions)
    Client->>Endpoint: Request
    Endpoint->>AuthSessions: AuthSessions.createSession()
    AuthSessions->>Database: Insert session
    Database-->>AuthSessions: SessionInfo
    AuthSessions-->>Endpoint: AuthSuccess
    Endpoint-->>Client: Token
    end

    rect rgb(220, 255, 200)
    Note over Client,Database: New Flow (Instance TokenManager)
    Client->>Endpoint: Request
    Endpoint->>TokenManager: tokenManager.issueToken(session, authUserId, method)
    TokenManager->>AuthSessions: authSessions.createSession(...)
    AuthSessions->>Database: Insert session
    Database-->>AuthSessions: SessionInfo
    AuthSessions-->>TokenManager: AuthSuccess
    TokenManager-->>Endpoint: AuthSuccess (base64 encoded token)
    Endpoint-->>Client: Token
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Areas requiring extra attention:

  • API Signature Breaking Changes: TokenIssuer.issueToken parameter order (Session moved from named to positional) and MultiTokenManager.issueToken changes require verification that all call sites are updated correctly
  • AuthSessions Refactoring: Transition from static to instance-based API is pervasive; verify test coverage remains complete and no static call sites remain unreachable
  • Token Encoding Logic: FakeTokenManager now base64-encodes tokens; ensure validation/decoding paths handle all edge cases (invalid base64, null handling)
  • Transaction Parameter Propagation: New Transaction? parameters added to TokenManager.listTokens, issueToken interfaces; verify transaction is correctly threaded through all implementations
  • IDP Constructor Changes: Google, Apple, Email IDPs all gain new token-manager-related parameters; verify all instantiation points supply these (especially in integration/backwards-compatibility tests)
  • AuthSessionConfig Validation: New sessionKeyHashPepper requirement with length validation (min 10 chars); verify all test and production initialization provides valid pepper
  • Session Key Hash Factory: New AuthSessionKeyHash.fromConfig factory; verify it correctly extracts and applies both salt length and pepper

Possibly related PRs

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description Check ⚠️ Warning The PR description provides a general overview of the changes (moving server-side session management into AuthConfig and exposing a TokenManager), but it is missing critical required sections. Most significantly, the Breaking changes section is entirely empty despite the raw summary showing numerous breaking changes including updates to public API signatures across AuthConfig, AuthSessions, TokenManager interfaces, and multiple IDP constructors. The issue reference appears only at the end as "Related issue: #3856" rather than being properly listed in the main description as required by the template. Additionally, nearly all items in the Pre-launch Checklist are unchecked, including documentation updates, test additions, and breaking change documentation, suggesting incomplete preparation for merge. The author should update the description to: (1) list the fixed issue in the main description section in the format requested by the template ("List which issues are fixed by this PR"), (2) document all breaking changes in the Breaking changes section, including the public API signature changes to AuthConfig, AuthSessions, TokenManager, and IDP constructors visible in the code changes, and (3) complete the Pre-launch Checklist items to indicate whether documentation was added, tests were included, and code was formatted according to Dart style guidelines.
✅ Passed checks (1 passed)
Check name Status Explanation
Title Check ✅ Passed The PR title "feat: Manage and issue server side session tokens from AuthConfig" accurately and concisely describes the primary change reflected across the changeset. The raw summary shows extensive modifications to introduce token management through AuthConfig, including a new authentication configuration flow with AuthConfig.set, conversion of AuthSessions from static to instance-based methods, and introduction of AuthSessionsTokenManager. The title directly captures this main objective without being vague or overly broad, making it clear to reviewers scanning history what the primary change is about.

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.

@SandPod
SandPod force-pushed the 3856-add-server-side-sessions-to-auth-config branch from f2b8812 to b2192e1 Compare October 29, 2025 16:39
@SandPod
SandPod force-pushed the 3856-add-server-side-sessions-to-auth-config branch 3 times, most recently from c720ba9 to cd9c40a Compare October 29, 2025 17:05
@SandPod

SandPod commented Oct 29, 2025

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Oct 29, 2025

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

Caution

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

⚠️ Outside diff range comments (2)
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/test/unified_auth_handler_test.dart (1)

22-35: Restore test cleanup for AuthenticationTokens override

AuthenticationTokens.secretsTestOverride is now set in setUp but never cleared, so every later test in the suite keeps running with this mock configuration. That state leak will contaminate unrelated tests that rely on the default secrets. Please reinstate the teardown reset.

     setUp(() async {
       AuthenticationTokens.secretsTestOverride =
           AuthenticationTokenSecretsMock()
             ..setHs512Algorithm()
             ..refreshTokenHashPepper = 'some pepper 123';
 
       session = sessionBuilder.build();
 
       sasAuthSuccess = (await authSessions.createSession(
         session,
         authUserId: await createAuthUser(session),
         scopes: {const Scope('sas')},
         method: 'test',
       ));
 
       jwtAuthSuccess = await AuthenticationTokens.createTokens(
         session,
         authUserId: await createAuthUser(session),
         scopes: {const Scope('jwt')},
         method: 'test',
       );
     });
+
+    tearDown(() {
+      AuthenticationTokens.secretsTestOverride = null;
+    });
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/session/business/auth_sessions.dart (1)

225-249: Honor the optional method filter when deleting sessions.

We now accept an optional method, but the query still removes every session for the user. Callers passing method (for example, to invalidate only one provider) will unexpectedly sign the user out everywhere. Serverpod’s own guidance shows filtering revocations by method when you only want to target a specific auth flow.(docs.serverpod.dev)

Apply this diff so the filter is respected:

-    final auths = await AuthSession.db.deleteWhere(
-      session,
-      where: (final row) => row.authUserId.equals(authUserId),
-      transaction: transaction,
-    );
+    final auths = await AuthSession.db.deleteWhere(
+      session,
+      where: (final row) {
+        var predicate = row.authUserId.equals(authUserId);
+        if (method != null) {
+          predicate = predicate & row.method.equals(method);
+        }
+        return predicate;
+      },
+      transaction: transaction,
+    );
🧹 Nitpick comments (3)
modules/new_serverpod_auth/serverpod_auth_bridge/serverpod_auth_bridge_server/test/integration/backwards_compatibility_test.dart (2)

10-14: Consider test isolation with shared token manager instance.

The tokenManager is instantiated once in main() and shared across all tests. While this works for the current single test, it could cause isolation issues if:

  • Additional tests are added that modify token manager state
  • Tests run in parallel and share mutable state

Consider moving the token manager initialization into setUp() to ensure each test gets a fresh instance, or document why sharing is safe in this context.

setUp(() {
  final tokenManager = AuthSessionsTokenManager(
    config: AuthSessionConfig(
      sessionKeyHashPepper: 'test-pepper',
    ),
  );
  
  session = sessionBuilder.build();
  AuthBackwardsCompatibility.config = AuthBackwardsCompatibilityConfig(
    emailIDP: EmailIDP(
      config: config,
      tokenManager: tokenManager,
    ),
  );
});

17-20: Consider renaming variable to remove "new" prefix.

The variable name newEmailIDP includes a "new" prefix that doesn't add clarity since there's no "old" EmailIDP to distinguish from in this file. Consider renaming to simply emailIDP for better readability.

-  final newEmailIDP = EmailIDP(
+  final emailIDP = EmailIDP(
     config: config,
     tokenManager: tokenManager,
   );

And update the usage:

       AuthBackwardsCompatibility.config = AuthBackwardsCompatibilityConfig(
-        emailIDP: newEmailIDP,
+        emailIDP: emailIDP,
       );
modules/new_serverpod_auth/serverpod_auth_core/serverpod_auth_core_server/lib/src/common/business/auth_config.dart (1)

54-63: Documentation mismatch for additionalTokenManagers.

Doc block still describes this parameter as “a map keyed by strategy name”, but the API now exposes it as a List<TokenManager>. Please update the wording so integrators aren’t misled when wiring their own managers.

Apply this diff to fix the text:

-/// [additionalTokenManagers] is a map of additional token managers keyed by strategy
-/// name (e.g., 'jwt', 'session') that handle token lifecycle operations alongside the
-/// [primaryTokenManager]. The default token manager is always included automatically.
+/// [additionalTokenManagers] is a list of additional token managers that handle token
+/// lifecycle operations alongside the [primaryTokenManager]. The primary manager is
+/// always included automatically.

@SandPod
SandPod force-pushed the 3856-add-server-side-sessions-to-auth-config branch 4 times, most recently from 9c816b6 to 35fbfda Compare October 30, 2025 09:41
@SandPod
SandPod force-pushed the 3856-add-server-side-sessions-to-auth-config branch from 35fbfda to 817e96e Compare October 30, 2025 09:53
@SandPod
SandPod marked this pull request as ready for review October 30, 2025 10:10
@SandPod
SandPod requested review from a team, exaby73 and nielsenko and removed request for exaby73 October 30, 2025 10:11
@SandPod

SandPod commented Oct 30, 2025

Copy link
Copy Markdown
Contributor Author

@coderabbitai This PR implements a simple sever side session token manager, but it is currently not possible to control the additional properties such as how long a session lives. Could you create an issue that is a sub issue to #3856 to address this?

@coderabbitai

coderabbitai Bot commented Oct 30, 2025

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Get details of issue #3856 to understand the parent context
gh issue view 3856 --json number,title,body,url

Length of output: 1976


🏁 Script executed:

#!/bin/bash
# Create a new issue as a sub-issue to #3856 for session lifetime configuration
gh issue create \
  --title "Add configuration for session token properties (lifetime, expiration, etc.) in AuthConfig" \
  --body "## Summary

The server-side session token manager implemented in PR #4127 currently does not expose configuration options for controlling session properties such as session lifetime, expiration policies, and other token-related settings.

## Parent Issue

This is a sub-issue of #3856 - Add shared configuration interface for authentication providers with generalized configuration list.

## Current State

PR #4127 introduces \`AuthSessionsTokenManager\` which manages server-side session tokens, but session configuration properties are not currently exposed through the \`AuthConfig\` interface.

## Requirements

Add configuration options to control session token properties, including:

- Session lifetime/duration (time until expiration)
- Session expiration policies (absolute vs. sliding expiration)
- Session refresh policies
- Maximum concurrent sessions per user
- Session timeout settings
- Other relevant token/session properties

## Proposed Solution

Extend the \`AuthSessionConfig\` or create a new configuration class that can be passed to \`AuthSessionsTokenManager\` through the \`AuthConfig\` setup, allowing developers to customize session behavior based on their application requirements.

## References

- Parent issue: #3856
- Implementing PR: https://github.com/serverpod/serverpod/pull/4127
- Requested by: @SandPod in https://github.com/serverpod/serverpod/pull/4127#discussion_r1 (comment discussion)

## Acceptance Criteria

- [ ] Define session configuration properties
- [ ] Expose configuration through \`AuthConfig\` or related configuration classes
- [ ] Update \`AuthSessionsTokenManager\` to respect configured session properties
- [ ] Add validation for configuration values
- [ ] Add documentation with examples
- [ ] Add tests for various session configuration scenarios" \
  --assignee SandPod

Length of output: 50


@SandPod: I've created issue #4128 to address the configuration of session token properties like lifetime and expiration policies.

The issue is set up as a sub-issue to #3856 and includes:

  • Reference to this PR (feat: Manage and issue server side session tokens from AuthConfig. #4127) and your comment
  • Requirements for session lifetime, expiration policies, refresh policies, and other token properties
  • Proposed solution to extend AuthSessionConfig or related configuration classes
  • Acceptance criteria covering configuration definition, exposure through AuthConfig, implementation, validation, documentation, and tests

You can view and edit the issue here: #4128


🧠 Learnings used
Learnt from: SandPod
PR: serverpod/serverpod#4127
File: modules/new_serverpod_auth/serverpod_auth_idp/serverpod_auth_idp_server/lib/src/providers/passkey/endpoints/passkey_account_base_endpoint.dart:11-16
Timestamp: 2025-10-30T10:11:34.735Z
Learning: In Serverpod authentication endpoints, SandPod prefers eager initialization of AuthConfig-dependent fields (e.g., `final TokenManager tokenManager = AuthConfig.instance.tokenManager;`) rather than lazy getters, to detect misconfiguration at server startup rather than deferring errors until the first request to the endpoint.

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

I think we should avoid the anonymous record type

@nielsenko nielsenko 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 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 a few questions, but everything looks good!

@SandPod
SandPod merged commit eec61be into serverpod:main Oct 30, 2025
@SandPod
SandPod deleted the 3856-add-server-side-sessions-to-auth-config branch October 30, 2025 15:14
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 30, 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