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

Log incoming metadata of JWT verified nodes #402

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

mkysel
Copy link
Collaborator

@mkysel mkysel commented Jan 9, 2025

Fixes #391

Summary by CodeRabbit

  • New Features

    • Enhanced JWT verification to return node ID alongside error status
    • Added logging of incoming client address and DNS name during authentication
  • Bug Fixes

    • Improved token verification process with more detailed error handling
  • Refactor

    • Updated authentication-related method signatures to provide more context during verification
    • Modified mock and test implementations to support new verification approach

Copy link

coderabbitai bot commented Jan 9, 2025

Walkthrough

This pull request introduces changes to the authentication (authn) package, modifying the Verify method across multiple files to return a uint32 node ID alongside the existing error. The changes impact the JWTVerifier interface, RegistryVerifier implementation, and related test files. The AuthInterceptor in the server interceptors has been updated to log incoming client address information and capture the node ID returned during token verification.

Changes

File Change Summary
pkg/authn/interface.go Updated Verify method signature to return (uint32, error)
pkg/authn/verifier.go Modified RegistryVerifier.Verify() to return subject node ID and error
pkg/authn/claims_test.go, pkg/authn/verifier_test.go Updated test functions to handle new Verify method return signature
pkg/interceptors/server/auth.go Added logIncomingAddressIfAvailable method and updated token verification logging
pkg/mocks/authn/mock_JWTVerifier.go Updated mock Verify method to match new return signature

Assessment against linked issues

