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

Refactor webhook method configuration and add CLI commands #1082

Merged
merged 2 commits into from
Nov 27, 2024

Conversation

chacha912
Copy link
Contributor

@chacha912 chacha912 commented Nov 27, 2024

What this PR does / why we need it:

  1. Change webhook behavior to require explicit method configuration
  • Previously: Webhooks triggered for all methods when none specified
  • Now: Webhooks only trigger for explicitly configured methods
  • This makes the behavior more intuitive and gives users better control
  1. Add CLI commands for managing webhook methods
  • Implement commands to add/remove webhook methods
  • Support for single method, multiple methods, and ALL methods
  • Remove operations are always processed before add operations
# Add a single method
bin/yorkie project update project-name --auth-webhook-method-add PushPull

# Remove a method
bin/yorkie project update project-name --auth-webhook-method-rm PushPull

# Add ALL methods
bin/yorkie project update project-name --auth-webhook-method-add ALL

# Remove ALL methods
bin/yorkie project update project-name --auth-webhook-method-rm ALL

# Add multiple methods
bin/yorkie project update project-name \
  --auth-webhook-method-add ActivateClient \
  --auth-webhook-method-add PushPull \
  --auth-webhook-method-add WatchDocuments

Which issue(s) this PR fixes:

Related yorkie-team/dashboard#175 (comment)

Special notes for your reviewer:

Does this PR introduce a user-facing change?:

image

$ bin/yorkie project update project-name --help
Update a project

Usage:
  yorkie project update [name] [flags]

Examples:
yorkie project update name [options]

Flags:
      --auth-webhook-method-add stringArray   authorization-webhook methods to add ('ALL' for all methods)
      --auth-webhook-method-rm stringArray    authorization-webhook methods to remove ('ALL' for all methods)
      --auth-webhook-url string               authorization-webhook update url
      --client-deactivate-threshold string    client deactivate threshold for housekeeping
  -h, --help                                  help for update
      --name string                           new project name

Global Flags:
  -o, --output string     One of 'yaml' or 'json'.
      --rpc-addr string   Address of the rpc server (default "localhost:8080")

Additional documentation:


Checklist:

  • Added relevant tests or not required
  • Addressed and resolved all CodeRabbit review comments
  • Didn't break anything

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced project update functionality with new options for managing authorization webhook methods.
    • Introduced flexible management of authorization methods during project updates, allowing addition and removal of methods.
  • Bug Fixes

    • Adjusted behavior of authorization requirement logic to not require authentication when no methods are specified.
  • Tests

    • Updated test cases to reflect changes in authorization webhook methods, ensuring accurate validation of new functionality.

Previously triggered for all methods by default.
Modified code to require explicit method configuration.
@chacha912 chacha912 requested a review from hackerwins November 27, 2024 02:13
Copy link

coderabbitai bot commented Nov 27, 2024

Walkthrough

The changes in this pull request involve modifications to the authorization handling in the Project struct and its associated methods. The RequireAuth method's logic was altered to indicate that no authorization is required when no methods are specified. Additionally, the update command was enhanced to manage authorization webhook methods more flexibly, allowing for the addition and removal of methods through command flags. Corresponding test cases were updated to reflect these changes in both functionality and expected outcomes.

Changes

File Change Summary
api/types/project.go Modified RequireAuth method logic to return false when AuthWebhookMethods is empty.
api/types/project_test.go Updated test cases for RequireAuth to assert false when no authentication methods are specified.
cmd/yorkie/project/update.go Added flags for managing authorization webhook methods; enhanced logic in RunE function for adding/removing methods.
test/integration/auth_webhook_test.go Introduced allWebhookMethods variable; updated test cases to use this variable for AuthWebhookMethods field.

Assessment against linked issues

Objective Addressed Explanation
Show all Auth Webhook methods checked when no specific method is selected (175) The changes do not address UI behavior or state.

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 (4)
api/types/project.go (1)

Line range hint 63-73: Consider enhancing documentation and validation

The method's behavior could be made more explicit and robust.

Consider these improvements:

 // RequireAuth returns whether the given method requires authorization.
