Skip to content
This repository was archived by the owner on May 30, 2025. It is now read-only.

feat: generate JWT token on each call#28

Merged
tzdybal merged 1 commit intomainfrom
tzdybal/fix_jwt
Feb 18, 2025
Merged

feat: generate JWT token on each call#28
tzdybal merged 1 commit intomainfrom
tzdybal/fix_jwt

Conversation

@tzdybal
Copy link
Contributor

@tzdybal tzdybal commented Feb 18, 2025

Overview

Resolves #27

Summary by CodeRabbit

  • Refactor
    • Enhanced authentication token management with refined secret decoding and improved error handling for a more robust and reliable process.
  • Tests
    • Streamlined simulated API response encoding in test cases to ensure consistency without altering overall behavior.

@coderabbitai
Copy link

coderabbitai bot commented Feb 18, 2025

Walkthrough

The pull request refines the JWT secret handling for authentication. In execution.go, the signature of getAuthToken is updated to accept a byte slice, and a new helper function decodeSecret is introduced to decode a hex string into this byte slice. The integration tests in integration_test.go are updated accordingly to incorporate these changes with improved error handling. Additionally, minor adjustments were made in mocks_test.go to simplify JSON response encoding.

Changes

File(s) Summary of Changes
execution.go, integration_test.go * JWT secret handling improved: getAuthToken now accepts a byte slice.
* Introduced decodeSecret for decoding hex-string secrets.
* Integration test updated to decode the secret and handle errors before calling getAuthToken.
mocks_test.go * Simplified JSON response encoding in NewMockEthAPI by condensing two lines into a single line without changing functionality.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Integration Test/Caller
    participant Container as waitForRethContainer
    participant Decoder as decodeSecret
    participant Auth as getAuthToken

    Client->>Container: Provide JWT secret (hex string)
    Container->>Decoder: Decode secret from hex to byte slice
    Decoder-->>Container: Return decoded secret (or error)
    alt Decoding successful
        Container->>Auth: Request JWT token using secret bytes
        Auth-->>Container: Return JWT token
        Container-->>Client: Return JWT token
    else Decoding failed
        Container-->>Client: Return error
    end
Loading

Possibly related PRs

Suggested reviewers

  • gupadhyaya
  • MSevey

Poem

I'm a rabbit hopping through the code,
With secrets decoded on my merry road.
A hex-to-byte tale in every line,
JWT tokens now perfectly align.
Hopping with joy as the bugs all vanish—
CodeRabbit's magic makes the system flourish! 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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.

@RollkitBot RollkitBot requested review from a team, MSevey, gupadhyaya and tuxcanfly and removed request for a team February 18, 2025 14:00
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 (1)
integration_test.go (1)

197-288: 🛠️ Refactor suggestion

Add test cases for JWT token generation.

Consider adding test cases for:

  • Invalid JWT secrets (wrong length, invalid hex)
  • Expired tokens
  • Token generation errors
+func TestJWTTokenGeneration(t *testing.T) {
+	tests := []struct {
+		name    string
+		secret  string
+		wantErr bool
+	}{
+		{
+			name:    "valid secret",
+			secret:  "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
+			wantErr: false,
+		},
+		{
+			name:    "invalid hex",
+			secret:  "invalid-hex",
+			wantErr: true,
+		},
+		{
+			name:    "wrong length",
+			secret:  "1234",
+			wantErr: true,
+		},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			secret, err := decodeSecret(tt.secret)
+			if tt.wantErr {
+				require.Error(t, err)
+				return
+			}
+			require.NoError(t, err)
+
+			token, err := getAuthToken(secret)
+			require.NoError(t, err)
+			require.NotEmpty(t, token)
+		})
+	}
+}
🧹 Nitpick comments (1)
execution.go (1)

293-305: Consider making token expiration time configurable.

The token expiration time is currently hardcoded to 1 hour. Consider making it configurable to support different security requirements.

+// DefaultTokenExpiration is the default expiration time for JWT tokens
+const DefaultTokenExpiration = time.Hour

-func getAuthToken(jwtSecret []byte) (string, error) {
+func getAuthToken(jwtSecret []byte, expiration time.Duration) (string, error) {
+	if expiration == 0 {
+		expiration = DefaultTokenExpiration
+	}
 	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
-		"exp": time.Now().Add(time.Hour * 1).Unix(), // Expires in 1 hour
+		"exp": time.Now().Add(expiration).Unix(),
 		"iat": time.Now().Unix(),
 	})
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 80138b5 and 89739f7.

📒 Files selected for processing (3)
  • execution.go (2 hunks)
  • integration_test.go (1 hunks)
  • mocks_test.go (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • mocks_test.go
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test / Run Unit Tests
🔇 Additional comments (2)
execution.go (1)

57-67: LGTM! Improved JWT secret handling.

The changes enhance security by properly decoding hex-encoded JWT secrets and implementing robust error handling.

integration_test.go (1)

169-174: LGTM! Proper integration with JWT token changes.

The changes correctly implement the new JWT token generation flow with proper error handling.

@tzdybal tzdybal enabled auto-merge February 18, 2025 14:05
@tzdybal tzdybal added this pull request to the merge queue Feb 18, 2025
Merged via the queue into main with commit 78e9b7e Feb 18, 2025
18 checks passed
@tac0turtle tac0turtle removed this from Evolve Apr 24, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Improve JWT token handling

2 participants