Skip to content

fix: Resolve infinite recursion in Auth API #10

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

Merged
merged 3 commits into from
Jan 13, 2025

Conversation

hanzeINGH
Copy link
Contributor

@hanzeINGH hanzeINGH commented Jan 13, 2025

Fix the infinite recursion problem caused during JWT authentication.

Summary by CodeRabbit

  • New Features

    • Enhanced authentication context management.
    • Added improved token retrieval mechanism for requests.
    • Introduced context-based authentication checks.
  • Improvements

    • Optimized authentication request handling.
    • Added more robust error logging for token retrieval.
  • Technical Updates

    • Updated context management functions.
    • Implemented new authentication context utilities.

Change-Id: I3042c85ea174c93e72d1617b473ea987c5e8ac8c
Copy link

coderabbitai bot commented Jan 13, 2025

Warning

Rate limit exceeded

@hanzeINGH has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 16 minutes and 52 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 16b623d and c32e172.

📒 Files selected for processing (1)
  • utils.go (2 hunks)

Walkthrough

The pull request introduces changes to authentication and context management across three files: auth.go, client.go, and utils.go. The modifications focus on improving how authentication contexts are handled during HTTP requests. The getAccessToken and doGetDeviceCode methods are updated to utilize a new context generated by genAuthContext. Additionally, the RoundTrip method in the authentication transport is enhanced to conditionally handle token retrieval based on the context's authentication status. New utility functions for context management are also added.

Changes

File Change Summary
auth.go Updated getAccessToken and doGetDeviceCode methods to use genAuthContext(ctx) for core requests.
client.go Modified RoundTrip method to check for authenticated context and conditionally retrieve access tokens.
utils.go Added contextKey type, authContextKey and authContextValue constants, and introduced genAuthContext() and isAuthContext() functions.

Sequence Diagram

sequenceDiagram
    participant Client
    participant AuthTransport
    participant AuthClient
    participant Core

    Client->>AuthTransport: Make HTTP Request
    AuthTransport->>AuthTransport: Check Context Authentication
    alt Is Authenticated Context
        AuthTransport->>Core: Forward Request Directly
    else Not Authenticated
        AuthTransport->>AuthClient: Retrieve Access Token
        AuthClient-->>AuthTransport: Return Token
        AuthTransport->>Core: Add Authorization Header
        AuthTransport->>Core: Forward Request
    end
Loading

Poem

🐰 In the realm of auth and code so bright,
Contexts dance with tokens' might.
Contexts tagged, requests so clean,
Authentication's new routine,
A rabbit's tale of context's grace! 🔐


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.

@hanzeINGH hanzeINGH changed the title fix: jwt request transport cycle fix: jwt recursion problem Jan 13, 2025
@hanzeINGH hanzeINGH changed the title fix: jwt recursion problem fix: jwt infinite recursion problem Jan 13, 2025
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

🧹 Nitpick comments (1)
utils.go (1)

58-60: Consider adding validation for nil context

The function should handle nil context gracefully.

 func genAuthContext(ctx context.Context) context.Context {
+    if ctx == nil {
+        ctx = context.Background()
+    }
     return context.WithValue(ctx, authContextKey, authContextValue)
 }
🧰 Tools
🪛 golangci-lint (1.62.2)

59-59: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions

(staticcheck)

🪛 GitHub Check: Test (1.21)

[failure] 59-59:
SA1029: should not use built-in type string as key for value; define your own type to avoid collisions (staticcheck)


[failure] 59-59:
SA1029: should not use built-in type string as key for value; define your own type to avoid collisions (staticcheck)

🪛 GitHub Check: Test (1.19)

[failure] 59-59:
SA1029: should not use built-in type string as key for value; define your own type to avoid collisions (staticcheck)


[failure] 59-59:
SA1029: should not use built-in type string as key for value; define your own type to avoid collisions (staticcheck)

🪛 GitHub Check: Test (1.18)

[failure] 59-59:
SA1029: should not use built-in type string as key for value; define your own type to avoid collisions (staticcheck)


[failure] 59-59:
SA1029: should not use built-in type string as key for value; define your own type to avoid collisions (staticcheck)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6930d97 and a66f111.

📒 Files selected for processing (3)
  • auth.go (3 hunks)
  • client.go (1 hunks)
  • utils.go (2 hunks)
🧰 Additional context used
🪛 golangci-lint (1.62.2)
utils.go

59-59: SA1029: should not use built-in type string as key for value; define your own type to avoid collisions

(staticcheck)

🪛 GitHub Check: Test (1.21)
utils.go

[failure] 59-59:
SA1029: should not use built-in type string as key for value; define your own type to avoid collisions (staticcheck)


[failure] 59-59:
SA1029: should not use built-in type string as key for value; define your own type to avoid collisions (staticcheck)

🪛 GitHub Check: Test (1.19)
utils.go

[failure] 59-59:
SA1029: should not use built-in type string as key for value; define your own type to avoid collisions (staticcheck)


[failure] 59-59:
SA1029: should not use built-in type string as key for value; define your own type to avoid collisions (staticcheck)

🪛 GitHub Check: Test (1.18)
utils.go

[failure] 59-59:
SA1029: should not use built-in type string as key for value; define your own type to avoid collisions (staticcheck)


[failure] 59-59:
SA1029: should not use built-in type string as key for value; define your own type to avoid collisions (staticcheck)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Test (1.23)
🔇 Additional comments (3)
utils.go (1)

62-72: LGTM! The context validation is thorough

The implementation properly validates both the existence and type of the context value.

client.go (1)

98-100: LGTM! Effectively prevents JWT request transport cycle

The implementation successfully breaks the potential infinite recursion by checking the auth context before attempting token retrieval.

auth.go (1)

288-288: LGTM! Consistent application of auth context

The auth context is consistently applied across all token retrieval methods, ensuring the solution works uniformly throughout the authentication flow.

Also applies to: 465-465, 519-519

Change-Id: Ia9ff6a11bdf31f14645b6d6db12dd05b305ce5ac
Copy link

codecov bot commented Jan 13, 2025

Codecov Report

Attention: Patch coverage is 55.55556% with 8 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
utils.go 58.33% 5 Missing ⚠️
client.go 0.00% 2 Missing and 1 partial ⚠️
Files with missing lines Coverage Δ
auth.go 78.55% <100.00%> (+0.05%) ⬆️
client.go 95.23% <0.00%> (-4.77%) ⬇️
utils.go 75.00% <58.33%> (-6.25%) ⬇️

... and 8 files with indirect coverage changes

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

🧹 Nitpick comments (3)
utils.go (3)

53-53: Use English comments for consistency

Replace the Chinese comment with its English equivalent: "Define custom type for context keys"


54-64: Add godoc comments for exported types and functions

Add documentation comments to improve code maintainability and help users understand the purpose of each component.

Apply these changes:

+// contextKey is a custom type for context keys to prevent collisions
 type contextKey string

 const (
+    // authContextKey is the key used to store authentication status in context
     authContextKey   = contextKey("auth_context")
+    // authContextValue represents an authenticated context
     authContextValue = "1"
 )

+// genAuthContext creates a new context with authentication information
 func genAuthContext(ctx context.Context) context.Context {
     return context.WithValue(ctx, authContextKey, authContextValue)
 }

56-60: Improve type safety for context values

Consider using a custom type for authContextValue to make it more type-safe and prevent accidental string comparisons.

Here's a suggested improvement:

+type authStatus string

 const (
     authContextKey   = contextKey("auth_context")
-    authContextValue = "1"
+    authContextValue = authStatus("authenticated")
 )
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a66f111 and 16b623d.

📒 Files selected for processing (1)
  • utils.go (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Test (1.22)

@chyroc chyroc added the bug Something isn't working label Jan 13, 2025
@chyroc
Copy link
Contributor

chyroc commented Jan 13, 2025

fix #9

Change-Id: I7f544f7588ff66d33bc6fa467277c371cb9bb074
@chyroc chyroc changed the title fix: jwt infinite recursion problem fix: Resolve infinite recursion in Auth API Jan 13, 2025
@chyroc chyroc merged commit 50d5c42 into coze-dev:main Jan 13, 2025
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants