Skip to content

fix (gql-middleware): Introducing synchronous graphql reconnection endpoint to resolve race condition issues - #21816

Merged
TiagoJacobs merged 1 commit into
bigbluebutton:v3.0.x-releasefrom
gustavotrott:gql-fix-race-condition-userJoin
Dec 4, 2024
Merged

TiagoJacobs merged 1 commit into
bigbluebutton:v3.0.x-releasefrom
gustavotrott:gql-fix-race-condition-userJoin

Conversation

@gustavotrott

Copy link
Copy Markdown
Contributor

Currently, when a user joins, changes roles, becomes a presenter, or leaves, Akka-Apps:

  1. Updates the database.
  2. Sends a Redis message to graphql-middleware to invalidate and restart the GraphQL connection with Hasura.

This ensures the connection reflects the new session variables (e.g., role changes). However, the current approach is asynchronous and does not guarantee that the GraphQL connection will restart before the client receives the new status and begins sending queries with expectations of the updated role.

In cases where the server is slow, this creates a race condition where the client queries using outdated session variables.

Solution

This PR introduces a new synchronous HTTP endpoint in graphql-middleware to manage GraphQL reconnections. The new flow ensures Akka-Apps can:

  1. Request graphql-middleware to restart the GraphQL connection via the HTTP endpoint.
  2. Wait for confirmation of the connection restart.
  3. Update the database and notify the client of the new status/role.

The synchronous nature of HTTP requests resolves the race condition issue because it guarantees the GraphQL connection is updated before the client acts on the new status.

Implementation

  • New Endpoint:
    URL: http://127.0.0.1:8378/graphql-reconnection
    Parameters:
    • sessionToken: Identifies the session to reconnect.
    • reason: Explains why the reconnection is required (e.g., user_joined).

Example Request

GET http://127.0.0.1:8378/graphql-reconnection?sessionToken=123&reason=user_joined

This change mainly addresses the /join flow and resolves the race condition issue highlighted during stress tests conducted by @schrd and @TiagoJacobs.

@gustavotrott gustavotrott added this to the Release 3.0 milestone Dec 4, 2024
@coderabbitai

coderabbitai Bot commented Dec 4, 2024 •

Copy link
Copy Markdown
Contributor

Walkthrough

The changes in this pull request introduce significant modifications to the handling of GraphQL reconnections across various components of the application. A new GraphqlMiddleware object is created, which includes a method for requesting reconnections. This method is integrated into multiple existing handlers, replacing previous implementations that relied on a Sender object. Specifically, methods for ejecting users, changing user roles, and managing user sessions now utilize GraphqlMiddleware.requestGraphqlReconnection, streamlining the process of notifying users about reconnections after events such as permission violations or user inactivity.

Additionally, a new configuration entry for graphqlMiddlewareAPI is added to the application configuration, specifying a default URL for the GraphQL middleware. The introduction of a new HTTP handler for the /graphql-reconnection endpoint in the bbb-graphql-middleware further enhances the middleware's capabilities, allowing it to process reconnection requests effectively. Overall, these changes improve the structure and maintainability of the code while ensuring that user session management is handled more efficiently.

Suggested reviewers

  • TiagoJacobs

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.

@gustavotrott gustavotrott changed the title fix (gql-middleware): Introducing Synchronous GraphQL Reconnection Endpoint to Resolve Race Condition Issues fix (gql-middleware): Introducing synchronous graphql reconnection endpoint to resolve race condition issues Dec 4, 2024
@sonarqubecloud

sonarqubecloud Bot commented Dec 4, 2024

Copy link
Copy Markdown

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

🧹 Outside diff range and nitpick comments (6)
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/UsersApp.scala (1)

78-84: Consider adding error handling for GraphQL reconnection

The current implementation doesn't handle potential failures in the GraphQL reconnection request. Consider wrapping the call in a try-catch block to handle network issues or server errors gracefully.