+// If AuthWebhookURL is set but AuthWebhookMethods is empty, no authorization
+// is required. To require authorization for all methods, explicitly add them
+// to AuthWebhookMethods.
 func (p *Project) RequireAuth(method Method) bool {
     if len(p.AuthWebhookURL) == 0 {
         return false
     }
 
     if len(p.AuthWebhookMethods) == 0 {
         return false
     }
 
+    // Convert method list to a map for O(1) lookup
+    methodSet := make(map[Method]struct{}, len(p.AuthWebhookMethods))
+    for _, m := range p.AuthWebhookMethods {
+        methodSet[Method(m)] = struct{}{}
+    }
+    
+    _, exists := methodSet[method]
+    return exists
 }
cmd/yorkie/project/update.go (1)

38-39: Consider using typed constants for webhook methods.

While the implementation is functional, using raw strings for method names could lead to runtime errors due to typos. Consider:

  1. Using typed constants or enums for webhook methods
  2. Adding validation for method names when they're added

Example improvement:

-var allAuthWebhookMethods = []string{
-    string(types.ActivateClient),
-    string(types.DeactivateClient),
-    // ...
-}
+var allAuthWebhookMethods = []types.WebhookMethod{
+    types.ActivateClient,
+    types.DeactivateClient,
+    // ...
+}

+func isValidWebhookMethod(method string) bool {
+    for _, m := range allAuthWebhookMethods {
+        if string(m) == method {
+            return true
+        }
+    }
+    return false
+}

Also applies to: 44-53

test/integration/auth_webhook_test.go (2)

44-53: Add documentation for the allWebhookMethods variable

Consider adding a documentation comment explaining the purpose and usage of this variable, especially since it's used across multiple test cases.

+// allWebhookMethods contains all available webhook methods that can be configured
+// for authorization. This is used across test cases to verify webhook behavior
+// when all methods are enabled.
 var allWebhookMethods = &[]string{

Line range hint 215-260: LGTM! Comprehensive test coverage for selected methods

The test case effectively verifies the new behavior where only explicitly configured methods require authorization. It tests both authorized (Activate) and unauthorized (Attach) methods.

Consider adding an assertion to verify that the project's AuthWebhookMethods field is correctly set after the update:

 		)
 		assert.NoError(t, err)
+		
+		// Verify that only specified methods are configured
+		updatedProject, err := adminCli.GetProject(ctx, project.ID.String())
+		assert.NoError(t, err)
+		assert.Equal(t, []string{
+			string(types.AttachDocument),
+			string(types.WatchDocuments),
+		}, updatedProject.AuthWebhookMethods)
 
 		projectInfoCacheTTL := 5 * time.Second
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e863b62 and 3f82724.

📒 Files selected for processing (4)
  • api/types/project.go (1 hunks)
  • api/types/project_test.go (1 hunks)
  • cmd/yorkie/project/update.go (4 hunks)
  • test/integration/auth_webhook_test.go (12 hunks)
🔇 Additional comments (6)
api/types/project_test.go (2)

38-44: LGTM! Test correctly verifies the new webhook behavior.

The test case properly validates that when no methods are specified, authentication is not required for any method, which aligns with the new webhook behavior described in the PR objectives.


38-44: Verify impact on existing deployments.

This represents a significant behavioral change where webhooks will no longer trigger for all methods by default. This might affect existing deployments that rely on the previous behavior where an empty method list meant "allow all".

Let's check for potential impacts:

✅ Verification successful

Let me gather more information about the webhook behavior and its changes.


Let me check the changelog and previous behavior to understand if this is a documented change.


Based on the gathered information, I can now provide the final response:

The change in webhook behavior is safe and as designed

The current implementation is consistent with the documented behavior and previous changes. From the changelog entries, we can see that webhook authorization was intentionally designed with explicit method specification:

  • The feature was initially added with basic behavior (v0.1.5)
  • Authorization webhook methods were explicitly added as a configurable flag (pre-0.2.0)
  • The behavior has been stable since these initial implementations

The test case correctly verifies that an empty method list means "deny all" rather than "allow all", which is a more secure default that requires explicit method specification.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for existing webhook configurations that might be affected by this change

# Look for webhook-related configuration files
fd -e yaml -e json -e toml | xargs rg -l 'webhook|auth.*url' 

# Look for webhook URL configurations in code
rg -A 3 'AuthWebhookURL.*=|SetAuthWebhookURL|authWebhookURL'

# Look for tests that might need updates
rg -A 5 'TestAuth.*Webhook|webhook.*test'

Length of output: 10306


Script:

#!/bin/bash
# Look for the implementation of RequireAuth and its changes
ast-grep --pattern 'func (p *Project) RequireAuth($_) bool {
  $$$
}'

# Look for webhook-related configuration in the project
rg -l "AuthWebhookMethods.*empty" 

# Check for documentation about webhook configuration
fd README.md | xargs rg -l "webhook"

# Look for any migration scripts or upgrade notes
fd -e md | xargs rg -l "upgrade|migration|breaking.change"

Length of output: 1165


Script:

#!/bin/bash
# Check the changelog for any mentions of webhook changes
rg -A 5 -B 5 "webhook" CHANGELOG.md

# Look at previous implementation through git
git log -p api/types/project.go

# Check if this is documented in API docs
rg "webhook" api/docs/yorkie/v1/resources.openapi.yaml

Length of output: 1419

api/types/project.go (1)

65-65: ⚠️ Potential issue

⚠️ Breaking Change: Authorization behavior significantly modified

This change reverses the default authorization behavior when webhook URL is set but methods are empty. Previously, this would require authorization for all methods, but now it requires no authorization. This is a breaking change that could have security implications.

Consider the following recommendations:

  1. Add a migration guide for existing projects
  2. Update documentation to clearly explain the new behavior
  3. Consider adding a deprecation period where you warn about the upcoming behavior change
  4. Add logging to help detect affected projects

Let's verify the impact and identify affected projects:

cmd/yorkie/project/update.go (2)

131-131: LGTM!

The addition of AuthWebhookMethods to the updatable fields follows the existing pattern and is implemented correctly.


196-207: LGTM! Verify command help text.

The flag definitions are clear and follow the Docker CLI patterns as intended in the PR objectives.

Let's verify the command help text is properly registered:

✅ Verification successful

Flag definitions are properly implemented and registered

The code inspection confirms that:

  • The flags are correctly defined and registered in the init() function
  • The flag descriptions are clear and consistent
  • The flags are properly handled in the command's RunE function
  • The 'ALL' keyword functionality is implemented as described
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the help text for the update command flags

# Build the help text and check for the new flags
go run ./cmd/yorkie/main.go project update --help 2>&1 | grep -A 2 "auth-webhook-method"

Length of output: 83


Script:

#!/bin/bash
# Let's verify the command structure and help text using different approaches

# Check if the update command is registered and its flags
rg -A 5 "project update" cmd/

# Look for the flag registration in the update command
ast-grep --pattern 'func NewUpdateCommand($$$) *cobra.Command {
  $$$
}'

# Check for any test files that might verify the flags
fd -e go -E vendor test.*update

Length of output: 520


Script:

#!/bin/bash
# Let's examine the update command implementation more closely

# Look at the entire update.go file to understand the command structure
cat cmd/yorkie/project/update.go

# Search for any cobra.Command initialization patterns
ast-grep --pattern 'cmd := &cobra.Command{
  $$$
}'

Length of output: 5686

test/integration/auth_webhook_test.go (1)

Line range hint 1-677: LGTM! Comprehensive test coverage for webhook method configuration

The test file has been thoroughly updated to verify the new webhook behavior where methods must be explicitly configured. It includes comprehensive test coverage for:

  • Default behavior with all methods
  • Selected method authorization
  • Error handling
  • Caching behavior
  • Token management

The test cases are well-structured and effectively verify the changes described in the PR objectives.

cmd/yorkie/project/update.go Show resolved Hide resolved
Copy link

codecov bot commented Nov 27, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 46.79%. Comparing base (e863b62) to head (3f82724).
Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #1082   +/-   ##
=======================================
  Coverage   46.79%   46.79%           
=======================================
  Files          84       84           
  Lines       12219    12219           
=======================================
  Hits         5718     5718           
  Misses       5928     5928           
  Partials      573      573           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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 merged commit e6cfb15 into main Nov 27, 2024
5 checks passed
@hackerwins hackerwins deleted the webhook-methods branch November 27, 2024 09:59
@coderabbitai coderabbitai bot mentioned this pull request Dec 29, 2024
3 tasks
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