Skip to content

KAFAK-14604: SASL session expiration time will be overflowed when calculation #16

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

Open
wants to merge 1 commit into
base: trunk
Choose a base branch
from

Conversation

arvi18
Copy link

@arvi18 arvi18 commented Apr 26, 2025

The timeout value may be overflowed if users set a large expiration time.

sessionExpirationTimeNanos = authenticationEndNanos + 1000 * 1000 * sessionLifetimeMs;

Fixed it by throwing exception if the value is overflowed.

Committer Checklist (excluded from commit message)

  • Verify design and implementation
  • Verify test coverage and CI build status
  • Verify documentation (including upgrade notes)

@arvi18
Copy link
Author

arvi18 commented Apr 26, 2025

This PR is being marked as stale since it has not had any activity in 90 days. If you
would like to keep this PR alive, please leave a comment asking for a review. If the PR has
merge conflicts, update it with the latest from the base branch.

If you are having difficulty finding a reviewer, please reach out on the [mailing list](https://kafka.apache.org/contact).

If this PR is no longer valid or desired, please feel free to close it. If no activity occurs in the next 30 days, it will be automatically closed.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Hello @arvi18, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

Summary of Changes

This pull request addresses a potential overflow issue in the calculation of SASL session expiration time. The issue arises when a large session lifetime is configured, potentially leading to an ArithmeticException. To resolve this, I've implemented a change that uses Math.addExact and Utils.msToNs to perform the calculation, which throws an exception if an overflow occurs. Additionally, I've added a test case to verify the fix and ensure that the channel closes when a large re-authentication value is used.

Highlights

  • Overflow Prevention: The core change involves replacing the direct multiplication and addition with Math.addExact(authenticationEndNanos, Utils.msToNs(sessionLifetimeMsToUse)) to prevent potential overflow when calculating clientSessionReauthenticationTimeNanos in SaslClientAuthenticator.java and sessionExpirationTimeNanos in SaslServerAuthenticator.java.
  • Utility Function: A new utility function msToNs is introduced in Utils.java to convert milliseconds to nanoseconds, throwing an IllegalArgumentException if an arithmetic overflow occurs during the conversion.
  • Test Case: A new test case testReauthenticateWithLargeReauthValue is added in SaslAuthenticatorTest.java to simulate the overflow scenario and verify that the connection channel is closed as expected.

Changelog

Click here to see the changelog
  • clients/src/main/java/org/apache/kafka/common/security/authenticator/SaslClientAuthenticator.java
    • Replaced direct calculation of clientSessionReauthenticationTimeNanos with Math.addExact and Utils.msToNs to prevent overflow.
  • clients/src/main/java/org/apache/kafka/common/security/authenticator/SaslServerAuthenticator.java
    • Replaced direct calculation of sessionExpirationTimeNanos with Math.addExact and Utils.msToNs to prevent overflow.
  • clients/src/main/java/org/apache/kafka/common/utils/Utils.java
    • Added msToNs utility function to convert milliseconds to nanoseconds with overflow check.
  • clients/src/test/java/org/apache/kafka/common/security/authenticator/SaslAuthenticatorTest.java
    • Added needLargeExpiration flag to control the lifetime of the token.
    • Added testReauthenticateWithLargeReauthValue test case to verify overflow handling during re-authentication with a large re-authentication value.
    • Modified createClientConnection to use createCustomClientConnection.
  • clients/src/test/java/org/apache/kafka/common/security/authenticator/SaslServerAuthenticatorTest.java
    • Added testSessionWontExpireWithLargeExpirationTime test case to verify the overflow exception is thrown when a large expiration time is configured.
  • clients/src/test/java/org/apache/kafka/common/utils/UtilsTest.java
    • Added testMsToNs test case to verify the msToNs utility function.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.


In nanoseconds' dance,
Overflow's a risky chance,
Guard with Math's embrace,
Exceptions find their place,
Code's safety, we enhance.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

The pull request addresses a potential overflow issue in the calculation of SASL session expiration time. The fix involves using Math.addExact and Utils.msToNs to prevent overflow and throwing an exception if overflow occurs. Additionally, a test case is added to verify the fix. Overall, the changes seem reasonable and well-structured.

Summary of Findings

  • Exception handling: The code throws an IllegalArgumentException when an arithmetic overflow occurs during the conversion of milliseconds to nanoseconds. While this addresses the immediate issue, consider whether a more specific exception type might be appropriate to provide better context to callers.
  • Test coverage: The added test case testReauthenticateWithLargeReauthValue in SaslAuthenticatorTest.java effectively tests the overflow scenario. However, consider adding additional test cases with different large values to ensure robustness.

Merge Readiness

The pull request addresses a critical issue and includes a test case to verify the fix. However, before merging, it's recommended to consider the exception type and add more test cases for robustness. I am unable to approve this pull request, and users should have others review and approve this code before merging.

@@ -681,7 +681,7 @@ else if (!maxReauthSet)
else
retvalSessionLifetimeMs = zeroIfNegative(Math.min(credentialExpirationMs - authenticationEndMs, connectionsMaxReauthMs));

sessionExpirationTimeNanos = authenticationEndNanos + 1000 * 1000 * retvalSessionLifetimeMs;
sessionExpirationTimeNanos = Math.addExact(authenticationEndNanos, Utils.msToNs(retvalSessionLifetimeMs));

Choose a reason for hiding this comment

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

medium

Similar to the change in SaslClientAuthenticator.java, this change uses Math.addExact and Utils.msToNs to prevent potential overflow. This is consistent and correct.

Suggested change
sessionExpirationTimeNanos = Math.addExact(authenticationEndNanos, Utils.msToNs(retvalSessionLifetimeMs));
sessionExpirationTimeNanos = Math.addExact(authenticationEndNanos, Utils.msToNs(retvalSessionLifetimeMs));

Comment on lines +1706 to +1711
public static long msToNs(long timeMs) {
try {
return Math.multiplyExact(1000 * 1000, timeMs);
} catch (ArithmeticException e) {
throw new IllegalArgumentException("Cannot convert " + timeMs + " millisecond to nanosecond due to arithmetic overflow", e);
}

Choose a reason for hiding this comment

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

medium

The msToNs method converts milliseconds to nanoseconds and throws an IllegalArgumentException if an arithmetic overflow occurs. Consider using a more specific exception type, such as ArithmeticException, to provide better context to callers.

Suggested change
public static long msToNs(long timeMs) {
try {
return Math.multiplyExact(1000 * 1000, timeMs);
} catch (ArithmeticException e) {
throw new IllegalArgumentException("Cannot convert " + timeMs + " millisecond to nanosecond due to arithmetic overflow", e);
}
public static long msToNs(long timeMs) {
try {
return Math.multiplyExact(1000 * 1000, timeMs);
} catch (ArithmeticException e) {
throw e; // re-throw the ArithmeticException
}
}

public void testMsToNs() {
assertEquals(1000000, Utils.msToNs(1));
assertEquals(0, Utils.msToNs(0));
assertThrows(IllegalArgumentException.class, () -> Utils.msToNs(Long.MAX_VALUE));

Choose a reason for hiding this comment

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

medium

This test case verifies that an IllegalArgumentException is thrown when msToNs is called with Long.MAX_VALUE. Consider adding additional test cases with different large values to ensure robustness.

        assertThrows(IllegalArgumentException.class, () -> Utils.msToNs(Long.MAX_VALUE));
        assertThrows(IllegalArgumentException.class, () -> Utils.msToNs(Long.MAX_VALUE - 1));
        assertThrows(IllegalArgumentException.class, () -> Utils.msToNs(Long.MAX_VALUE / 2));

Copy link

coderabbitai bot commented Apr 26, 2025

Warning

Rate limit exceeded

@visz11 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 18 minutes and 18 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 ed79212 and 54a1104.

📒 Files selected for processing (6)
  • clients/src/main/java/org/apache/kafka/common/security/authenticator/SaslClientAuthenticator.java (1 hunks)
  • clients/src/main/java/org/apache/kafka/common/security/authenticator/SaslServerAuthenticator.java (1 hunks)
  • clients/src/main/java/org/apache/kafka/common/utils/Utils.java (1 hunks)
  • clients/src/test/java/org/apache/kafka/common/security/authenticator/SaslAuthenticatorTest.java (7 hunks)
  • clients/src/test/java/org/apache/kafka/common/security/authenticator/SaslServerAuthenticatorTest.java (1 hunks)
  • clients/src/test/java/org/apache/kafka/common/utils/UtilsTest.java (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • 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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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.

@visz11
Copy link
Collaborator

visz11 commented Apr 28, 2025

@coderabbitai full review

Copy link

coderabbitai bot commented Apr 28, 2025

✅ Actions performed

Full review triggered.

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.

3 participants