Objective Addressed Explanation
Print metadata about incoming node connections [#391]

Possibly related PRs

Suggested reviewers

  • richardhuaaa

Finishing Touches

  • 📝 Generate Docstrings

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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 comments (2)
pkg/mocks/authn/mock_JWTVerifier.go (2)

Line range hint 21-35: Update mock implementation to handle uint32 return value correctly

The current implementation always returns 0 for the uint32 value, which may not be suitable for testing scenarios where specific node IDs need to be verified.

Apply this diff to properly handle both return values:

 func (_m *MockJWTVerifier) Verify(tokenString string) (uint32, error) {
 	ret := _m.Called(tokenString)
 
 	if len(ret) == 0 {
 		panic("no return value specified for Verify")
 	}
 
-	var r0 error
-	if rf, ok := ret.Get(0).(func(string) error); ok {
-		r0 = rf(tokenString)
+	var r0 uint32
+	var r1 error
+	if rf, ok := ret.Get(0).(func(string) (uint32, error)); ok {
+		r0, r1 = rf(tokenString)
+	} else {
+		if ret.Get(0) != nil {
+			r0 = ret.Get(0).(uint32)
+		}
+		r1 = ret.Error(1)
+	}
-	} else {
-		r0 = ret.Error(0)
-	}
 
-	return 0, r0
+	return r0, r1
 }

Line range hint 47-67: Update mock Return and RunAndReturn methods to support new signature

The Return and RunAndReturn methods need to be updated to support the new (uint32, error) signature.

Apply this diff to update the methods:

-func (_c *MockJWTVerifier_Verify_Call) Return(_a0 error) *MockJWTVerifier_Verify_Call {
-	_c.Call.Return(_a0)
+func (_c *MockJWTVerifier_Verify_Call) Return(_a0 uint32, _a1 error) *MockJWTVerifier_Verify_Call {
+	_c.Call.Return(_a0, _a1)
 	return _c
 }

-func (_c *MockJWTVerifier_Verify_Call) RunAndReturn(run func(string) error) *MockJWTVerifier_Verify_Call {
+func (_c *MockJWTVerifier_Verify_Call) RunAndReturn(run func(string) (uint32, error)) *MockJWTVerifier_Verify_Call {
 	_c.Call.Return(run)
 	return _c
 }
🧹 Nitpick comments (4)
pkg/authn/claims_test.go (1)

73-73: Add assertions for the returned node ID

The tests currently ignore the returned node ID (using _). Consider adding assertions to verify the correct node ID is returned in success cases.

Example addition:

-			_, verificationError := verifier.Verify(token.SignedString)
+			nodeID, verificationError := verifier.Verify(token.SignedString)
 			if tt.wantErr {
 				require.Error(t, verificationError)
 			} else {
 				require.NoError(t, verificationError)
+				require.Equal(t, uint32(SIGNER_NODE_ID), nodeID, "Unexpected node ID returned")
 			}

Also applies to: 122-122

pkg/authn/verifier_test.go (1)

68-69: Enhance test coverage for node ID verification

The tests should verify both error cases and successful node ID returns. Consider adding assertions for:

  1. Successful verification returns the correct node ID
  2. Failed verification returns 0 as node ID

Example enhancement for TestVerifier:

-	_, verificationError := verifier.Verify(token.SignedString)
+	nodeID, verificationError := verifier.Verify(token.SignedString)
 	require.NoError(t, verificationError)
+	require.Equal(t, uint32(SIGNER_NODE_ID), nodeID, "Successful verification should return signer's node ID")

-	_, verificationError = verifier.Verify(tokenForWrongNode.SignedString)
+	nodeID, verificationError = verifier.Verify(tokenForWrongNode.SignedString)
 	require.Error(t, verificationError)
+	require.Equal(t, uint32(0), nodeID, "Failed verification should return 0 as node ID")

Also applies to: 75-76, 93-94, 108-109, 128-129, 150-151, 172-173, 195-196, 207-208

pkg/interceptors/server/auth.go (2)

59-82: Consider performance and security implications of DNS lookups

The DNS resolution in logIncomingAddressIfAvailable has several concerns:

  1. DNS lookups are blocking operations that could impact performance
  2. Failed DNS resolutions still result in logging, which could flood logs
  3. DNS names are not validated before logging, potentially leading to log injection

Consider these improvements:

  1. Make DNS resolution asynchronous or use a timeout
  2. Add rate limiting for failed resolutions
  3. Validate and sanitize DNS names before logging

Example implementation with timeout:

 func (i *AuthInterceptor) logIncomingAddressIfAvailable(ctx context.Context, nodeId uint32) {
 	if i.logger.Core().Enabled(zap.DebugLevel) {
 		if p, ok := peer.FromContext(ctx); ok {
 			clientAddr := p.Addr.String()
 			var dnsName []string
-			// Attempt to resolve the DNS name
 			host, _, err := net.SplitHostPort(clientAddr)
 			if err == nil {
-				dnsName, err = net.LookupAddr(host)
+				// Add timeout for DNS resolution
+				dnsCtx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
+				defer cancel()
+				resolver := &net.Resolver{}
+				dnsName, err = resolver.LookupAddr(dnsCtx, host)
 				if err != nil || len(dnsName) == 0 {
 					dnsName = []string{"Unknown"}
 				}

5-6: Consider using x/net/netutil for DNS operations

For better DNS resolution handling, consider using the more robust golang.org/x/net/netutil package.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 994f91e and 1241572.

📒 Files selected for processing (6)
  • pkg/authn/claims_test.go (2 hunks)
  • pkg/authn/interface.go (1 hunks)
  • pkg/authn/verifier.go (2 hunks)
  • pkg/authn/verifier_test.go (8 hunks)
  • pkg/interceptors/server/auth.go (4 hunks)
  • pkg/mocks/authn/mock_JWTVerifier.go (2 hunks)
🔇 Additional comments (3)
pkg/authn/verifier.go (1)

Line range hint 30-53: LGTM! Proper error handling and security validation

The implementation:

  1. Returns 0 with errors for invalid cases
  2. Validates the token before returning the node ID
  3. Maintains the security checks in the correct order
pkg/interceptors/server/auth.go (2)

98-108: LGTM: Unary interceptor changes look good

The changes to capture and log the nodeId in the Unary interceptor are well-implemented.


129-140: LGTM: Stream interceptor changes look good

The changes to capture and log the nodeId in the Stream interceptor are well-implemented and consistent with the Unary interceptor.

@@ -1,5 +1,5 @@
package authn

type JWTVerifier interface {
Verify(tokenString string) error
Verify(tokenString string) (uint32, error)
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Update mock implementation to handle both return values

The interface change is properly implemented in the main code, but the mock implementation needs to be updated. The mock's Return and RunAndReturn methods are incorrectly handling the return values:

  • pkg/mocks/authn/mock_JWTVerifier.go: Update Return and RunAndReturn to handle both uint32 and error return values.
🔗 Analysis chain

Verify all implementations of the JWTVerifier interface

The change to return (uint32, error) instead of just error is a breaking change that requires updates to all implementations of the JWTVerifier interface.

Let's verify all implementations:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find all implementations of JWTVerifier interface
ast-grep --pattern 'type $_ struct {
  $$$
}

func ($_ *$_) Verify(tokenString string) (uint32, error) {
  $$$
}'

Length of output: 115


Script:

#!/bin/bash
# Try different approaches to find implementations

# Search for any Verify method with the new signature
echo "=== Searching for Verify method implementations ==="
ast-grep --pattern 'func $_($_ $_) Verify(tokenString string) (uint32, error)'

# Use ripgrep to find potential implementation files
echo -e "\n=== Searching for files mentioning JWTVerifier ==="
rg -l "JWTVerifier"

# Search for Verify method calls to find potential implementations
echo -e "\n=== Searching for Verify method calls ==="
rg "\.Verify\("

Length of output: 2274


Script:

#!/bin/bash
# Find the verifier implementation
echo "=== Searching for verifier implementation ==="
fd "verifier\.go" --exclude "*test.go" --exclude "*mock*.go"

# Check mock implementation
echo -e "\n=== Checking mock implementation ==="
cat pkg/mocks/authn/mock_JWTVerifier.go

# Search for struct definitions in verifier files
echo -e "\n=== Searching for verifier structs ==="
rg -A 5 "type.*struct" pkg/authn/

Length of output: 4015


Script:

#!/bin/bash
# Check the verifier implementation
echo "=== Checking verifier implementation ==="
cat pkg/authn/verifier.go

# Also check auth.go since it's using the Verify method
echo -e "\n=== Checking auth interceptor usage ==="
cat pkg/interceptors/server/auth.go

Length of output: 7757

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.

Print metadata about incoming node connections
1 participant