Skip to content

Comments

[WEB-2729] chore: updated live server auth cookies handling#5913

Merged
pushya22 merged 4 commits intopreviewfrom
chore/live-server-updates
Oct 30, 2024
Merged

[WEB-2729] chore: updated live server auth cookies handling#5913
pushya22 merged 4 commits intopreviewfrom
chore/live-server-updates

Conversation

@1akhanBaheti
Copy link
Member

@1akhanBaheti 1akhanBaheti commented Oct 25, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced authentication process with improved error handling and credential management.
    • Introduced new types for better clarity and type safety, including HocusPocusServerContext and updates to TUserDetails.
  • Bug Fixes

    • Refined error handling for user authentication to ensure proper validation of credentials.
  • Documentation

    • Updated comments for better readability and understanding of the code structure.
  • Chores

    • Reorganized import statements for improved code clarity.

issue attached: WEB-2729

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 25, 2024

Walkthrough

The changes primarily involve updates to the getExtensions, getHocusPocusServer, and authentication logic across several files. Key modifications include the introduction of a context parameter in the Database methods, enhancements to error handling in the Redis client, and adjustments to how user authentication is managed. The TUserDetails type has been updated to include a cookie property, and new types have been defined to improve type safety. Overall, these changes enhance context handling, error management, and code readability.

Changes

File Path Change Summary
live/src/core/extensions/index.ts - Updated getExtensions function to use context parameter in fetch and store methods.
- Refined error handling in Redis client connection.
- Reorganized import statements for clarity.
live/src/core/hocuspocus-server.ts - Modified getHocusPocusServer function to include context in onAuthenticate.
- Restructured cookie extraction and error handling.
- Updated handleAuthentication to use userId.
live/src/core/lib/authentication.ts - Changed Props type to replace token with userId.
- Updated authentication logic to compare response.id with userId.
live/src/core/types/common.d.ts - Introduced new type HocusPocusServerContext with cookie property.
- Updated TDocumentTypes to include TAdditionalDocumentTypes.
packages/editor/src/core/hooks/use-collaborative-editor.ts - Modified HocuspocusProvider initialization to use JSON.stringify(user) for the token.
- Updated useMemo dependency array to remove redundancy.
packages/editor/src/core/types/editor.ts - Added optional cookie property to TUserDetails type.

Possibly related PRs

Suggested labels

🌐frontend, ✍️editor, 🌟improvement

Suggested reviewers

  • aaryan610
  • SatishGandham
  • pushya22

🐰 In the code we hop and play,
Context and cookies lead the way.
With user details now in sight,
Authentication feels just right!
Error handling, clear and bright,
Our changes make the code take flight! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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 resolve resolve all the CodeRabbit review comments.
  • @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.

@1akhanBaheti 1akhanBaheti marked this pull request as ready for review October 30, 2024 11:44
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: 5

🧹 Outside diff range and nitpick comments (5)
live/src/core/types/common.d.ts (1)

6-8: Consider adding JSDoc comments for better documentation.

The type definition looks good, but adding JSDoc comments would improve code documentation and provide better context for other developers.

+/**
+ * Context type for HocusPocus server containing authentication cookie.
+ * Used for maintaining authentication state in WebSocket connections.
+ */
 export type HocusPocusServerContext = {
+  /** Authentication cookie string used for maintaining user session */
   cookie: string;
 };
live/src/core/lib/authentication.ts (1)

Line range hint 14-31: Consider adding cookie validation.

