Skip to content

Conversation

@haicoder
Copy link
Contributor

@haicoder haicoder commented Aug 15, 2025

Summary by CodeRabbit

  • New Features
    • Added a public API to generate JWTs directly from callers, with a single options object for inputs.
    • Options can include TTL plus optional session name and session context to be embedded in the token when provided.
    • Signing, claims (iss, aud, iat, exp, jti) and existing behavior remain compatible with current integrations.

@CLAassistant
Copy link

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.


chenchang.cc seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.

@coderabbitai
Copy link

coderabbitai bot commented Aug 15, 2025

Walkthrough

Replaced a private JWT helper with a new public API: GenerateJWT(ctx context.Context, opts *GenerateJWTReq), introduced GenerateJWTReq to carry TTL, SessionName, and SessionContext, and updated GetAccessToken to construct and call the new API. JWT claims and signing behavior remain the same.

Changes

Cohort / File(s) Summary
JWT API and request struct
auth.go
Replaced private generateJWT(ttl int, sessionName *string, sessionContext *SessionContext) (string, error) with exported GenerateJWT(ctx context.Context, opts *GenerateJWTReq) (string, error) and added GenerateJWTReq type (TTL, SessionName, SessionContext). Updated GetAccessToken to build GenerateJWTReq and call GenerateJWT. Claims include iss, aud, iat, exp, jti, and optionally session_name and session_context; JWT built with RS256 and signed with the private key.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant JWTOAuthClient
    participant Signer

    Caller->>JWTOAuthClient: GetAccessToken(ctx)
    JWTOAuthClient->>JWTOAuthClient: build GenerateJWTReq{TTL, SessionName, SessionContext}
    JWTOAuthClient->>JWTOAuthClient: GenerateJWT(ctx, opts)
    JWTOAuthClient->>Signer: create claims (iss,aud,iat,exp,jti[,session_*]) + header(kid,alg)
    Signer-->>JWTOAuthClient: signed JWT string
    JWTOAuthClient-->>Caller: return JWT
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Possibly related PRs

Suggested labels

feature

Poem

I nibbled code in soft moonlight,
A helper grew and took its flight.
GenerateJWT now hops outside,
With session crumbs tucked safe inside.
Keys gleam, tokens bound and bright. 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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: 0

🧹 Nitpick comments (2)
auth.go (2)

676-676: Add GoDoc for the newly exported method to satisfy lint and improve discoverability

Exported identifiers should have a comment starting with the identifier’s name. This also helps consumers understand the method’s purpose.

Apply:

-func (c *JWTOAuthClient) GenerateJWT(ttl int, sessionName *string, sessionContext *SessionContext) (string, error) {
+// GenerateJWT builds and signs an RS256 JWT for the OAuth JWT-bearer grant.
+// ttl is in seconds; sessionName and sessionContext are optional claims.
+func (c *JWTOAuthClient) GenerateJWT(ttl int, sessionName *string, sessionContext *SessionContext) (string, error) {

Optionally, for a smoother migration in case any in-package references remain, add a private shim (non-diff snippet shown since it’s outside this hunk):

// Deprecated: use GenerateJWT instead. Will be removed in a future release.
func (c *JWTOAuthClient) generateJWT(ttl int, sessionName *string, sessionContext *SessionContext) (string, error) {
	return c.GenerateJWT(ttl, sessionName, sessionContext)
}

If you want, I can open a follow-up PR to add the doc comment and deprecation shim.


703-707: Nit: setting "alg" header is redundant; jwt library sets it from the signing method

jwt.NewWithClaims(jwt.SigningMethodRS256, ...) already sets alg to RS256. Manually setting it increases the chance of drift if the signing method ever changes.

Apply:

 token.Header["kid"] = c.publicKey
 token.Header["typ"] = "JWT"
-token.Header["alg"] = "RS256"
📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between adfc6e9 and c75a608.

📒 Files selected for processing (1)
  • auth.go (2 hunks)
🔇 Additional comments (1)
auth.go (1)

656-656: GenerateJWT call-site updated — no remaining references to old private generateJWT

Quick verification: searching the repo found no occurrences of generateJWT( and shows the public usage/definition only.

  • auth.go:656 — call site: jwtCode, err := c.GenerateJWT(ttl, opts.SessionName, opts.SessionContext)
  • auth.go:676 — definition: func (c *JWTOAuthClient) GenerateJWT(...)

@chyroc chyroc added the feature label Aug 15, 2025
@chyroc chyroc changed the title Export JWTOAuthClient.generateJWT method to public feat: Export GenerateJWT method to public Aug 15, 2025
@chyroc chyroc merged commit 7a23df3 into coze-dev:main Aug 15, 2025
10 of 13 checks passed
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: 0

🔭 Outside diff range comments (1)
auth.go (1)

688-731: Fix: avoid nil deref, prevent zero-expiry tokens, and resolve unused ctx compile error.

  • Public GenerateJWT dereferences opts without a nil check, which will panic if callers pass nil.
  • Using opts.TTL directly allows 0 or negative TTL, yielding tokens that are immediately expired.
  • The ctx parameter is unused, which is a compile-time error in Go.

Apply this minimal, backward-compatible fix:

 func (c *JWTOAuthClient) GenerateJWT(ctx context.Context, opts *GenerateJWTReq) (string, error) {
-	now := time.Now()
+	// Reserved for future tracing/logging; avoid unused param compile error.
+	_ = ctx
+	now := time.Now()
 	jti, err := generateRandomString(16)
 	if err != nil {
 		return "", err
 	}
 
-	ttl := opts.TTL
-	sessionName := opts.SessionName
-	sessionContext := opts.SessionContext
+	// Derive effective TTL and optional session info, with sensible defaults.
+	ttl := c.ttl
+	var sessionName *string
+	var sessionContext *SessionContext
+	if opts != nil {
+		if opts.TTL > 0 {
+			ttl = opts.TTL
+		}
+		sessionName = opts.SessionName
+		sessionContext = opts.SessionContext
+	}
 
 	// Build claims
 	claims := jwt.MapClaims{
 		"iss": c.clientID,
 		"aud": c.hostName,
 		"iat": now.Unix(),
 		"exp": now.Add(time.Duration(ttl) * time.Second).Unix(),
 		"jti": jti,
 	}

Optional follow-up: consider returning an error for invalid TTL values instead of silently falling back, if you prefer stricter input validation.

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

681-687: Clarify TTL semantics in the new public request type.

Since callers may omit or pass non-positive TTLs, document that such values fall back to the client default. This avoids confusion and better communicates intended behavior.

 type GenerateJWTReq struct {
-	TTL            int             `json:"ttl,omitempty"`             // Token validity period (in seconds)
+	TTL            int             `json:"ttl,omitempty"`             // Token validity period in seconds; <= 0 uses client default
 	SessionName    *string         `json:"session_name,omitempty"`    // Session name
 	SessionContext *SessionContext `json:"session_context,omitempty"` // SessionContext
 }
📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between c75a608 and cd1bd14.

📒 Files selected for processing (1)
  • auth.go (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Test success
🔇 Additional comments (1)
auth.go (1)

656-662: Good refactor: centralize JWT generation via exported API.

Calling the new exported GenerateJWT with a clearly constructed GenerateJWTReq keeps GetAccessToken lean and improves reuse. No issues here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants