Skip to content
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

fix: NPE while creating a policies copy #36172

Merged
merged 3 commits into from
Sep 9, 2024
Merged

fix: NPE while creating a policies copy #36172

merged 3 commits into from
Sep 9, 2024

Conversation

abhvsn
Copy link
Contributor

@abhvsn abhvsn commented Sep 7, 2024

Description

PR to handle the empty collection and null values for policies. We expect web should never end up in this state but we have received enough evidences that because of broken functionality in GAC we may end up in this scenario. One such example is #36063

/test all

🔍 Cypress test results

Caution

🔴 🔴 🔴 Some tests have failed.
Workflow run: https://github.com/appsmithorg/appsmith/actions/runs/10767073729
Commit: e225d54
Cypress dashboard.
Tags: @tag.All
Spec:
The following are new failures, please fix them before merging the PR:

  1. cypress/e2e/Regression/ClientSide/Debugger/Widget_property_navigation_spec.ts
  2. cypress/e2e/Regression/ClientSide/OneClickBinding/PropertyControl_spec.ts
List of identified flaky tests.
Mon, 09 Sep 2024 07:01:41 UTC

Communication

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

  • Yes
  • No

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of user permissions to prevent potential errors related to null values in policies.
    • Enhanced robustness in policy management methods to avoid null-related errors when retrieving existing policies.
  • Tests
    • Added unit tests for user permissions handling and policy management to ensure robust behavior under various conditions.

Copy link
Contributor

coderabbitai bot commented Sep 7, 2024

Walkthrough

The changes improve the handling of policies in the BaseAppsmithRepositoryCEImpl and PolicySolutionCEImpl classes. Modifications ensure that null values are explicitly checked when retrieving existing policies, preventing potential NullPointerExceptions. Policies are now initialized safely, enhancing the robustness of the code.

Changes

File Change Summary
app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/BaseAppsmithRepositoryCEImpl.java
app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PolicySolutionCEImpl.java
Both files were updated to include null checks when retrieving existing policies. The initialization of policy sets now ensures that an empty set is created if no policies exist, preventing NullPointerExceptions.
app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/ce/BaseAppsmithRepositoryImplTest.java
app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/PolicySolutionCEImplTest.java
New test classes were added to validate the behavior of the setUserPermissionsInObject and addPoliciesToExistingObject methods, ensuring correct handling of null and empty policy sets.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Repository
    participant PolicySolution

    User->>Repository: Request to set user permissions
    Repository->>Repository: Retrieve existing policies
    alt Existing policies are null
        Repository->>Repository: Initialize policies to empty set
    else Existing policies exist
        Repository->>Repository: Initialize policies with existing set
    end
    Repository->>PolicySolution: Pass policies for processing
    PolicySolution->>PolicySolution: Add or remove policies as needed
    PolicySolution->>User: Respond with updated policies
Loading

🎉 In code we trust, with checks so bright,
Nulls are now handled, our future's in sight.
Policies guarded, no more fright,
Robust and safe, our code takes flight!
🌟

Possibly related PRs

Tip

New features

Walkthrough comment now includes:

  • Possibly related PRs: A list of potentially related PRs to help you recall past context.
  • Suggested labels: CodeRabbit can now suggest labels by learning from your past PRs. You can also provide custom labeling instructions in the UI or configuration file.

Notes:

  • Please share any feedback in the discussion post on our Discord.
  • Possibly related PRs, automatic label suggestions based on past PRs, learnings, and possibly related issues require data opt-in (enabled by default).

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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.

@abhvsn abhvsn added the ok-to-test Required label for CI label Sep 7, 2024
@github-actions github-actions bot added the Bug Something isn't working label Sep 7, 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: 0

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 58b07dd and 68be843.

Files selected for processing (2)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/BaseAppsmithRepositoryCEImpl.java (1 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PolicySolutionCEImpl.java (2 hunks)
Additional context used
Learnings (1)
app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/BaseAppsmithRepositoryCEImpl.java (1)
Learnt from: sharat87
PR: appsmithorg/appsmith#33602
File: app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/BaseAppsmithRepositoryCEImpl.java:462-473
Timestamp: 2024-06-03T11:56:24.442Z
Learning: The codebase has mechanisms to gracefully handle `null` values, making the use of `Optional` for `AclPermission` unnecessary in certain contexts. This is leveraged by replacing `Optional.empty()` with `null` in method signatures where `null` is already handled gracefully.
Additional comments not posted (3)
app/server/appsmith-server/src/main/java/com/appsmith/server/solutions/ce/PolicySolutionCEImpl.java (2)

72-73: Good handling of null values.

The change to initialize policies with an empty set if existingPolicies is null is a good practice to avoid NullPointerExceptions. This ensures that the method behaves predictably even when existingPolicies is null.


106-107: Consistent null handling across methods.

The approach to handle existingPolicies being null by initializing policies with an empty set is consistent with the changes in the addPoliciesToExistingObject method. This consistency is crucial for maintaining predictable behavior across similar methods.

app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/BaseAppsmithRepositoryCEImpl.java (1)

419-420: Proactive null handling in setUserPermissionsInObject.

The modification to initialize policies with an empty set if existingPolicies is null is a prudent measure to prevent NullPointerExceptions. This change ensures that the method can safely proceed without crashing due to null values.

@appsmithorg appsmithorg deleted a comment from github-actions bot Sep 9, 2024
@abhvsn abhvsn added ok-to-test Required label for CI and removed ok-to-test Required label for CI labels Sep 9, 2024
@abhvsn abhvsn requested a review from nsarupr September 9, 2024 03:16
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: 3

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 68be843 and 63700ce.

Files selected for processing (1)
  • app/server/appsmith-server/src/test/java/com/appsmith/server/repositories/ce/BaseAppsmithRepositoryImplTest.java (1 hunks)

Comment on lines +16 to +21
BaseAppsmithRepositoryCEImpl<TestClass> baseAppsmithRepositoryImpl;

@BeforeEach
public void setup() {
baseAppsmithRepositoryImpl = new BaseAppsmithRepositoryCEImpl<>() {};
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper initialization in the setup method.

The setup method correctly initializes baseAppsmithRepositoryImpl. However, consider using @Mock for dependencies and @InjectMocks for the class under test to ensure isolation and control over the test environment.

Comment on lines +25 to +35
@Test
void testSetUserPermissionsInObject_whenPoliciesIsEmptySet_emptyCollectionValueIsSet() {
// Test the method setPoliciesInObject when the policies are null
// The method should set an empty collection value in the object
// The method should return the object
TestClass obj = baseAppsmithRepositoryImpl
.setUserPermissionsInObject(new TestClass(), null)
.block();
assertNotNull(obj);
Assertions.assertEquals(0, obj.getPolicies().size());
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Review the logic and naming in the test method.

The test method testSetUserPermissionsInObject_whenPoliciesIsEmptySet_emptyCollectionValueIsSet seems to have a misleading name. The description and the test imply it handles null policies, not an empty set. Consider renaming the method to reflect that it tests the behavior when policies are null.

Additionally, the test asserts that the policies size is zero, which contradicts the setup where policies are set to null. This might indicate a misunderstanding in the implementation or the test itself. Clarify whether the method should indeed set an empty set or handle null values differently.

Comment on lines +37 to +51
@Test
void testSetUserPermissionsInObject_whenPoliciesIsNull_nullPoliciesAreSet() {
// Test the method setPoliciesInObject when the policies are empty
// The method should set an empty collection value in the object
// The method should return the object
TestClass obj = new TestClass();
obj.setPolicies(null);
Set<String> permissionGroups = new HashSet<>();
permissionGroups.add(UUID.randomUUID().toString());
obj = baseAppsmithRepositoryImpl
.setUserPermissionsInObject(obj, permissionGroups)
.block();
assertNotNull(obj);
Assertions.assertNull(obj.getPolicies());
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Clarify test behavior and improve assertions.

The test method testSetUserPermissionsInObject_whenPoliciesIsNull_nullPoliciesAreSet is named as if it tests null policies, but the setup and assertions suggest it tests an empty set scenario. The method name should be corrected to reflect the actual test scenario.

The use of Assertions.assertNull(obj.getPolicies()) is appropriate if the expected behavior is to maintain the null state of policies. However, ensure that this aligns with the intended functionality of the method being tested. If the method is supposed to convert null policies into an empty set, this assertion would be incorrect.

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: 1

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 63700ce and e225d54.

Files selected for processing (1)
  • app/server/appsmith-server/src/test/java/com/appsmith/server/solutions/ce/PolicySolutionCEImplTest.java (1 hunks)

Comment on lines +35 to +45
@Test
void testAddNewPoliciesToNullPoliciesObject() {
TestClass obj = new TestClass();
obj.setPolicies(null);
Map<String, Policy> policyMap = new HashMap<>();
policyMap.put("read", new Policy("read", new HashSet<>(Set.of("group1"))));

BaseDomain result = policySolution.addPoliciesToExistingObject(policyMap, obj);

assertTrue(result.getPolicies().containsAll(policyMap.values()));
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Well done on adding the test for null policies!

This test method testAddNewPoliciesToNullPoliciesObject is a crucial addition to ensure that your application gracefully handles cases where the policies object might be null. It's good to see that you're not only setting the policies to null but also verifying that the policies are added correctly afterwards.

However, let's consider a few enhancements:

  1. Additional Assertions: It might be beneficial to add more granular assertions to check individual elements of the policies to ensure that each policy is not only present but also correctly configured.
  2. Exception Handling: While the current test checks for the successful addition of policies, consider adding a test case to verify the system's behavior when an exception is expected, such as adding a null policy to the map.

Here's a suggestion to expand the test coverage:

@Test
void testAddNullPolicyToPoliciesObject() {
    TestClass obj = new TestClass();
    obj.setPolicies(null);
    Map<String, Policy> policyMap = new HashMap<>();
    policyMap.put("read", null);  // Intentionally adding a null policy

    Exception exception = assertThrows(NullPointerException.class, () -> {
        policySolution.addPoliciesToExistingObject(policyMap, obj);
    });

    assertEquals("Policy cannot be null", exception.getMessage());
}

This additional test will help ensure robust error handling in your policy management logic.

Copy link
Contributor

@nsarupr nsarupr left a comment

Choose a reason for hiding this comment

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

Changes look good to me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Something isn't working ok-to-test Required label for CI
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants