Skip to content

Conversation

hanzeINGH
Copy link
Contributor

Change-Id: I96cda3ea6a200b85184177851af8b1e4ce27f21d

Change-Id: I96cda3ea6a200b85184177851af8b1e4ce27f21d
Copy link

coderabbitai bot commented Jan 23, 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 7 minutes and 17 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 37c1ddc and 4b113ee.

📒 Files selected for processing (1)
  • .github/workflows/ci.yml (1 hunks)

Walkthrough

This pull request represents a version increment for the Coze API Java SDK from version 0.2.1 to 0.2.2. The changes are consistent across multiple files, including the project's POM files, the OAuth client implementation, and an example authentication class. The version update is applied to the project's core artifacts, dependency references, and user agent versioning, ensuring a synchronized version across the project.

Changes

File Change Summary
api/pom.xml Version updated from 0.2.1 to 0.2.2
example/pom.xml Dependency coze-api version updated from 0.2.1 to 0.2.2
api/src/main/java/com/coze/openapi/service/auth/OAuthClient.java Added wwwURL field, initialized by replacing "api." in baseURL; updated _getOAuthURL method to use wwwURL
api/src/main/java/com/coze/openapi/service/utils/UserAgentInterceptor.java Updated VERSION constant from "0.2.1" to "0.2.2"
example/src/main/java/example/auth/WebOAuthExample.java Added "state" parameter to getOAuthURL method calls
example/src/main/java/example/auth/PKCEOAuthExample.java Updated second parameter of genOAuthURL method from "state" to "states"

Possibly related PRs

  • fix: Fix User Agent reporting #20: This PR updates the version number in the UserAgentInterceptor class from "0.1.6" to "0.2.2", which is directly related to the versioning changes in the main PR that updates the project version in api/pom.xml from 0.2.1 to 0.2.2.
  • feat: Create OAuth client from config & Bump version to 0.2.1 #29: This PR also updates the version number in the api/pom.xml file from 0.2.0 to 0.2.1, which is part of the same versioning scheme as the main PR's update from 0.2.1 to 0.2.2.

Suggested labels

bug

Poem

🐰 A version hop, a rabbit's delight,
From 0.2.1 to 0.2.2's bright height
Code dancing, URLs refined with care
A small increment beyond compare!
SDK leaps forward, version so neat 🚀


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.

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

codecov bot commented Jan 23, 2025

Codecov Report

Attention: Patch coverage is 42.85714% with 4 lines in your changes missing coverage. Please review.

Project coverage is 76.37%. Comparing base (966e49c) to head (4b113ee).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...ava/com/coze/openapi/service/auth/OAuthClient.java 42.85% 3 Missing and 1 partial ⚠️
@@             Coverage Diff              @@
##               main      #30      +/-   ##
============================================
- Coverage     76.57%   76.37%   -0.21%     
  Complexity      203      203              
============================================
  Files            41       41              
  Lines          1144     1147       +3     
  Branches         83       84       +1     
============================================
  Hits            876      876              
- Misses          210      212       +2     
- Partials         58       59       +1     
Flag Coverage Δ Complexity Δ
unittests 76.37% <42.85%> (-0.21%) 203.00 <0.00> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ Complexity Δ
...ze/openapi/service/utils/UserAgentInterceptor.java 81.25% <ø> (ø) 7.00 <0.00> (ø)
...ava/com/coze/openapi/service/auth/OAuthClient.java 63.63% <42.85%> (-1.84%) 22.00 <0.00> (ø)

... and 1 file with indirect coverage changes

@@ -54,6 +56,7 @@ protected OAuthClient(OAuthBuilder<?> builder) {
this.clientSecret = builder.clientSecret;
this.clientID = builder.clientID;
this.baseURL = builder.baseURL;
this.wwwURL = Strings.replace(baseURL, "api.", "www.");
Copy link
Contributor

Choose a reason for hiding this comment

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

如果入参指定了 www 域名就用入参,否则字符串替换

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 (2)
api/src/main/java/com/coze/openapi/service/auth/OAuthClient.java (1)

49-49: LGTM: Fixed OAuth URL construction using correct subdomain.

Good fix for using www subdomain instead of api subdomain for OAuth URLs. However, consider using a URL manipulation library for more robust URL handling.

Consider using java.net.URL for URL manipulation instead of string replacement:

-this.wwwURL = Strings.replace(baseURL, "api.", "www.");
+java.net.URL url = new java.net.URL(baseURL);
+this.wwwURL = new java.net.URL(url.getProtocol(), 
+    url.getHost().replace("api.", "www."), 
+    url.getPort(), 
+    url.getFile()).toString();

Also applies to: 59-59

example/src/main/java/example/auth/WebOAuthExample.java (1)

50-50: Security improvement: Added state parameter to OAuth flow

Good addition of the state parameter to prevent CSRF attacks. This follows OAuth 2.0 best practices by maintaining state between the request and callback.

However, using a hardcoded "state" value reduces its effectiveness.

Consider generating a random state parameter for each request:

-    String oauthURL = oauth.getOAuthURL(redirectURI, "state");
+    String state = java.util.UUID.randomUUID().toString();
+    String oauthURL = oauth.getOAuthURL(redirectURI, state);

-    oauthURL = oauth.getOAuthURL(redirectURI, "state", "workspaceID");
+    oauthURL = oauth.getOAuthURL(redirectURI, state, "workspaceID");

Also applies to: 56-56

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 966e49c and 8bc92ed.

📒 Files selected for processing (5)
  • api/pom.xml (1 hunks)
  • api/src/main/java/com/coze/openapi/service/auth/OAuthClient.java (4 hunks)
  • api/src/main/java/com/coze/openapi/service/utils/UserAgentInterceptor.java (1 hunks)
  • example/pom.xml (1 hunks)
  • example/src/main/java/example/auth/WebOAuthExample.java (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • api/pom.xml
  • api/src/main/java/com/coze/openapi/service/utils/UserAgentInterceptor.java
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test (Java 11 on Windows)
🔇 Additional comments (4)
example/src/main/java/example/auth/WebOAuthExample.java (1)

50-50: Good security practice: Added state parameter to OAuth flow!

Adding the state parameter is a security best practice that helps prevent CSRF attacks in OAuth flows. The state parameter should be a unique, non-guessable value that is validated when processing the callback.

Consider validating the state parameter in your callback handler. Here's a script to check if state validation is implemented:

Also applies to: 56-56

✅ Verification successful

Good security practice confirmed: State parameter correctly added to OAuth flow!

The state parameter is properly implemented in the OAuth URL generation. Since this is a client SDK, the actual validation of the state parameter should be implemented by applications using this library in their callback handlers.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for state parameter validation in callback handlers
rg -i "state.*equals|state.*match|validateState|verifyState" .

Length of output: 64


Script:

#!/bin/bash
# Search for OAuth callback handler implementations
rg -i "callback|redirect.*uri|oauth.*callback" -A 5 .

# Also search for specific endpoint mappings that might handle OAuth callbacks
ast-grep --pattern 'class $_ {
  $$$
  @$_Mapping($$$"/callback"$$$)
  $$$
}'

Length of output: 49537

api/src/main/java/com/coze/openapi/service/auth/OAuthClient.java (2)

127-127: LGTM: Consistent use of wwwURL for OAuth endpoints.

The OAuth URL construction now correctly uses the www subdomain for both regular and workspace-specific authorization endpoints.

Also applies to: 129-129


127-127: Approve URL endpoint changes

Good change to use wwwURL for OAuth endpoints, ensuring the correct domain is used for the authorization flow.

Also applies to: 129-129

example/pom.xml (1)

19-19: LGTM: Version bump for bug fix.

Appropriate version increment (0.2.1 → 0.2.2) following semantic versioning for a bug fix.

@@ -45,6 +46,7 @@ public abstract class OAuthClient {
protected final String clientSecret;
protected final String clientID;
protected final String baseURL;
protected final String wwwURL;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Validate wwwURL construction

While the URL domain separation is correct, the current implementation using simple string replacement could be fragile.

Consider adding validation and using URL parsing:

-    this.wwwURL = Strings.replace(baseURL, "api.", "www.");
+    try {
+        java.net.URL url = new java.net.URL(baseURL);
+        String host = url.getHost().replace("api.", "www.");
+        this.wwwURL = new java.net.URL(url.getProtocol(), host, url.getPort(), "").toString();
+    } catch (java.net.MalformedURLException e) {
+        throw new IllegalArgumentException("Invalid base URL: " + baseURL, e);
+    }

Also applies to: 59-59

Change-Id: I5fdea142e7f80c43ea9e78047ff0d1e1e38ef65a
fix code format

Change-Id: I22bd59dcadd3777eb6ba3eb37ff8a739c469e751
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

♻️ Duplicate comments (1)
api/src/main/java/com/coze/openapi/service/auth/OAuthClient.java (1)

59-63: ⚠️ Potential issue

Fix code formatting and improve URL handling.

  1. Fix the formatting violation:
-    }else {
+    } else {
  1. The current implementation using simple string replacement could be fragile. Consider using URL parsing:
-    if (builder.wwwURL != null) {
-      this.wwwURL = builder.wwwURL;
-    } else {
-      this.wwwURL = Strings.replace(baseURL, "api.", "www.");
-    }
+    if (builder.wwwURL != null) {
+      validateURL(builder.wwwURL);
+      this.wwwURL = builder.wwwURL;
+    } else {
+      try {
+        java.net.URL url = new java.net.URL(baseURL);
+        String host = url.getHost().replace("api.", "www.");
+        this.wwwURL = new java.net.URL(url.getProtocol(), host, url.getPort(), "").toString();
+      } catch (java.net.MalformedURLException e) {
+        throw new IllegalArgumentException("Invalid base URL: " + baseURL, e);
+      }
+    }
🧹 Nitpick comments (2)
api/src/main/java/com/coze/openapi/service/auth/OAuthClient.java (2)

131-133: Improve URL path handling.

The current URL construction using string concatenation could lead to malformed URLs if wwwURL ends with a slash. Consider using java.net.URL or a URL builder:

-    String uri = wwwURL + "/api/permission/oauth2/authorize";
-    if (workspaceID != null) {
-      uri = wwwURL + String.format("/api/permission/oauth2/workspace_id/%s/authorize", workspaceID);
-    }
+    String path = workspaceID != null
+        ? String.format("/api/permission/oauth2/workspace_id/%s/authorize", workspaceID)
+        : "/api/permission/oauth2/authorize";
+    try {
+        java.net.URL baseUrl = new java.net.URL(wwwURL);
+        uri = new java.net.URL(baseUrl, path).toString();
+    } catch (java.net.MalformedURLException e) {
+        throw new IllegalArgumentException("Failed to construct OAuth URL", e);
+    }

260-260: Add URL validation in the builder.

Consider adding validation in the wwwURL setter to fail fast if an invalid URL is provided:

     public T wwwURL(String wwwURL) {
+      try {
+        new java.net.URL(wwwURL);
+      } catch (java.net.MalformedURLException e) {
+        throw new IllegalArgumentException("Invalid www URL: " + wwwURL, e);
+      }
       this.wwwURL = wwwURL;
       return self();
     }

Also applies to: 286-290

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8bc92ed and d87e548.

📒 Files selected for processing (1)
  • api/src/main/java/com/coze/openapi/service/auth/OAuthClient.java (6 hunks)
🧰 Additional context used
🪛 GitHub Actions: CI
api/src/main/java/com/coze/openapi/service/auth/OAuthClient.java

[error] 58-58: Code formatting violation: Incorrect spacing around 'else' keyword. Found 'else{' but expected 'else {'.

🔇 Additional comments (1)
api/src/main/java/com/coze/openapi/service/auth/OAuthClient.java (1)

49-49: LGTM: Field declaration is appropriate.

The new wwwURL field follows the class's field declaration patterns with proper access level and immutability.

update

Change-Id: I7bcbf5ac5d04881da5ed121c34f6c908759d19d2
Change-Id: I4c409c46bb5418912e1cb8ed5403a73e5b364b58
Change-Id: I34d5994b0e6d952139acd854dcb6f4f94a996075
Change-Id: I3f8ffdc919f51f45ade99eca622460574905505f
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: 2

♻️ Duplicate comments (1)
api/src/main/java/com/coze/openapi/service/auth/OAuthClient.java (1)

58-62: 🛠️ Refactor suggestion

Use URL parsing for safer domain conversion.

The current string replacement approach could be fragile. Consider using proper URL parsing for safer domain conversion.

     if (builder.wwwURL != null) {
       this.wwwURL = builder.wwwURL;
     } else {
-      this.wwwURL = builder.baseURL.replace("api.", "www.");
+      try {
+          java.net.URL url = new java.net.URL(builder.baseURL);
+          String host = url.getHost().replace("api.", "www.");
+          this.wwwURL = new java.net.URL(url.getProtocol(), host, url.getPort(), "").toString();
+      } catch (java.net.MalformedURLException e) {
+          throw new IllegalArgumentException("Invalid base URL: " + builder.baseURL, e);
+      }
     }
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 59-59: api/src/main/java/com/coze/openapi/service/auth/OAuthClient.java#L59
Added line #L59 was not covered by tests

🧹 Nitpick comments (1)
api/src/main/java/com/coze/openapi/service/auth/OAuthClient.java (1)

130-132: Improve URL path handling.

The current URL construction could lead to malformed URLs if wwwURL ends with a slash. Consider using java.net.URL or a URL builder to properly handle path concatenation.

-    String uri = wwwURL + "/api/permission/oauth2/authorize";
+    String baseUri = wwwURL.endsWith("/") ? wwwURL.substring(0, wwwURL.length() - 1) : wwwURL;
+    String uri = baseUri + "/api/permission/oauth2/authorize";
     if (workspaceID != null) {
-      uri = wwwURL + String.format("/api/permission/oauth2/workspace_id/%s/authorize", workspaceID);
+      uri = baseUri + String.format("/api/permission/oauth2/workspace_id/%s/authorize", workspaceID);
     }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d87e548 and 37c1ddc.

📒 Files selected for processing (2)
  • api/src/main/java/com/coze/openapi/service/auth/OAuthClient.java (5 hunks)
  • example/src/main/java/example/auth/PKCEOAuthExample.java (1 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
api/src/main/java/com/coze/openapi/service/auth/OAuthClient.java

[warning] 59-59: api/src/main/java/com/coze/openapi/service/auth/OAuthClient.java#L59
Added line #L59 was not covered by tests


[warning] 286-287: api/src/main/java/com/coze/openapi/service/auth/OAuthClient.java#L286-L287
Added lines #L286 - L287 were not covered by tests

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: test (Java 11 on Windows)
🔇 Additional comments (1)
api/src/main/java/com/coze/openapi/service/auth/OAuthClient.java (1)

48-48: LGTM: Field declaration follows class conventions.

The new wwwURL field is appropriately declared with matching protection level and immutability.

@@ -45,7 +45,7 @@ public static void main(String[] args) {
to select the code_challenge_method.
* */
GetPKCEAuthURLResp oauthURL =
oauth.genOAuthURL(redirectURI, "state", PKCEOAuthClient.CodeChallengeMethod.S256);
oauth.genOAuthURL(redirectURI, "states", PKCEOAuthClient.CodeChallengeMethod.S256);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical: Incorrect OAuth state parameter name breaks CSRF protection

The state parameter has been changed from "state" to "states", which deviates from the OAuth 2.0 specification. This is incorrect and could break the CSRF protection mechanism, as OAuth providers expect the standard parameter name "state".

Apply this fix to align with the OAuth 2.0 specification:

-        oauth.genOAuthURL(redirectURI, "states", PKCEOAuthClient.CodeChallengeMethod.S256);
+        oauth.genOAuthURL(redirectURI, "state", PKCEOAuthClient.CodeChallengeMethod.S256);

This is also consistent with the example shown in the comments at line 56.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
oauth.genOAuthURL(redirectURI, "states", PKCEOAuthClient.CodeChallengeMethod.S256);
oauth.genOAuthURL(redirectURI, "state", PKCEOAuthClient.CodeChallengeMethod.S256);

@@ -251,6 +256,7 @@
protected String clientID;
protected String clientSecret;
protected String baseURL;
protected String wwwURL;
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Add test coverage for wwwURL builder methods

The codebase analysis confirms that wwwURL builder functionality lacks test coverage. Existing OAuth client tests demonstrate thorough testing patterns for other builder properties, but wwwURL-specific tests are missing. Please add test cases to verify:

  • Setting custom wwwURL
  • Fallback to baseURL conversion
  • Invalid URL handling
🔗 Analysis chain

Add test coverage for wwwURL builder methods.

The new builder methods for wwwURL are not covered by tests. Please add test cases to verify:

  • Setting custom wwwURL
  • Fallback to baseURL conversion
  • Invalid URL handling

Also applies to: 285-289

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for existing test coverage of wwwURL functionality

# Search for test files that might contain wwwURL-related tests
echo "Searching for existing test files..."
fd -e java -e kt test

# Search for wwwURL usage in test files
echo -e "\nSearching for wwwURL test coverage..."
rg -l "wwwURL" $(fd -e java -e kt test)

Length of output: 4911


Script:

#!/bin/bash
# Check for builder pattern usage in auth tests
echo "Checking builder usage in auth tests..."
rg -A 5 -B 5 "\.builder\(\)" api/src/test/java/com/coze/openapi/service/auth/

# Check for any indirect wwwURL testing through setters
echo -e "\nChecking for indirect wwwURL testing..."
rg -A 5 -B 5 "\.setWww" api/src/test/java/com/coze/openapi/service/auth/

Length of output: 338


Script:

#!/bin/bash
# Check test structure and initialization patterns
echo "Analyzing OAuthClient test implementations..."
rg -l "OAuthClient" api/src/test/java/com/coze/openapi/service/auth/ | xargs cat

# Broader search for builder-related patterns
echo -e "\nChecking for builder patterns..."
rg "new\s+.*Builder|builder\s*\(\)" api/src/test/java/com/coze/openapi/service/auth/

Length of output: 30942

@chyroc chyroc added the bug Something isn't working label Jan 23, 2025
Change-Id: Iba86b9bd15c662abfae7759abd2db4794bbba660
@chyroc chyroc changed the title fix: callback url fix: Update OAuth authentication URL host to www domain Jan 23, 2025
@chyroc chyroc changed the title fix: Update OAuth authentication URL host to www domain fix: Update OAuth authentication URL host to www domain & Bump version to 0.2.2 Jan 23, 2025
@chyroc chyroc merged commit 8fa97f2 into coze-dev:main Jan 23, 2025
8 of 11 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