The function accepts a cookie string but doesn't validate its format or presence. Consider adding basic validation to ensure the cookie is properly formatted before making the API call.

 export const handleAuthentication = async (props: Props) => {
   const { cookie, userId } = props;
+  if (!cookie || typeof cookie !== 'string' || cookie.trim() === '') {
+    throw new Error('Invalid or missing authentication cookie');
+  }
   // fetch current user info
   let response;
live/src/core/extensions/index.ts (2)

Line range hint 34-64: Refactor Promise constructor usage to avoid anti-pattern.

The current implementation has two issues:

  1. Using an async function in Promise constructor is an anti-pattern as it makes error handling unreliable.
  2. The TODO comment about the ESLint error should be addressed rather than disabled.

Consider refactoring to:

-        // TODO: Fix this lint error.
-        // eslint-disable-next-line no-async-promise-executor
-        return new Promise(async (resolve) => {
-          try {
-            let fetchedData = null;
-            if (documentType === "project_page") {
-              fetchedData = await fetchPageDescriptionBinary(
-                params,
-                pageId,
-                cookie,
-              );
-            } else {
-              fetchedData = await fetchDocument({
-                cookie,
-                documentType,
-                pageId,
-                params,
-              });
-            }
-            resolve(fetchedData);
-          } catch (error) {
-            manualLogger.error("Error in fetching document", error);
-          }
-        });
+        try {
+          if (documentType === "project_page") {
+            return await fetchPageDescriptionBinary(
+              params,
+              pageId,
+              cookie,
+            );
+          }
+          return await fetchDocument({
+            cookie,
+            documentType,
+            pageId,
+            params,
+          });
+        } catch (error) {
+          manualLogger.error("Error in fetching document", error);
+          return null;
+        }

Line range hint 66-97: Fix Promise handling in store method.

The current implementation has several issues:

  1. Using an async function in Promise constructor (same anti-pattern as fetch).
  2. The Promise never resolves or rejects, which could cause memory leaks.
  3. Error handling doesn't propagate errors properly.

Consider refactoring to:

-        // TODO: Fix this lint error.
-        // eslint-disable-next-line no-async-promise-executor
-        return new Promise(async () => {
-          try {
-            if (documentType === "project_page") {
-              await updatePageDescription(params, pageId, state, cookie);
-            } else {
-              await updateDocument({
-                cookie,
-                documentType,
-                pageId,
-                params,
-                updatedDescription: state,
-              });
-            }
-          } catch (error) {
-            manualLogger.error("Error in updating document:", error);
-          }
-        });
+        try {
+          if (documentType === "project_page") {
+            await updatePageDescription(params, pageId, state, cookie);
+          } else {
+            await updateDocument({
+              cookie,
+              documentType,
+              pageId,
+              params,
+              updatedDescription: state,
+            });
+          }
+          return true;
+        } catch (error) {
+          manualLogger.error("Error in updating document:", error);
+          throw error; // Propagate error to Hocuspocus
+        }
live/src/core/hocuspocus-server.ts (1)

Line range hint 50-57: Handle errors more specifically in handleAuthentication

The catch block throws a generic error message "Authentication unsuccessful!". Providing more specific error messages can aid in debugging and improve user feedback. Consider handling different error types to give more informative messages.

Apply this diff to handle errors more specifically:

} catch (error) {
-   throw Error("Authentication unsuccessful!");
+   if (error instanceof SomeSpecificError) {
+     throw new Error("Specific error message related to the issue.");
+   } else {
+     throw new Error("Authentication unsuccessful: " + error.message);
+   }
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 6d08cf2 and 29cea39.

📒 Files selected for processing (6)
  • live/src/core/extensions/index.ts (6 hunks)
  • live/src/core/hocuspocus-server.ts (2 hunks)
  • live/src/core/lib/authentication.ts (2 hunks)
  • live/src/core/types/common.d.ts (1 hunks)
  • packages/editor/src/core/hooks/use-collaborative-editor.ts (1 hunks)
  • packages/editor/src/core/types/editor.ts (1 hunks)
🔇 Additional comments (8)
live/src/core/types/common.d.ts (1)

Line range hint 1-4: LGTM!

The union type combining project_page with TAdditionalDocumentTypes is well-structured and provides good type safety.

live/src/core/lib/authentication.ts (2)

14-14: LGTM: Parameter destructuring updated correctly.

The destructuring syntax correctly matches the Props type definition.


10-10: Verify the security implications of using userId instead of token.

The change from token to userId might have security implications. While the cookie provides authentication, using a potentially predictable userId instead of an unpredictable token could make the system more vulnerable to brute force attacks.

packages/editor/src/core/types/editor.ts (1)

141-141: Consider security implications of cookie handling.

The addition of the optional cookie property to TUserDetails is well-structured and maintains backward compatibility. However, since cookies often contain sensitive authentication data:

  1. Ensure the cookie is only used for authentication purposes and not exposed unnecessarily
  2. Consider documenting the expected cookie format/content in a comment
  3. Verify that the cookie is properly sanitized before use

Let's verify the cookie usage across the codebase:

✅ Verification successful

Cookie handling is properly secured in the implementation

Based on the verification results, the cookie implementation is secure and well-handled:

  1. The cookie is only used in authentication context within handleAuthentication function
  2. Cookie is properly passed through secure channels:
    • Used in authenticated API requests with proper headers
    • Stored in WebSocket context for maintaining connection state
  3. No instances of cookie exposure through logging were found
  4. Cookie is handled server-side in hocuspocus-server.ts with proper fallback mechanisms

The implementation aligns with security best practices by:

  • Keeping cookie handling on the server side
  • Using cookies only for authentication purposes
  • Not exposing cookies in client-side code or logs
  • Properly validating cookie presence before authentication
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential security issues in cookie handling
# Expected: Cookie should only be used in authentication context

# Test 1: Look for cookie usage in authentication-related code
echo "Checking cookie usage in authentication flows..."
rg -l 'cookie.*authenticate|authenticate.*cookie'

# Test 2: Check for potential cookie exposure in logging or client-side code
echo "Checking for potential cookie exposure..."
rg -l 'console\.log.*cookie|cookie.*console\.log'

Length of output: 303


Script:

#!/bin/bash
# Let's try a broader search to understand cookie usage

# Search for cookie-related code
echo "Searching for cookie usage patterns..."
rg -A 3 -B 3 'cookie' --type ts

# Search for files importing or using TUserDetails
echo "Searching for TUserDetails usage..."
rg -A 3 -B 3 'TUserDetails'

# Look for WebSocket or authentication-related code that might use the cookie
echo "Searching for WebSocket and authentication patterns..."
rg -A 3 'WebSocket|authenticate|authorization' --type ts

Length of output: 20479

live/src/core/extensions/index.ts (2)

20-23: LGTM! Well-organized imports with clear type definitions.

The addition of HocusPocusServerContext and TDocumentTypes types enhances type safety for the cookie handling changes.


119-119: LGTM! Consistent error logging format.

The added commas improve consistency in the logging statements.

Also applies to: 133-133, 138-138

live/src/core/hocuspocus-server.ts (2)

47-47: Verify that context is properly initialized before assignment

When assigning cookie to context, ensure that context is properly initialized and not undefined. If context is undefined, attempting to assign a property to it may result in a runtime error.


52-54: Ensure handleAuthentication receives the correct parameters

Verify that the handleAuthentication function expects an object with cookie and userId. Passing unexpected parameters may lead to unexpected behavior or runtime errors.

Comment on lines +23 to 24
if (response.id !== userId) {
throw Error("Authentication failed: Token doesn't match the current user.");
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Update error message to reflect userId instead of token.

The error message still mentions "Token" despite the parameter being changed to userId. This could be confusing for debugging.

-    throw Error("Authentication failed: Token doesn't match the current user.");
+    throw Error("Authentication failed: User ID doesn't match the current user.");
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (response.id !== userId) {
throw Error("Authentication failed: Token doesn't match the current user.");
if (response.id !== userId) {
throw Error("Authentication failed: User ID doesn't match the current user.");

parameters: realtimeConfig.queryParams,
// using user id as a token to verify the user on the server
token: user.id,
token: JSON.stringify(user),
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Update useMemo dependencies to match usage.

The dependency array includes user.id, but the hook now depends on the entire user object due to JSON.stringify(user). This could lead to missed updates if other user properties change.

-[id, realtimeConfig, serverHandler, user.id]
+[id, realtimeConfig, serverHandler, user]

Also applies to: 64-64


⚠️ Potential issue

Reconsider sending the entire user object as token.

Sending the complete user object as a token raises several concerns:

  1. Security: Exposing more user data than necessary could lead to potential information leakage
  2. Performance: Increased payload size due to serializing the entire user object
  3. Type safety: No validation on the stringified user structure

Consider creating a minimal token object with only the required fields (e.g., id and cookie).

-token: JSON.stringify(user),
+token: JSON.stringify({ id: user.id, cookie: user.cookie }),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
token: JSON.stringify(user),
token: JSON.stringify({ id: user.id, cookie: user.cookie }),

Comment on lines +28 to +39
try {
const parsedToken = JSON.parse(token) as TUserDetails;
userId = parsedToken.id;
cookie = parsedToken.cookie;
} catch (error) {
// If token parsing fails, fallback to request headers
console.error("Token parsing failed, using request headers:", error);
} finally {
// If cookie is still not found, fallback to request headers
if (!cookie) {
cookie = requestHeaders.cookie?.toString();
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure userId is obtained when token parsing fails

When the parsing of token fails, userId remains undefined because it is only assigned within the try block. As a result, even if cookie is obtained from requestHeaders, the authentication will fail due to the missing userId.

Consider adding a fallback mechanism to obtain userId when token parsing fails. This ensures that authentication can proceed if userId can be retrieved from another source.

cookie = parsedToken.cookie;
} catch (error) {
// If token parsing fails, fallback to request headers
console.error("Token parsing failed, using request headers:", error);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid logging raw errors to prevent sensitive data exposure

Logging the raw error object may expose sensitive information if the error contains details about user input. To prevent potential leakage of sensitive data, consider logging only the error message or a generic message.

Apply this diff to modify the logging statement:

- console.error("Token parsing failed, using request headers:", error);
+ console.error("Token parsing failed, using request headers. Error:", error.message);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
console.error("Token parsing failed, using request headers:", error);
console.error("Token parsing failed, using request headers. Error:", error.message);

@1akhanBaheti 1akhanBaheti changed the title chore: updated live server auth cookies handling [WEB-2729] chore: updated live server auth cookies handling Oct 30, 2024
@pushya22 pushya22 merged commit 8ea34b5 into preview Oct 30, 2024
@pushya22 pushya22 deleted the chore/live-server-updates branch October 30, 2024 12:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants