Skip to content

chore: Bust OAuth2 client cache for spring boot 3.3#36660

Merged
nidhi-nair merged 1 commit intoreleasefrom
chore/ouath-cache-key
Oct 2, 2024
Merged

chore: Bust OAuth2 client cache for spring boot 3.3#36660
nidhi-nair merged 1 commit intoreleasefrom
chore/ouath-cache-key

Conversation

@nidhi-nair
Copy link
Contributor

@nidhi-nair nidhi-nair commented Oct 2, 2024

Description

Tip

Add a TL;DR when the description is longer than 500 words or extremely technical (helps the content, marketing, and DevRel team).

Please also include relevant motivation and context. List any dependencies that are required for this change. Add links to Notion, Figma or any other documents that might be relevant to the PR.

Fixes #Issue Number
or
Fixes Issue URL

Warning

If no issue exists, please create an issue first, and check with the maintainers if the issue is valid.

Automation

/ok-to-test tags=""

🔍 Cypress test results

Caution

If you modify the content in this section, you are likely to disrupt the CI result for your PR.

Communication

Should the DevRel and Marketing teams inform users about this change?

  • Yes
  • No

Summary by CodeRabbit

  • New Features

    • Enhanced serialization and deserialization of OAuth2 client data for improved handling.
    • Introduced a migration process to clear outdated OAuth2 session data from Redis.
  • Bug Fixes

    • Corrected type handling for OAuth2AuthorizedClient during data processing.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 2, 2024

Walkthrough

The changes introduced in this pull request involve modifications to the serialization and deserialization logic within the JSONSessionRedisSerializer class in RedisConfig.java, specifically adjusting type checks for OAuth2 client data. Additionally, a new migration class Migration063CacheBustSpringBoot3_3.java has been added to manage Redis session data for Spring Boot 3.3, including functionality to clear specific OAuth2 authorized client keys from Redis.

Changes

File Change Summary
app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/RedisConfig.java Updated serialization and deserialization logic in JSONSessionRedisSerializer for OAuth2 client types.
app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration063CacheBustSpringBoot3_3.java Added new migration class to clear OAuth2 session data from Redis, with methods for execution and rollback.

Suggested labels

skip-changelog, ok-to-test

Suggested reviewers

  • sharat87
  • mohanarpit

🎉 In the realm of code, changes abound,
OAuth2 clients, new logic found.
A migration to clear, with scripts so neat,
Redis sessions, now tidy and sweet!
So let’s celebrate, with joy and cheer,
For cleaner code brings us all near! 🌟


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 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.

@github-actions github-actions bot added the skip-changelog Adding this label to a PR prevents it from being listed in the changelog label Oct 2, 2024
Copy link
Contributor

@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: 4

🧹 Outside diff range and nitpick comments (1)
app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration063CacheBustSpringBoot3_3.java (1)

27-37: Add Javadoc comments to public methods

For clarity and maintainability, it's helpful to document your public methods using Javadoc comments. This provides future developers with information about the method's purpose and how to use it.

/**
 * Clears Redis session keys that contain OAuth2 authorized client information.
 *
 * @param reactiveRedisOperations the ReactiveRedisOperations instance used to interact with Redis
 */
public static void doClearRedisOAuth2AuthClientKeys(
        ReactiveRedisOperations<String, String> reactiveRedisOperations) {
    // method implementation
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 688324e and 47f51fc.

📒 Files selected for processing (2)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/RedisConfig.java (1 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/migrations/db/ce/Migration063CacheBustSpringBoot3_3.java (1 hunks)
🔇 Additional comments (2)
app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/RedisConfig.java (2)

Line range hint 1-365: Excellent work, class! Let's summarize what we've learned today.

We've made significant improvements to our Redis configuration, particularly in how we handle OAuth2 client data. Here's a quick recap:

  1. We've updated our serialization process to work with OAuth2AuthorizedClient instead of OAuth2AuthorizedClientDTO.
  2. Our deserialization process now converts data back to OAuth2AuthorizedClient, maintaining consistency.
  3. These changes align our code better with Spring Security standards and improve our overall data handling.

Remember, these changes might require updates in other parts of our codebase. It's crucial to ensure that all areas of our application are consistent with these new changes.

For homework, I want you all to review any code that interacts with OAuth2 client data and make sure it's compatible with these updates. Keep up the good work!


Line range hint 280-289: Now, class, let's examine the changes in our deserialization process!

We've updated our deserialize method to convert OAuth2AuthorizedClientDTO back into OAuth2AuthorizedClient. This is a crucial step to maintain consistency with our serialization changes.

Here's what you need to remember:

  1. This change ensures that we're working with OAuth2AuthorizedClient throughout our application.
  2. It completes the cycle of serialization and deserialization, maintaining data integrity.
  3. We need to be vigilant about any code that might still be expecting OAuth2AuthorizedClientDTO.

As good programmers, we always ensure our data flows smoothly through our application. This change helps us achieve that goal!

Let's double-check our work with this quick test:

#!/bin/bash
# Search for any remaining uses of makeOAuth2AuthorizedClient in the codebase
rg "makeOAuth2AuthorizedClient" --type java

Comment on lines +27 to +37
public static void doClearRedisOAuth2AuthClientKeys(
ReactiveRedisOperations<String, String> reactiveRedisOperations) {
final String authorizedClientsKey =
"sessionAttr:org.springframework.security.oauth2.client.web.server.WebSessionServerOAuth2AuthorizedClientRepository.AUTHORIZED_CLIENTS";
final String script =
"for _,k in ipairs(redis.call('keys','spring:session:sessions:*')) do local fieldExists = redis.call('hexists', k, '"
+ authorizedClientsKey + "'); if fieldExists == 1 then redis.call('del', k) end end";
final Flux<Object> flushdb = reactiveRedisOperations.execute(RedisScript.of(script));

flushdb.blockLast();
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid blocking calls in reactive streams

Dear student, it's important to remember that using blocking calls like blockLast() in a reactive pipeline can undermine the benefits of reactive programming. Blocking operations can lead to performance bottlenecks and thread starvation.

To maintain a non-blocking, asynchronous flow, consider refactoring the code to use reactive operators and subscribing to the sequence without blocking. Here's how you might modify the code:

reactiveRedisOperations.execute(RedisScript.of(script))
    .doOnError(error -> log.error("Error executing Redis script", error))
    .doOnComplete(() -> log.info("Successfully cleared OAuth2 client keys from Redis"))
    .subscribe();

Comment on lines +31 to +33
final String script =
"for _,k in ipairs(redis.call('keys','spring:session:sessions:*')) do local fieldExists = redis.call('hexists', k, '"
+ authorizedClientsKey + "'); if fieldExists == 1 then redis.call('del', k) end end";
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid using KEYS command in Redis scripts

Remember that using the KEYS command in Redis can be problematic in production environments. It can block the Redis server if there are many keys, leading to performance issues.

Instead, consider using the SCAN command, which is non-blocking and more suitable for iterating over keys in a large keyspace. Here's an example of how you can modify the script:

final String script =
    "local cursor = '0' " +
    "repeat " +
    "  local result = redis.call('SCAN', cursor, 'MATCH', 'spring:session:sessions:*') " +
    "  cursor = result[1] " +
    "  local keys = result[2] " +
    "  for _,k in ipairs(keys) do " +
    "    local fieldExists = redis.call('hexists', k, '" + authorizedClientsKey + "') " +
    "    if fieldExists == 1 then " +
    "      redis.call('del', k) " +
    "    end " +
    "  end " +
    "until cursor == '0'";

Comment on lines +23 to +25
public void execute() {
doClearRedisOAuth2AuthClientKeys(reactiveRedisOperations);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add exception handling in the execute method

It's good practice to handle exceptions to make your code more robust. In the execute() method, consider adding a try-catch block to catch any exceptions that may occur during the Redis operations. This way, you can log the error and handle it appropriately.

public void execute() {
    try {
        doClearRedisOAuth2AuthClientKeys(reactiveRedisOperations);
    } catch (Exception e) {
        log.error("An error occurred while clearing OAuth2 client keys from Redis", e);
        // Optionally, handle the exception or rethrow it
    }
}

@github-actions
Copy link

github-actions bot commented Oct 2, 2024

Failed server tests

  • com.external.plugins.MySqlPluginTest#testDatasourceDestroy
  • com.external.plugins.MySqlPluginTest#testDuplicateColumnNames
  • com.external.plugins.MySqlPluginTest#testExecuteDataTypesExtensive
  • com.external.plugins.MySqlPluginTest#testExecuteDescTableCmd
  • com.external.plugins.MySqlPluginTest#testExecuteDescribeTableCmd
  • com.external.plugins.MySqlPluginTest#testExecuteWithLongRunningQuery
  • com.external.plugins.MySqlPluginTest#testStructure

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

Labels

skip-changelog Adding this label to a PR prevents it from being listed in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants