Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance webhook tests and error handling for authentication #930

Merged
merged 1 commit into from
Nov 27, 2024

Conversation

chacha912
Copy link
Contributor

@chacha912 chacha912 commented Nov 27, 2024

What this PR does / why we need it?

  • Update webhook tests to align with new method configuration behavior
  • Add missing test cases (RemoveDocument, Broadcast)

Any background context you want to provide?

What are the relevant tickets?

Related yorkie-team/yorkie#1082

Checklist

  • Added relevant tests or not required
  • Didn't break anything

Summary by CodeRabbit

  • New Features

    • Enhanced error handling for authentication failures during broadcast operations.
    • Added support for a new method type, 'Broadcast', in the AuthErrorEvent interface.
  • Bug Fixes

    • Improved robustness of token management and error handling in webhook tests.
  • Tests

    • Expanded test cases to cover additional scenarios for token refresh and authentication errors.
    • Updated tests to utilize multiple client instances for more comprehensive document operation testing.

@chacha912 chacha912 requested a review from hackerwins November 27, 2024 02:21
Copy link

coderabbitai bot commented Nov 27, 2024

Walkthrough

The changes in this pull request focus on enhancing error handling and authentication management within the Client class's broadcast method and related components. A new error condition for ConnectError specifically checks for ErrUnauthenticated, triggering an AuthError event. The handleConnectError method is updated to refresh the authentication token upon encountering authentication failures. Additionally, the AuthErrorEvent interface is modified to include a new Broadcast method type. The test suite is also expanded to cover new scenarios related to token management and error handling.

Changes

File Change Summary
packages/sdk/src/client/client.ts Modified broadcast method to add error handling for ConnectError and ErrUnauthenticated, publishing an AuthError event. Updated handleConnectError to refresh the authentication token.
packages/sdk/src/document/document.ts Updated AuthErrorEvent interface to include a new method type: 'Broadcast'.
packages/sdk/test/integration/webhook_test.ts Introduced AllAuthWebhookMethods constant, expanded test cases for token management and error handling, and modified existing tests to utilize multiple client instances for comprehensive testing.

Possibly related PRs

Suggested reviewers

  • hackerwins

🐇 In the realm of code, I hop with glee,
New errors caught, as clear as can be!
With tokens refreshed, our clients will sing,
Broadcasting joy, oh what joy it will bring!
So here’s to the changes, let’s all celebrate,
For smoother connections, we can’t wait! 🎉

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/sdk/src/client/client.ts

Oops! Something went wrong! :(

ESLint: 8.19.0

ESLint couldn't find the plugin "@typescript-eslint/eslint-plugin".

(The package "@typescript-eslint/eslint-plugin" was not found when loaded as a Node module from the directory "/packages/sdk".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install @typescript-eslint/eslint-plugin@latest --save-dev

The plugin "@typescript-eslint/eslint-plugin" was referenced from the config file in "packages/sdk/.eslintrc.js » ../../.eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.


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.

Copy link

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

🧹 Outside diff range and nitpick comments (5)
packages/sdk/src/client/client.ts (2)

730-744: Consider refactoring error handling for better maintainability.

The error handling logic could be extracted into a separate method to improve readability and maintainability.

Consider this refactor:

- if (await this.handleConnectError(err)) {
-   if (
-     err instanceof ConnectError &&
-     errorCodeOf(err) === Code.ErrUnauthenticated
-   ) {
-     attachment.doc.publish([
-       {
-         type: DocEventType.AuthError,
-         value: {
-           reason: errorMetadataOf(err).reason,
-           method: 'Broadcast',
-         },
-       },
-     ]);
-   }
+ if (await this.handleBroadcastError(err, attachment)) {

And add a new method:

private async handleBroadcastError<T, P extends Indexable>(
  err: unknown,
  attachment: Attachment<T, P>
): Promise<boolean> {
  if (!(await this.handleConnectError(err))) {
    return false;
  }

  if (
    err instanceof ConnectError &&
    errorCodeOf(err) === Code.ErrUnauthenticated
  ) {
    attachment.doc.publish([
      {
        type: DocEventType.AuthError,
        value: {
          reason: errorMetadataOf(err).reason,
          method: 'Broadcast',
        },
      },
    ]);
  }

  return true;
}

730-744: Consider creating a shared error handling utility.

The authentication error handling pattern is duplicated across multiple methods (broadcast, syncInternal, runWatchLoop). Consider extracting this into a shared utility method.

Consider adding a utility method:

private publishAuthError<T, P extends Indexable>(
  err: unknown,
  attachment: Attachment<T, P>,
  method: string
): void {
  if (
    err instanceof ConnectError &&
    errorCodeOf(err) === Code.ErrUnauthenticated
  ) {
    attachment.doc.publish([
      {
        type: DocEventType.AuthError,
        value: {
          reason: errorMetadataOf(err).reason,
          method,
        },
      },
    ]);
  }
}

This can then be used across all methods:

this.publishAuthError(err, attachment, 'Broadcast');
this.publishAuthError(err, attachment, 'PushPull');
this.publishAuthError(err, attachment, 'WatchDocuments');
packages/sdk/test/integration/webhook_test.ts (3)

345-368: Refactor duplicated project setup code into a helper function

The code for creating and updating a project is duplicated in multiple test cases (lines 345–368 and 581–605). Refactoring this into a helper function will improve maintainability and reduce code duplication.

You can create a helper function like createProjectWithWebhook:

+async function createProjectWithWebhook(methods: string[]): Promise<{ projectId: string; apiKey: string }> {
+  const projectResponse = await axios.post(
+    `${testRPCAddr}/yorkie.v1.AdminService/CreateProject`,
+    { name: `auth-webhook-${new Date().getTime()}` },
+    {
+      headers: { Authorization: adminToken },
+    },
+  );
+  const projectId = projectResponse.data.project.id;
+  const apiKey = projectResponse.data.project.publicKey;
+
+  await axios.post(
+    `${testRPCAddr}/yorkie.v1.AdminService/UpdateProject`,
+    {
+      id: projectId,
+      fields: {
+        auth_webhook_url: `http://${webhookServerAddress}:${webhookServerPort}/auth-webhook`,
+        auth_webhook_methods: { methods },
+      },
+    },
+    {
+      headers: { Authorization: adminToken },
+    },
+  );
+  return { projectId, apiKey };
+}

Then replace the duplicated code in your tests:

-// Create new project
-const projectResponse = await axios.post(
-  `${testRPCAddr}/yorkie.v1.AdminService/CreateProject`,
-  { name: `auth-webhook-${new Date().getTime()}` },
-  {
-    headers: { Authorization: adminToken },
-  },
-);
-const projectId = projectResponse.data.project.id;
-apiKey = projectResponse.data.project.publicKey;
-
-// Update project with webhook URL and methods
-await axios.post(
-  `${testRPCAddr}/yorkie.v1.AdminService/UpdateProject`,
-  {
-    id: projectId,
-    fields: {
-      auth_webhook_url: `http://${webhookServerAddress}:${webhookServerPort}/auth-webhook`,
-      auth_webhook_methods: { methods: ['RemoveDocument'] },
-    },
-  },
-  {
-    headers: { Authorization: adminToken },
-  },
-);
+const { projectId, apiKey } = await createProjectWithWebhook(['RemoveDocument']);

Also applies to: 581-605


145-150: Reuse the authTokenInjector function for multiple clients

You have identical authTokenInjector functions for c1 and c2. Consider defining it once and reusing it to simplify the code.

Refactor as follows:

+const authTokenInjector = async () => {
+  return `token-${Date.now() + 1000 * 60 * 60}`; // expire in 1 hour
+};

const c1 = new yorkie.Client(testRPCAddr, {
  apiKey,
- authTokenInjector: async () => {
-   return `token-${Date.now() + 1000 * 60 * 60}`; // expire in 1 hour
- },
+ authTokenInjector,
});

const c2 = new yorkie.Client(testRPCAddr, {
  apiKey,
- authTokenInjector: async () => {
-   return `token-${Date.now() + 1000 * 60 * 60}`; // expire in 1 hour
- },
+ authTokenInjector,
});

371-376: Handle potential negative token expiration times

In your authTokenInjector function (lines 371–376 and 607–612), you return expired tokens by subtracting TokenExpirationMs from Date.now(). Ensure that TokenExpirationMs is always positive to prevent potential issues with negative expiration times.

Consider adding a check or using absolute values:

-return `token-${Date.now() - TokenExpirationMs}`; // token expired
+return `token-${Date.now() - Math.abs(TokenExpirationMs)}`; // token expired

Also applies to: 607-612

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 63d2dce and f58b35a.

📒 Files selected for processing (3)
  • packages/sdk/src/client/client.ts (1 hunks)
  • packages/sdk/src/document/document.ts (1 hunks)
  • packages/sdk/test/integration/webhook_test.ts (5 hunks)
🔇 Additional comments (2)
packages/sdk/src/client/client.ts (1)

730-744: LGTM! Well-structured error handling for authentication failures.

The implementation correctly:

  • Checks for authentication errors before retry attempts
  • Publishes AuthError events with proper context
  • Maintains the existing retry mechanism
packages/sdk/src/document/document.ts (1)

428-428: LGTM! The AuthErrorEvent interface extension is well-aligned.

The addition of 'Broadcast' to the method types is consistent with the enhanced error handling for broadcast operations.

Let's verify the broadcast authentication error handling implementation:

✅ Verification successful

Based on the search results, I can now generate the final response:

The AuthErrorEvent interface extension is correctly implemented and consistent with the codebase.

The search results show that:

  1. The AuthErrorEvent interface is properly defined with DocEventType.AuthError and includes 'Broadcast' as a valid method type
  2. The auth error event handling is implemented in the event subscription system
  3. The broadcast method exists and can trigger events through the publish mechanism

The addition of 'Broadcast' to the method types is a valid extension that aligns with the existing auth error handling infrastructure.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the broadcast authentication error handling implementation
# Expected: Find the broadcast method that triggers AuthError events

# Search for broadcast method implementation that handles auth errors
ast-grep --pattern 'broadcast($$$) {
  $$$
  type: DocEventType.AuthError,
  $$$
}'

# Search for broadcast-related authentication error handling
rg -A 5 'DocEventType\.AuthError.*Broadcast'

Length of output: 132


Script:

#!/bin/bash
# Let's try a different approach to find broadcast-related error handling

# Search for broadcast method implementation
ast-grep --pattern 'broadcast($$$) {
  $$$
}'

# Search for AuthError event emissions
rg -B 5 -A 2 'emit.*AuthError'

# Search for broadcast-related error handling
rg -B 3 -A 3 'broadcast.*error|error.*broadcast' -i

# Look for any authentication checks in broadcast-related code
rg -B 3 -A 3 'broadcast.*auth|auth.*broadcast' -i

Length of output: 109885


Script:

#!/bin/bash
# Let's search for broadcast-related authentication code more broadly

# Search for broadcast method implementation and auth-related code
ast-grep --pattern 'broadcast($$$) {
  $$$
  auth
  $$$
}'

# Search for auth error handling in broadcast context
rg -B 5 -A 5 'broadcast.*error|error.*broadcast' -i

# Look for auth error event emissions
rg -B 3 -A 3 'emit.*AuthError.*method.*Broadcast'

# Search for broadcast method with error handling
rg -B 5 -A 5 'broadcast.*\{' -i

Length of output: 110354


Script:

#!/bin/bash
# Let's search for auth error handling in the document.ts file specifically

# Search for auth error event type definition and usage
rg -B 3 -A 3 'AuthError.*event' packages/sdk/src/document/document.ts

# Search for broadcast method implementation
rg -B 10 -A 10 'broadcast.*\{' packages/sdk/src/document/document.ts

# Search for auth error handling in broadcast context
rg -B 5 -A 5 'AuthError.*Broadcast|Broadcast.*AuthError' packages/sdk/src/document/document.ts

# Look for event emission related to broadcast auth
rg -B 5 -A 5 'emit.*auth.*broadcast|broadcast.*auth.*emit' -i packages/sdk/src/document/document.ts

Length of output: 1914


Script:

#!/bin/bash
# Let's search for auth error handling more broadly

# Search for AuthError type definition
rg -B 5 -A 5 'type.*AuthError' packages/sdk/src/document/document.ts

# Search for DocEventType.AuthError usage
rg -B 5 -A 5 'DocEventType\.AuthError' packages/sdk/src/document/document.ts

# Search for auth error handling in event types
rg -B 5 -A 5 'interface.*AuthError.*Event' packages/sdk/src/document/document.ts

# Look for auth error event emission
rg -B 5 -A 5 'emit.*AuthError|publish.*AuthError' packages/sdk/src/document/document.ts

Length of output: 1842

packages/sdk/test/integration/webhook_test.ts Show resolved Hide resolved
Copy link
Member

@hackerwins hackerwins left a comment

Choose a reason for hiding this comment

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

Thanks for your contribution.

@hackerwins hackerwins changed the title Update webhook tests and add missing test cases Enhance webhook tests and error handling for authentication Nov 27, 2024
@hackerwins hackerwins merged commit ea20ed9 into main Nov 27, 2024
2 checks passed
@hackerwins hackerwins deleted the webhook-methods branch November 27, 2024 10:10
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