Here's a suggested improvement:

 if(regUser.joined) {
-  GraphqlMiddleware.requestGraphqlReconnection(regUser.sessionToken, "assigned_presenter_automatically")
+  try {
+    GraphqlMiddleware.requestGraphqlReconnection(regUser.sessionToken, "assigned_presenter_automatically")
+  } catch {
+    case e: Exception =>
+      log.error(s"Failed to reconnect GraphQL for user ${regUser.id}: ${e.getMessage}")
+      // Consider if additional error handling is needed
+  }
 }
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/breakout/EjectUserFromBreakoutInternalMsgHdlr.scala (2)

Line range hint 31-31: Implement the TODO about informing reason

There's an unimplemented TODO comment about informing the reason for ejection.

Would you like me to help implement the reason notification system? I can propose a solution that integrates with your existing messaging system.


Based on the code analysis, I can now provide the final response:

Race condition concern is valid, but implementation needs improvement

The current implementation of GraphqlMiddleware.requestGraphqlReconnection lacks error handling and doesn't provide any feedback about the success or failure of the operation. This makes the suggested order-of-operations change essential, as the current implementation could leave the system in an inconsistent state if the GraphQL reconnection fails after the soft delete.

  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/graphql/GraphqlMiddleware.scala: Add error handling and make the method return a Try/Either type instead of Unit
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/breakout/EjectUserFromBreakoutInternalMsgHdlr.scala: Implement the suggested order change with proper error handling
🔗 Analysis chain

Line range hint 31-40: Review order of operations for race condition prevention

The current order of operations (soft delete before GraphQL reconnection) might still allow a race condition if the user makes requests between these operations.

Let's verify the impact:

Consider this order instead:

-      UserDAO.softDelete(registeredUser.meetingId, registeredUser.id)
-
-      // Force reconnection with graphql to refresh permissions
-      GraphqlMiddleware.requestGraphqlReconnection(registeredUser.sessionToken, msg.reasonCode)
+      // Force reconnection with graphql to refresh permissions first
+      try {
+        GraphqlMiddleware.requestGraphqlReconnection(Vector(registeredUser.sessionToken), msg.reasonCode)
+        // Only proceed with soft delete after successful reconnection
+        UserDAO.softDelete(registeredUser.meetingId, registeredUser.id)
+      } catch {
+        case e: Exception =>
+          log.error(s"Failed to complete user ejection process for ${registeredUser.id}", e)
+          // Consider if we need to take any recovery actions
+      }

Let me gather more information about the GraphQL reconnection implementation to better understand the race condition potential.


Let me check the implementation of GraphqlMiddleware to understand its error handling.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other places where UserDAO.softDelete is called
rg "UserDAO.softDelete" -A 5 -B 5

Length of output: 6555


Script:

#!/bin/bash
# Search for GraphqlMiddleware.requestGraphqlReconnection implementation and usage
rg "requestGraphqlReconnection" -A 5 -B 5

# Also search for any error handling related to GraphQL reconnection
ast-grep --pattern 'try {
  $$$
  GraphqlMiddleware.requestGraphqlReconnection($$$)
  $$$
}'

Length of output: 24922


Script:

#!/bin/bash
# Search for GraphqlMiddleware implementation
rg -A 10 "object GraphqlMiddleware" 

# Also search for any HTTP client error handling
ast-grep --pattern 'try {
  $$$
  HttpClient.$$$
  $$$
} catch {
  $$$
}'

Length of output: 1487

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/UserLeaveReqMsgHdlr.scala (1)

Line range hint 19-29: Add error handling for GraphQL connection status update

The handleUserClosedAllGraphqlConnectionsInternalMsg method updates the GraphQL connection status without verifying if the update was successful.

Consider adding error handling:

 for {
   regUser <- RegisteredUsers.findWithUserId(msg.userId, liveMeeting.registeredUsers)
 } yield {
-  RegisteredUsers.updateUserConnectedToGraphql(liveMeeting.registeredUsers, regUser, graphqlConnected = false)
+  val updateSuccess = RegisteredUsers.updateUserConnectedToGraphql(liveMeeting.registeredUsers, regUser, graphqlConnected = false)
+  if (!updateSuccess) {
+    log.error(s"Failed to update GraphQL connection status for user ${msg.userId}")
+    // Consider appropriate error handling strategy
+  }
 }
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/ChangeLockSettingsInMeetingCmdMsgHdlr.scala (1)

261-261: LGTM! Consider adding error handling for the GraphQL reconnection request.

The change correctly uses the new synchronous GraphQL reconnection endpoint for locked viewers when lock settings change.

Consider adding error handling to gracefully handle failed reconnection requests:

-          GraphqlMiddleware.requestGraphqlReconnection(regUser.sessionToken, "lockSettings_changed")
+          try {
+            GraphqlMiddleware.requestGraphqlReconnection(regUser.sessionToken, "lockSettings_changed")
+          } catch {
+            case e: Exception =>
+              log.error(s"Failed to request GraphQL reconnection for user ${regUser.id}: ${e.getMessage}")
+          }
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/running/MeetingActor.scala (1)

1180-1180: LGTM! Consider adding logging for the GraphQL reconnection request.

The change correctly uses the new synchronous GraphQL reconnection endpoint when handling user inactivity.

Consider adding logging to track the GraphQL reconnection request:

-          GraphqlMiddleware.requestGraphqlReconnection(regUser.sessionToken, EjectReasonCode.USER_INACTIVITY)
+          log.info(s"Requesting GraphQL reconnection for inactive user ${regUser.id}")
+          try {
+            GraphqlMiddleware.requestGraphqlReconnection(regUser.sessionToken, EjectReasonCode.USER_INACTIVITY)
+            log.debug(s"Successfully requested GraphQL reconnection for user ${regUser.id}")
+          } catch {
+            case e: Exception =>
+              log.error(s"Failed to request GraphQL reconnection for user ${regUser.id}: ${e.getMessage}")
+          }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 97c31cd and 23bbe7d.

📒 Files selected for processing (28)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/SystemConfiguration.scala (1 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/ExternalVideoModel.scala (1 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/PermissionCheck.scala (2 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/ScreenshareModel.scala (0 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/breakout/EjectUserFromBreakoutInternalMsgHdlr.scala (2 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/breakout/UpdateBreakoutRoomsTimeMsgHdlr.scala (1 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/screenshare/ScreenshareRtmpBroadcastStoppedVoiceConfEvtMsgHdlr.scala (0 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/AssignPresenterReqMsgHdlr.scala (3 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/ChangeLockSettingsInMeetingCmdMsgHdlr.scala (2 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/ChangeUserAwayReqMsgHdlr.scala (0 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/ChangeUserRaiseHandReqMsgHdlr.scala (0 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/ChangeUserRoleCmdMsgHdlr.scala (2 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/EjectUserFromMeetingCmdMsgHdlr.scala (4 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/GenerateLiveKitTokenRespMsgHdlr.scala (0 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/LockUserInMeetingCmdMsgHdlr.scala (2 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/MuteUserCmdMsgHdlr.scala (0 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/RegisterUserReqMsgHdlr.scala (2 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/UserJoinMeetingReqMsgHdlr.scala (2 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/UserLeaveReqMsgHdlr.scala (2 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/UsersApp.scala (2 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/webcam/UpdateWebcamsOnlyForModeratorCmdMsgHdlr.scala (2 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/graphql/GraphqlMiddleware.scala (1 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/running/MeetingActor.scala (2 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core2/message/handlers/guests/GetGuestsWaitingApprovalReqMsgHdlr.scala (1 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core2/testdata/FakeUserGenerator.scala (1 hunks)
  • akka-bbb-apps/src/universal/conf/application.conf (1 hunks)
  • bbb-graphql-middleware/cmd/bbb-graphql-middleware/main.go (2 hunks)
  • bbb-graphql-middleware/internal/websrv/reconnectionHandler.go (1 hunks)
💤 Files with no reviewable changes (6)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/GenerateLiveKitTokenRespMsgHdlr.scala
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/MuteUserCmdMsgHdlr.scala
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/screenshare/ScreenshareRtmpBroadcastStoppedVoiceConfEvtMsgHdlr.scala
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/ScreenshareModel.scala
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/ChangeUserRaiseHandReqMsgHdlr.scala
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/ChangeUserAwayReqMsgHdlr.scala
✅ Files skipped from review due to trivial changes (3)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core2/testdata/FakeUserGenerator.scala
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core2/message/handlers/guests/GetGuestsWaitingApprovalReqMsgHdlr.scala
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/ExternalVideoModel.scala
👮 Files not reviewed due to content moderation or server errors (6)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/ChangeUserRoleCmdMsgHdlr.scala
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/EjectUserFromMeetingCmdMsgHdlr.scala
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/breakout/UpdateBreakoutRoomsTimeMsgHdlr.scala
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/AssignPresenterReqMsgHdlr.scala
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/RegisterUserReqMsgHdlr.scala
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/UserJoinMeetingReqMsgHdlr.scala
🔇 Additional comments (5)
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/users/UsersApp.scala (1)

17-17: LGTM: Import statement for GraphQL middleware

The addition of the GraphqlMiddleware import aligns with the PR's objective to implement synchronous GraphQL reconnection.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/webcam/UpdateWebcamsOnlyForModeratorCmdMsgHdlr.scala (1)

91-91: Implementation aligns with race condition fix strategy

The change from Sender to GraphqlMiddleware.requestGraphqlReconnection is consistent with the PR's objective to prevent race conditions through synchronous reconnection requests.

Let's verify the GraphQL middleware endpoint configuration:

✅ Verification successful

GraphQL middleware implementation is properly configured and consistently used

The change is part of a well-integrated GraphQL middleware system that:

  • Has proper configuration in application.conf with endpoint at http://127.0.0.1:8378
  • Is consistently used across multiple user management scenarios (role changes, ejections, lock settings, etc.)
  • Follows the same pattern for synchronous reconnection requests with specific reason codes
  • The implementation in UpdateWebcamsOnlyForModeratorCmdMsgHdlr.scala aligns with this established pattern
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify GraphQL middleware endpoint configuration
# Expected: Configuration should match the endpoint mentioned in PR objectives

rg -l "graphqlMiddlewareAPI.*8378" --type-add 'conf:*.conf' --type conf

Length of output: 123


Script:

#!/bin/bash
# Let's examine the actual configuration content to verify the GraphQL middleware setup
cat akka-bbb-apps/src/universal/conf/application.conf | grep -A 5 "graphqlMiddlewareAPI"

# Also check for any GraphqlMiddleware implementation to verify the method usage
rg -A 3 "object GraphqlMiddleware" 

Length of output: 812


Script:

#!/bin/bash
# Let's check the implementation details of requestGraphqlReconnection method
ast-grep --pattern 'def requestGraphqlReconnection($$$) {
  $$$
}'

# Also check for any other usages of this method in the codebase
rg "GraphqlMiddleware.requestGraphqlReconnection" -A 2

Length of output: 6682

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/PermissionCheck.scala (1)

95-95: Verify permission refresh synchronization

The implementation ensures that permission changes are synchronized with GraphQL reconnections, preventing potential security issues where a user might retain outdated permissions.

Let's verify the permission refresh implementation:

✅ Verification successful

Permission refresh synchronization is properly implemented

The verification confirms that the GraphQL reconnection mechanism is consistently used across the codebase to refresh permissions. The implementation in PermissionCheck.scala is part of a well-coordinated system where:

  • All permission-related changes trigger a GraphQL reconnection
  • The synchronization is handled uniformly through the GraphqlMiddleware
  • The implementation is used consistently across various permission-changing scenarios:
    • Role changes
    • Lock settings updates
    • User ejections
    • Presenter assignments
    • Permission violations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent permission refresh handling
# Expected: All permission-related reconnections should use GraphqlMiddleware

rg "requestGraphqlReconnection.*permission" -B 2 -A 2

Length of output: 55


Script:

#!/bin/bash
# Let's first check all usages of requestGraphqlReconnection to understand the context
rg "requestGraphqlReconnection" -B 3 -A 3

# Also search for permission-related reconnection patterns
rg "reconnection.*permission|permission.*reconnection" -B 3 -A 3

# Check the GraphqlMiddleware implementation
fd "GraphqlMiddleware" --exec cat {}

Length of output: 28941

akka-bbb-apps/src/universal/conf/application.conf (1)

69-69: Review security implications of GraphQL middleware endpoint

While the localhost binding is appropriate for internal service communication, consider the following security aspects:

  1. Ensure the port 8378 is not exposed externally
  2. Consider adding authentication for internal service communication

Let's verify the endpoint security configuration:

✅ Verification successful

GraphQL middleware endpoint configuration appears secure for internal communication

The verification reveals that:

  1. The GraphQL middleware is part of an internal communication system between akka-apps and bbb-graphql-middleware, with built-in health checks and connection management.
  2. The endpoint is correctly configured for localhost (127.0.0.1) communication, ensuring it's not externally accessible.
  3. Authentication is handled through session tokens and middleware UIDs, as evidenced by the connection management code.

The current configuration aligns with secure internal service communication practices:

  • Internal-only binding on localhost
  • Session-based authentication system
  • Proper connection tracking and management
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential security configurations
# Expected: The endpoint should only be accessible internally

# Check for any external bindings or security configurations
rg -l "127.0.0.1:8378" --type-add 'conf:*.conf' --type conf
rg "graphqlMiddleware.*security" --type scala

Length of output: 157


Script:

#!/bin/bash
# Let's check for any authentication or security-related configurations in the application.conf
# and related configuration files
rg -A 5 -B 5 "graphql" --type-add 'conf:*.conf' --type conf

# Check for any security-related code or middleware in Scala files
rg -A 5 "graphql.*middleware" --type scala

# Look for any network binding configurations that might restrict access
rg "bind.*address|listen.*address" --type-add 'conf:*.conf' --type conf

# Check for any authentication configurations
rg "auth.*token|security.*token|authentication" --type-add 'conf:*.conf' --type conf

Length of output: 9560

akka-bbb-apps/src/main/scala/org/bigbluebutton/SystemConfiguration.scala (1)

21-22: LGTM! Configuration for the new GraphQL middleware endpoint.

The configuration addition aligns with the PR objectives for introducing a synchronous GraphQL reconnection endpoint.

Let's verify if this configuration is properly set in the deployment configuration:

✅ Verification successful

Configuration for GraphQL middleware endpoint is properly set

The configuration is correctly defined in the deployment configuration file (akka-bbb-apps/src/universal/conf/application.conf) under the services section with the same default value:

services {
  graphqlMiddlewareAPI = "http://127.0.0.1:8378"
}
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the GraphQL middleware API configuration exists in deployment configs
# Look for the configuration in common deployment config files

rg -l "graphqlMiddlewareAPI" 

Length of output: 235


Script:

#!/bin/bash
# Let's check the content of application.conf to see how the configuration is defined
cat akka-bbb-apps/src/universal/conf/application.conf

Length of output: 4311

Comment on lines +78 to +84
// Force reconnection with graphql to refresh permissions (if user already joined)
for {
regUser <- RegisteredUsers.findWithUserId(newPresenter.intId, liveMeeting.registeredUsers)
} yield {
Sender.sendForceUserGraphqlReconnectionSysMsg(liveMeeting.props.meetingProp.intId, regUser.id, regUser.sessionToken, "role_changed", outGW)
if(regUser.joined) {
GraphqlMiddleware.requestGraphqlReconnection(regUser.sessionToken, "assigned_presenter_automatically")
}

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.

💡 Codebase verification

GraphQL reconnection implementation needs error handling improvements

The implementation in GraphqlMiddleware is synchronous and could potentially impact performance. The client.send() call blocks until the HTTP request completes, and while errors are logged, they're not propagated to the caller. Specific concerns:

  • Synchronous HTTP requests could block the actor processing thread
  • No timeout configuration for the HTTP client
  • Basic error handling that only prints to console
  • No retry mechanism for failed requests

Suggested improvements:

  • Convert to asynchronous HTTP client usage
  • Add proper error handling with logging
  • Configure request timeouts
  • Consider implementing retries for failed requests
🔗 Analysis chain

LGTM: GraphQL reconnection implementation for presenter assignment

The implementation correctly checks if the user has joined before requesting GraphQL reconnection, which aligns with the PR's goal of preventing race conditions. The reason "assigned_presenter_automatically" clearly indicates the context of the reconnection.

Let's verify the synchronous nature of the GraphqlMiddleware implementation:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for the implementation of requestGraphqlReconnection to verify it's synchronous
ast-grep --pattern 'def requestGraphqlReconnection($_, $_) {
  $$$
}'

Length of output: 71


Script:

#!/bin/bash
# Let's try to find the GraphqlMiddleware implementation with a broader search
rg -l "GraphqlMiddleware" 

# Then search for requestGraphqlReconnection method with context
rg "requestGraphqlReconnection" -A 5

Length of output: 15093


Script:

#!/bin/bash
# Let's examine the implementation of requestGraphqlReconnection in GraphqlMiddleware
cat akka-bbb-apps/src/main/scala/org/bigbluebutton/core/graphql/GraphqlMiddleware.scala

Length of output: 990

Comment on lines +8 to +25
func ReconnectionHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Only GET method is allowed", http.StatusMethodNotAllowed)
return
}

sessionToken := r.URL.Query().Get("sessionToken")
if sessionToken == "" {
http.Error(w, "Missing 'sessionToken' parameter", http.StatusBadRequest)
return
}

reason := r.URL.Query().Get("reason")

log.Debugf("Reconnection request received for sessionToken: %s, reason: %s", sessionToken, reason)

go InvalidateSessionTokenHasuraConnections(sessionToken)
}

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.

⚠️ Potential issue

Handler needs improvements for synchronous operation and proper response handling

The current implementation has several issues that could affect its reliability as a synchronous endpoint:

  1. The handler launches InvalidateSessionTokenHasuraConnections asynchronously with go but returns immediately, which doesn't fulfill the synchronous requirement mentioned in the PR objectives.
  2. No success response is sent back to the client.
  3. No timeout handling for the goroutine.
  4. No validation of sessionToken format.
  5. No rate limiting to prevent abuse.

Consider this implementation instead:

 func ReconnectionHandler(w http.ResponseWriter, r *http.Request) {
     if r.Method != http.MethodGet {
         http.Error(w, "Only GET method is allowed", http.StatusMethodNotAllowed)
         return
     }
 
     sessionToken := r.URL.Query().Get("sessionToken")
     if sessionToken == "" {
         http.Error(w, "Missing 'sessionToken' parameter", http.StatusBadRequest)
         return
     }
 
+    // Validate sessionToken format
+    if !isValidSessionToken(sessionToken) {
+        http.Error(w, "Invalid session token format", http.StatusBadRequest)
+        return
+    }
+
     reason := r.URL.Query().Get("reason")
 
     log.Debugf("Reconnection request received for sessionToken: %s, reason: %s", sessionToken, reason)
 
-    go InvalidateSessionTokenHasuraConnections(sessionToken)
+    // Use context with timeout for synchronous operation
+    ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
+    defer cancel()
+
+    done := make(chan error)
+    go func() {
+        done <- InvalidateSessionTokenHasuraConnections(ctx, sessionToken)
+    }()
+
+    // Wait for completion or timeout
+    select {
+    case err := <-done:
+        if err != nil {
+            log.Errorf("Failed to invalidate session: %v", err)
+            http.Error(w, "Internal server error", http.StatusInternalServerError)
+            return
+        }
+        w.WriteHeader(http.StatusOK)
+    case <-ctx.Done():
+        log.Errorf("Timeout while invalidating session: %v", ctx.Err())
+        http.Error(w, "Request timeout", http.StatusGatewayTimeout)
+    }
 }

Consider adding rate limiting to prevent abuse:

var limiter = rate.NewLimiter(rate.Every(time.Second), 10) // 10 requests per second

func ReconnectionHandler(w http.ResponseWriter, r *http.Request) {
    if !limiter.Allow() {
        http.Error(w, "Too many requests", http.StatusTooManyRequests)
        return
    }
    // ... rest of the handler
}

Comment on lines +8 to +25
def requestGraphqlReconnection(sessionTokens: Vector[String], reason: String): Unit = {
for {
sessionToken <- sessionTokens
} yield {
val url = s"${graphqlMiddlewareAPI}/graphql-reconnection?sessionToken=$sessionToken&reason=${reason}"

val client = HttpClient.newHttpClient()
val request = HttpRequest.newBuilder()
.uri(URI.create(url))
.GET()
.build()

val response = client.send(request, HttpResponse.BodyHandlers.ofString())
if (response.statusCode() != 200) {
println(s"Error on requesting graphql reconnection for ${sessionToken}. Response Code: ${response.statusCode()}")
}
}
}

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.

⚠️ Potential issue

Improve error handling, logging, and performance in GraphQL middleware

Several improvements are needed for robustness and reliability:

  1. Error handling for URI creation is missing
  2. HTTP client needs timeout configuration
  3. Using println for error logging is not production-grade
  4. No retry mechanism for failed requests
  5. Blocking HTTP calls in a for-yield loop could impact performance

Consider this implementation instead:

 object GraphqlMiddleware extends SystemConfiguration {
+  private val logger = LoggerFactory.getLogger(this.getClass)
+  private val client = HttpClient.newBuilder()
+    .connectTimeout(Duration.ofSeconds(5))
+    .build()
+
   def requestGraphqlReconnection(sessionTokens: Vector[String], reason: String): Unit = {
-    for {
-      sessionToken <- sessionTokens
-    } yield {
+    // Process requests in parallel
+    Future.sequence(sessionTokens.map { sessionToken =>
+      Future {
+        try {
+          val encodedReason = URLEncoder.encode(reason, StandardCharsets.UTF_8.toString)
+          val url = s"${graphqlMiddlewareAPI}/graphql-reconnection?sessionToken=$sessionToken&reason=$encodedReason"
+
+          val request = HttpRequest.newBuilder()
+            .uri(new URI(url))
+            .timeout(Duration.ofSeconds(5))
+            .GET()
+            .build()
+
+          // Implement retry with exponential backoff
+          retry(3, 1.seconds) {
+            val response = client.send(request, HttpResponse.BodyHandlers.ofString())
+            if (response.statusCode() != 200) {
+              logger.error(s"Error requesting graphql reconnection for $sessionToken. Response Code: ${response.statusCode()}")
+              throw new RuntimeException(s"Failed with status ${response.statusCode()}")
+            }
+            response
+          }
+        } catch {
+          case e: Exception =>
+            logger.error(s"Failed to process reconnection for $sessionToken", e)
+            throw e
+        }
+      }
+    })(ExecutionContext.global)
   }
+
+  private def retry[T](maxAttempts: Int, delay: FiniteDuration)(f: => T): T = {
+    try {
+      f
+    } catch {
+      case e if maxAttempts > 1 =>
+        Thread.sleep(delay.toMillis)
+        retry(maxAttempts - 1, delay * 2)(f)
+    }
+  }
 }

Consider adding metrics for monitoring:

private def recordMetrics(sessionToken: String, startTime: Long, success: Boolean): Unit = {
  val duration = System.currentTimeMillis() - startTime
  MetricsRegistry.defaultRegistry.counter("graphql.reconnection.requests").inc()
  MetricsRegistry.defaultRegistry.histogram("graphql.reconnection.duration").update(duration)
  if (!success) {
    MetricsRegistry.defaultRegistry.counter("graphql.reconnection.failures").inc()
  }
}


// Force reconnection with graphql to refresh permissions
Sender.sendForceUserGraphqlReconnectionSysMsg(liveMeeting.props.meetingProp.intId, registeredUser.id, registeredUser.sessionToken, msg.reasonCode, outGW)
GraphqlMiddleware.requestGraphqlReconnection(registeredUser.sessionToken, msg.reasonCode)

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.

⚠️ Potential issue

Add error handling for GraphQL reconnection request

The GraphQL reconnection request lacks error handling which could lead to silent failures.

Consider wrapping the call with error handling:

-      GraphqlMiddleware.requestGraphqlReconnection(registeredUser.sessionToken, msg.reasonCode)
+      try {
+        GraphqlMiddleware.requestGraphqlReconnection(Vector(registeredUser.sessionToken), msg.reasonCode)
+      } catch {
+        case e: Exception =>
+          log.error(s"Failed to request GraphQL reconnection for user ${registeredUser.id}", e)
+          // Consider if we need to take any recovery actions
+      }

Committable suggestion skipped: line range outside the PR's diff.

websrv.ConnectionHandler(w, r)
})

http.HandleFunc("/graphql-reconnection", websrv.ReconnectionHandler)

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.

⚠️ Potential issue

Consider adding rate limiting to the reconnection endpoint

While the /graphql endpoint has rate limiting protection, the new /graphql-reconnection endpoint doesn't. This could potentially be exploited for DoS attacks.

Consider applying the same rate limiter:

-http.HandleFunc("/graphql-reconnection", websrv.ReconnectionHandler)
+http.HandleFunc("/graphql-reconnection", func(w http.ResponseWriter, r *http.Request) {
+    ctx, cancel := context.WithTimeout(r.Context(), 120*time.Second)
+    defer cancel()
+    
+    if err := rateLimiter.Wait(ctx); err != nil {
+        if !errors.Is(err, context.Canceled) {
+            http.Error(w, "Request cancelled or rate limit exceeded", http.StatusTooManyRequests)
+        }
+        return
+    }
+    
+    websrv.ReconnectionHandler(w, r)
+})

Committable suggestion skipped: line range outside the PR's diff.

u <- RegisteredUsers.findWithUserId(uvo.intId, liveMeeting.registeredUsers)
} yield {
Sender.sendForceUserGraphqlReconnectionSysMsg(liveMeeting.props.meetingProp.intId, uvo.intId, u.sessionToken, "lock_user_changed", outGW)
GraphqlMiddleware.requestGraphqlReconnection(u.sessionToken, "lock_user_changed")

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.

⚠️ Potential issue

Add error handling for GraphQL reconnection request

The GraphQL reconnection request lacks error handling. If the request fails, the lock status change would proceed without the necessary GraphQL permission update, potentially leading to the race condition this PR aims to fix.

Consider handling the response:

-GraphqlMiddleware.requestGraphqlReconnection(u.sessionToken, "lock_user_changed")
+val reconnectionSuccess = GraphqlMiddleware.requestGraphqlReconnection(u.sessionToken, "lock_user_changed")
+if (!reconnectionSuccess) {
+    log.error(s"Failed to reconnect GraphQL for user ${uvo.intId} after lock status change")
+    // Consider appropriate error handling strategy
+}

Committable suggestion skipped: line range outside the PR's diff.

} yield {
RegisteredUsers.setUserLoggedOutFlag(liveMeeting.registeredUsers, ru)
Sender.sendForceUserGraphqlReconnectionSysMsg(liveMeeting.props.meetingProp.intId, ru.id, ru.sessionToken, "user_loggedout", outGW)
GraphqlMiddleware.requestGraphqlReconnection(ru.sessionToken, "user_loggedout")

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.

⚠️ Potential issue

Consider reversing the sequence of operations

The code updates the user's logged-out flag before ensuring the GraphQL reconnection is successful. This could lead to a state inconsistency if the reconnection fails.

Consider reversing the sequence:

-RegisteredUsers.setUserLoggedOutFlag(liveMeeting.registeredUsers, ru)
-GraphqlMiddleware.requestGraphqlReconnection(ru.sessionToken, "user_loggedout")
+val reconnectionSuccess = GraphqlMiddleware.requestGraphqlReconnection(ru.sessionToken, "user_loggedout")
+if (reconnectionSuccess) {
+    RegisteredUsers.setUserLoggedOutFlag(liveMeeting.registeredUsers, ru)
+} else {
+    log.error(s"Failed to reconnect GraphQL for user ${ru.id} during logout")
+    // Consider appropriate error handling strategy
+}

Committable suggestion skipped: line range outside the PR's diff.

@github-actions

github-actions Bot commented Dec 4, 2024

Copy link
Copy Markdown

Automated tests Summary

✅ All the CI tests have passed!

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.

2 participants