Skip to content

fix: improve session handling to avoid calling session refresh logic consecutively#3083

Merged
mcstepp merged 15 commits intomainfrom
fix-middleware
Apr 9, 2025
Merged

fix: improve session handling to avoid calling session refresh logic consecutively#3083
mcstepp merged 15 commits intomainfrom
fix-middleware

Conversation

@mcstepp
Copy link
Collaborator

@mcstepp mcstepp commented Apr 7, 2025

What does this PR do?

  • Leverages RSC caching for auth functions on pages
  • Moves session handling logic to RSC auth components and out of middleware
  • Makes middleware lightweight to check only for public routes and obviously unauthenticated requests

Objective: Fix session refresh logic to not invalidate our refresh token with edge middleware running repeatedly

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • Chore (refactoring code, technical debt, workflow improvements)
  • Enhancement (small improvements)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How should this be tested?

  • Manual testing

Checklist

Required

  • Filled out the "How to test" section in this PR
  • Read Contributing Guide
  • Self-reviewed my own code
  • Commented on my code in hard-to-understand areas
  • Ran pnpm build
  • Ran pnpm fmt
  • Checked for warnings, there are none
  • Removed all console.logs
  • Merged the latest changes from main onto my branch with git pull origin main
  • My changes don't cause any responsiveness issues

Appreciated

  • If a UI change was made: Added a screen recording or screenshots to this PR
  • Updated the Unkey Docs if changes were necessary

Summary by CodeRabbit

  • New Features

    • Introduced a public endpoint for refreshing authentication tokens, ensuring uninterrupted user sessions.
  • Refactor

    • Streamlined the authentication flow for more efficient and consistent session validation.
    • Enhanced middleware logic to rely on simplified checks, contributing to a smoother and more responsive dashboard experience.
    • Updated user and organization ID retrieval methods for improved clarity and performance.
    • Modified authentication mechanisms to improve session management and user handling.
    • Implemented a new authentication strategy to ensure better user session management.
    • Simplified the presentation of required fields in the OpenAPI schema definitions.

@changeset-bot
Copy link

changeset-bot bot commented Apr 7, 2025

⚠️ No Changeset found

Latest commit: 789e641

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@vercel
Copy link

vercel bot commented Apr 7, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
dashboard ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 9, 2025 6:55pm
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 9, 2025 6:55pm
play ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 9, 2025 6:55pm
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 9, 2025 6:55pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 7, 2025

📝 Walkthrough

Walkthrough

This pull request refactors the authentication flow across several modules. It replaces namespaced method calls (e.g., auth.getCurrentUser()) with direct function calls using getCurrentUser and getAuth. The changes affect how the current user and organization ID are retrieved in UI components and backend utilities, with redundant asynchronous calls removed. Additionally, authentication logic in middleware has been simplified to a basic session cookie presence check, and new caching measures have been introduced. An extra public path for refreshing authentication is also added.

Changes

File(s) Change Summary
apps/dashboard/app/auth/layout.tsx, apps/dashboard/app/new/create-ratelimit.tsx, apps/dashboard/app/new/page.tsx, apps/dashboard/lib/auth.ts, apps/dashboard/lib/auth/utils.ts, apps/dashboard/lib/trpc/context.ts Updated user retrieval and authentication calls: replaced auth.getCurrentUser() with direct getCurrentUser()/getAuth(), removed redundant async calls for organization ID, and adjusted return types and caching.
apps/dashboard/lib/auth/base-provider.ts, apps/dashboard/lib/auth/get-auth.ts, apps/dashboard/middleware.ts Simplified session cookie validation in the middleware: reduced internal session validation logic, added a response header (x-middleware-processed), and added the public path "/api/auth/refresh".
apps/dashboard/app/auth/actions.ts Added a comma at the end of the message property in the completeOrgSelection function return object.
go/apps/api/openapi/openapi.json Reformatted "required" fields in various schemas to a single-line array format for consistency.

Possibly related PRs

  • fix: don't load memberships for no reason #3046: The changes in the main PR and the retrieved PR are related as both involve modifications to the user authentication logic, specifically the handling of user retrieval methods in the create-ratelimit.tsx file and the getAuth function.

Suggested labels

Bug, 🕹️ oss.gg, :joystick: 150 points

Suggested reviewers

  • perkinsjr
  • chronark
  • ogzhanolguncu
  • MichaelUnkey

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1235ac1 and f37eb31.

📒 Files selected for processing (1)
  • apps/dashboard/app/auth/layout.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/dashboard/app/auth/layout.tsx
⏰ Context from checks skipped due to timeout of 90000ms (15)
  • GitHub Check: Test Go API Local / Test (Shard 6/8)
  • GitHub Check: Test Packages / Test ./internal/id
  • GitHub Check: Test Go API Local / Test (Shard 7/8)
  • GitHub Check: Test Go API Local / Test (Shard 3/8)
  • GitHub Check: Test Packages / Test ./packages/nextjs
  • GitHub Check: Test Go API Local / Test (Shard 4/8)
  • GitHub Check: Test Packages / Test ./packages/api
  • GitHub Check: Test Go API Local / Test (Shard 2/8)
  • GitHub Check: Test Packages / Test ./internal/clickhouse
  • GitHub Check: Test Packages / Test ./internal/resend
  • GitHub Check: Test Packages / Test ./packages/cache
  • GitHub Check: Test API / API Test Local
  • GitHub Check: Test Agent Local / test_agent_local
  • GitHub Check: Build / Build
  • GitHub Check: Analyze (javascript-typescript)

🪧 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.
    • Generate unit testing code for this file.
    • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

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

@github-actions
Copy link
Contributor

github-actions bot commented Apr 7, 2025

Thank you for following the naming conventions for pull request titles! 🙏

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
apps/dashboard/app/new/page.tsx (1)

3-26: Consider removing unused variable
The _auth variable is assigned but not used. Removing it helps keep the code clean and maintainable.

-  const _auth = await getAuth();
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e6e4dd6 and 761b37e.

📒 Files selected for processing (9)
  • apps/dashboard/app/auth/layout.tsx (2 hunks)
  • apps/dashboard/app/new/create-ratelimit.tsx (3 hunks)
  • apps/dashboard/app/new/page.tsx (2 hunks)
  • apps/dashboard/lib/auth.ts (1 hunks)
  • apps/dashboard/lib/auth/base-provider.ts (1 hunks)
  • apps/dashboard/lib/auth/get-auth.ts (0 hunks)
  • apps/dashboard/lib/auth/utils.ts (1 hunks)
  • apps/dashboard/lib/trpc/context.ts (1 hunks)
  • apps/dashboard/middleware.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • apps/dashboard/lib/auth/get-auth.ts
🧰 Additional context used
🧬 Code Definitions (5)
apps/dashboard/app/auth/layout.tsx (1)
apps/dashboard/lib/auth.ts (1)
  • getCurrentUser (64-72)
apps/dashboard/lib/auth/utils.ts (2)
apps/dashboard/lib/auth.ts (1)
  • getAuth (24-31)
apps/dashboard/lib/auth/get-auth.ts (1)
  • getAuth (10-64)
apps/dashboard/app/new/create-ratelimit.tsx (1)
apps/dashboard/lib/auth.ts (1)
  • getCurrentUser (64-72)
apps/dashboard/app/new/page.tsx (2)
apps/dashboard/lib/auth.ts (1)
  • getAuth (24-31)
apps/dashboard/lib/auth/get-auth.ts (1)
  • getAuth (10-64)
apps/dashboard/lib/auth.ts (2)
apps/dashboard/lib/auth/get-auth.ts (1)
  • getAuth (10-64)
apps/dashboard/lib/auth/types.ts (1)
  • User (9-17)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: Test Agent Local / test_agent_local
  • GitHub Check: Test Packages / Test ./packages/hono
  • GitHub Check: Test Go API Local / Test (Shard 7/8)
  • GitHub Check: Test Packages / Test ./packages/nextjs
  • GitHub Check: Test Packages / Test ./internal/clickhouse
  • GitHub Check: Test Packages / Test ./internal/keys
  • GitHub Check: Test Packages / Test ./internal/billing
  • GitHub Check: Build / Build
  • GitHub Check: Test API / API Test Local
🔇 Additional comments (15)
apps/dashboard/middleware.ts (1)

28-28: Added authentication refresh endpoint to public paths

Adding /api/auth/refresh to the public paths aligns with the PR objective of improving session handling to prevent consecutive refresh token calls. This change allows the refresh endpoint to be accessed without triggering authentication checks, which helps avoid the circular issue of refreshing auth during an auth refresh operation.

apps/dashboard/lib/trpc/context.ts (1)

4-4: Updated import path for getAuth

The import path has been modified from an absolute path to a relative path. This change doesn't affect functionality but might improve code organization and module resolution.

apps/dashboard/app/auth/layout.tsx (2)

4-4: Replaced auth.getCurrentUser with cached getCurrentUser function

This change aligns with the PR objective of leveraging React Server Components caching for authentication. By using the cached getCurrentUser function, you're avoiding redundant auth calls that could trigger session refresh logic multiple times.


78-78: Updated user retrieval method

Replacing auth.getCurrentUser() with the new cached getCurrentUser() function. This implements the PR's goal of leveraging RSC caching to avoid consecutive authentication calls, especially when edge middleware is running.

apps/dashboard/app/new/create-ratelimit.tsx (3)

3-3: Migrated to cached getCurrentUser function

Using the imported cached getCurrentUser function instead of auth.getCurrentUser() aligns with the PR objective of leveraging React Server Components caching for authentication operations.


16-16: Simplified user authentication

Replaced auth.getCurrentUser() with the new cached getCurrentUser() function. This change benefits from RSC caching to avoid multiple authentication calls when components are rendered.


28-28: Simplified organization ID retrieval

Instead of making a separate call to getOrgId(), the code now uses user.orgId! which comes from the enhanced getCurrentUser() function. This reduces redundant async calls and potential session refreshes.

apps/dashboard/lib/auth/utils.ts (2)

4-7: Imports align with the updated flow
The addition of getAuth and UNKEY_SESSION_COOKIE imports is consistent with the revised authentication approach.


10-15: Verify usage of the new return type
requireAuth now returns { userId, orgId } instead of a user object. Confirm that any existing callers handle the updated return type without expecting the old user shape.

apps/dashboard/lib/auth/base-provider.ts (3)

137-137: Header addition looks good
Using the x-middleware-processed header is a useful way to mark middleware processing.


141-160: Clear and comprehensive docstring
The new documentation for createMiddleware clearly explains its purpose and usage.


170-182: Potential session validity gap
This middleware only checks for a cookie’s presence, not its validity or expiration. Ensure the server components downstream fully validate session tokens to prevent unauthorized requests.

apps/dashboard/lib/auth.ts (3)

24-31: Redirect behavior check
getAuth redirects if no user is found. Double-check that this doesn't inadvertently affect pages meant to be publicly accessible.


43-51: Straightforward org check
When no orgId is found, redirecting to /new is a concise flow. This seems fine, but ensure it aligns with future multi-org expansions if planned.


64-72: Ensures valid user
getCurrentUser confirms both userId and a corresponding user record. This aligns with the consolidated authentication model.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
apps/dashboard/app/new/page.tsx (1)

27-27: Consider renaming the unused variable.

The variable _auth is appropriately prefixed with an underscore to indicate it's not directly used, but the code could be even clearer by using await getAuth() directly without assignment, since you're only using it for its side-effect of redirecting unauthenticated users.

-  const _auth = await getAuth(); 
+  await getAuth();
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 761b37e and cc02631.

📒 Files selected for processing (9)
  • apps/dashboard/app/auth/layout.tsx (2 hunks)
  • apps/dashboard/app/new/create-ratelimit.tsx (3 hunks)
  • apps/dashboard/app/new/page.tsx (2 hunks)
  • apps/dashboard/lib/auth.ts (1 hunks)
  • apps/dashboard/lib/auth/base-provider.ts (1 hunks)
  • apps/dashboard/lib/auth/get-auth.ts (0 hunks)
  • apps/dashboard/lib/auth/utils.ts (1 hunks)
  • apps/dashboard/lib/trpc/context.ts (1 hunks)
  • apps/dashboard/middleware.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • apps/dashboard/lib/auth/get-auth.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • apps/dashboard/middleware.ts
  • apps/dashboard/lib/trpc/context.ts
  • apps/dashboard/app/auth/layout.tsx
  • apps/dashboard/app/new/create-ratelimit.tsx
  • apps/dashboard/lib/auth/utils.ts
🧰 Additional context used
🧬 Code Definitions (2)
apps/dashboard/app/new/page.tsx (2)
apps/dashboard/lib/auth.ts (1)
  • getAuth (32-39)
apps/dashboard/lib/auth/get-auth.ts (1)
  • getAuth (10-64)
apps/dashboard/lib/auth.ts (3)
apps/dashboard/lib/auth/get-auth.ts (1)
  • getAuth (10-64)
apps/dashboard/lib/auth/workos.ts (1)
  • getCurrentUser (128-155)
apps/dashboard/lib/auth/types.ts (1)
  • User (9-18)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Test Packages / Test ./internal/clickhouse
🔇 Additional comments (8)
apps/dashboard/app/new/page.tsx (1)

3-3: Good update to the auth import.

The switch from importing the auth namespace to importing the specific getAuth function directly improves code clarity and aligns with the PR objective of leveraging RSC caching for authentication functions.

apps/dashboard/lib/auth/base-provider.ts (3)

137-137: Good addition of the middleware tracking header.

Adding x-middleware-processed header helps with debugging and provides visibility into the request processing pipeline.


141-160: Excellent documentation for the middleware factory.

The added JSDoc comment clearly explains the purpose, behavior, and usage of the middleware function. The example is particularly helpful for implementers.


170-182: Well-optimized session verification approach.

The middleware has been appropriately simplified to only perform lightweight cookie presence checks at the edge, delegating full authentication to server components. This aligns perfectly with the PR objective to streamline middleware and relocate session handling to RSC authentication components.

This change should help prevent the refresh token invalidation issues mentioned in the PR description by reducing duplicate validation calls in the request pipeline.

apps/dashboard/lib/auth.ts (4)

1-10: Good organization of authentication utilities.

The separation of cached and non-cached versions of getAuth is well-structured. The type definition for GetAuthResult is clear and appropriately placed.


20-39: Well-implemented caching strategy for authentication.

The caching implementation for getAuth is excellent. Using React's cache function ensures that:

  1. Authentication checks are performed only once per server request
  2. Results are consistent across components rendered during the same request
  3. Performance is optimized by eliminating redundant API calls

This directly addresses the PR objective of "leveraging RSC caching for authentication functions" and will help prevent the refresh token invalidation issues described in the PR.


41-59: Clean implementation of organization ID retrieval.

The getOrgId function now leverages the cached getAuth function, maintaining a clean separation of concerns while ensuring consistent authentication state throughout the request lifecycle. The comprehensive JSDoc comments make the function's purpose and behavior clear.


61-80: Excellent addition of the getCurrentUser utility.

The new getCurrentUser function provides a complete user object while maintaining proper authentication checks. It correctly:

  1. Leverages the cached getAuth to ensure consistent authentication state
  2. Fetches the complete user object using the userId
  3. Includes proper error handling with redirection
  4. Returns a complete user object with organization context

This function will make it easier to access user data across the application while maintaining the performance benefits of caching.

Copy link
Contributor

All looks good now

Copy link
Member

I'll be the judge of that.... :bugeyes:

Copy link
Member

@perkinsjr perkinsjr left a comment

Choose a reason for hiding this comment

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

Alrighty it looks good both code sniff and testing everything.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants