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

chore: Add appsmith user existence check for auth tests #38069

Merged
merged 5 commits into from
Dec 13, 2024

Conversation

abhvsn
Copy link
Contributor

@abhvsn abhvsn commented Dec 10, 2024

Description

PR to add the check for appsmith user existence before any assertions in pg-auth-test to remove the flakiness.

🔍 Cypress test results

Warning

Tests have not run on the HEAD 0ac8736 yet


Fri, 13 Dec 2024 05:18:03 UTC

Communication

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

  • Yes
  • No

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced testing for PostgreSQL authentication to ensure the Appsmith user exists before access checks.
  • Tests

    • Updated existing test functions to include user existence verification, improving the robustness of the testing process.
    • Introduced new functions to verify user existence and check the readiness of the Appsmith instance and PostgreSQL.
    • Streamlined logic for readiness checks, enhancing overall testing efficiency.

Copy link
Contributor

coderabbitai bot commented Dec 10, 2024

Walkthrough

The pull request modifies the test-pg-auth.sh script to enhance PostgreSQL user authentication testing. A new function, check_user_exists, has been introduced to verify the presence of the Appsmith user in the PostgreSQL database. This function is now called in existing test functions before checking user access to databases. Several functions related to readiness checks have been removed, streamlining the logic while preserving the overall structure and flow of the tests.

Changes

File Path Change Summary
deploy/docker/tests/test-pg-auth.sh Added check_user_exists(user) function to verify user existence; updated existing tests to call this function; removed several readiness check functions.
deploy/docker/tests/pg-test-utils.sh Added multiple functions: is_appsmith_instance_ready(), wait_for_postgres(), check_user_exists(user), check_user_datasource_access_with_host_port_wo_auth(), and check_user_datasource_access_with_local_port_wo_auth().

Possibly related PRs

Suggested labels

Bug, ok-to-test, DB Infrastructure Pod

Suggested reviewers

  • sharat87
  • pratapaprasanna

🎉 In the realm of code where functions play,
A check for users brightens the day!
With retries galore, and access in sight,
PostgreSQL testing shines ever so bright.
So let’s raise a toast to the code we adore,
For robust tests and much more! 🎈


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f1cb8ea and 0ac8736.

📒 Files selected for processing (2)
  • deploy/docker/tests/pg-test-utils.sh (1 hunks)
  • deploy/docker/tests/test-pg-auth.sh (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • deploy/docker/tests/pg-test-utils.sh
🧰 Additional context used
📓 Learnings (1)
deploy/docker/tests/test-pg-auth.sh (1)
Learnt from: abhvsn
PR: appsmithorg/appsmith#38069
File: deploy/docker/tests/pg-test-utils.sh:37-53
Timestamp: 2024-12-13T05:09:22.587Z
Learning: In `deploy/docker/tests/pg-test-utils.sh`, code is used in a controlled test environment, so security concerns like SQL injection in functions like `check_user_exists` are acceptable.
🔇 Additional comments (3)
deploy/docker/tests/test-pg-auth.sh (3)

123-124: LGTM: Proper sequencing of readiness checks

The wait_for_postgres call ensures PostgreSQL is ready before proceeding with instance checks.


205-220: LGTM: Consistent implementation across test cases

The error handling implementation is consistent with the first test case.


128-139: LGTM: Proper error handling for user existence check

The implementation includes proper error handling and clear error messages.

Let's verify the check_user_exists implementation:

✅ Verification successful

Implementation of check_user_exists function is robust and secure

The function implementation includes:

  • Proper parameterization of user input
  • Retry mechanism with max attempts
  • Clear status messages
  • Appropriate use of PostgreSQL system catalog
  • Clean return codes
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify check_user_exists implementation in pg-test-utils.sh
rg -l "check_user_exists" ./deploy/docker/tests/pg-test-utils.sh

Length of output: 103


Script:

#!/bin/bash
# Get the implementation of check_user_exists function
rg -A 10 "^check_user_exists" ./deploy/docker/tests/pg-test-utils.sh

Length of output: 489


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. (Experiment)
  • @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 Dec 10, 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: 1

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ad5e25f and 07e4b1c.

📒 Files selected for processing (1)
  • deploy/docker/tests/test-pg-auth.sh (3 hunks)
🧰 Additional context used
🪛 Shellcheck (0.10.0)
deploy/docker/tests/test-pg-auth.sh

[warning] 115-115: user_exists appears unused. Verify use (or export if used externally).

(SC2034)

🔇 Additional comments (2)
deploy/docker/tests/test-pg-auth.sh (2)

207-215: LGTM - Good integration of user existence check

The check is properly placed before testing access permissions, which should help reduce test flakiness.


282-290: LGTM - Consistent implementation across test functions

The integration follows the same pattern as the first test function, maintaining consistency.

Let's verify the effectiveness of this change in reducing test flakiness:

✅ Verification successful

The previous GitHub API query didn't yield results, so let's examine the test implementation directly to verify the consistency and potential flakiness improvements.


I need to see the complete test file to verify the consistency of error handling patterns and test implementation across functions, as the previous output only showed a partial implementation.


Implementation verified - Consistent error handling and test patterns

The test functions maintain consistent implementation patterns:

  • Both test functions use identical error checking with check_user_datasource_access_with_auth
  • Error handling follows the same pattern with proper exit codes
  • Both functions verify user existence before access checks
  • The implementation includes proper wait conditions and retries to reduce flakiness
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check recent test runs to compare failure rates
gh api graphql -f query='
{
  repository(owner: "appsmithorg", name: "appsmith") {
    pullRequests(last: 50, states: [OPEN, MERGED]) {
      nodes {
        title
        commits(last: 1) {
          nodes {
            commit {
              checkSuites(first: 1) {
                nodes {
                  checkRuns(first: 100) {
                    nodes {
                      name
                      conclusion
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}' | jq '.data.repository.pullRequests.nodes[] | select(.title | contains("pg-auth-test"))'

Length of output: 645


Script:

#!/bin/bash
# Let's check the test file content and its recent changes
git log -p --max-count=1 deploy/docker/tests/test-pg-auth.sh

# Also check for any related test files
fd -e sh . deploy/docker/tests/ -x grep -l "check_user_datasource_access_with_auth"

# And examine the function implementation
grep -A 10 "check_user_datasource_access_with_auth()" deploy/docker/tests/test-pg-auth.sh

Length of output: 636


Script:

#!/bin/bash
# Let's examine the full test file to understand the error handling and test patterns
cat deploy/docker/tests/test-pg-auth.sh

# Also check for any recent issues or PRs related to this test
fd . deploy/docker/tests/ -x grep -l "test-pg-auth"

Length of output: 12278

@abhvsn abhvsn requested a review from AnaghHegde December 10, 2024 07:07
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

🧹 Outside diff range and nitpick comments (1)
deploy/docker/tests/test-pg-auth.sh (1)

206-214: Improve error handling in test functions

Both test functions should handle the user existence check failure explicitly:

-      check_user_exists appsmith
+      if ! check_user_exists appsmith; then
+        echo "Failed to verify appsmith user existence"
+        echo "Test ${FUNCNAME[0]} Failed ❌"
+        exit 1
+      fi

Also applies to: 281-289

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 07e4b1c and 2b01442.

📒 Files selected for processing (1)
  • deploy/docker/tests/test-pg-auth.sh (3 hunks)
🔇 Additional comments (2)
deploy/docker/tests/test-pg-auth.sh (2)

206-208: Verify potential race condition between user check and access check

There's a potential race condition between checking user existence and verifying access. Consider combining these checks or implementing a transaction-like approach.

Also applies to: 281-283


111-128: 🛠️ Refactor suggestion

Add input validation and error handling to improve robustness

The function implementation needs several improvements for better reliability:

 check_user_exists() {
   local user
   user=$1
+  # Validate input parameter
+  if [ -z "$user" ]; then
+    echo "Error: User parameter is required"
+    return 1
+  }
+  # Use consistent retry configuration with other functions
+  local max_retries=${PG_MAX_RETRIES:-200}
+  local retry_interval=${PG_RETRY_INTERVAL:-2}
   local retry_count=0
-  local max_retries=200
   while [ $retry_count -lt $max_retries ]; do
-    if docker exec "${container_name}" bash -c "psql -p 5432 -U postgres -c \"\du\" | grep -q -w \"$user\""; then
+    if docker exec "${container_name}" bash -c "psql -p 5432 -U postgres -c \"\du\" 2>/dev/null | grep -q -w \"$user\""; then
       echo "$user user exists."
       return 0
     fi
     echo "Waiting for $user user to be created... (Attempt: $((retry_count + 1)))"
     retry_count=$((retry_count + 1))
-    sleep 1
+    sleep "$retry_interval"
   done
   echo "$user user does not exist."
   return 1
 }

Likely invalid or redundant comment.

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

🧹 Outside diff range and nitpick comments (1)
deploy/docker/tests/test-pg-auth.sh (1)

140-147: Enhance error handling for user existence check

Consider adding descriptive output messages for the user existence check to improve test debugging.

-      check_user_exists appsmith
+      echo "Checking if appsmith user exists..."
+      if ! check_user_exists appsmith; then
+        echo "Test failed: appsmith user does not exist ❌"
+        exit 1
+      fi
+      echo "appsmith user exists ✅"

Also applies to: 214-221

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2b01442 and 0e6555f.

📒 Files selected for processing (1)
  • deploy/docker/tests/test-pg-auth.sh (3 hunks)

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)
deploy/docker/tests/pg-test-utils.sh (1)

2-18: Consider making retry parameters configurable

The retry count and sleep duration are hardcoded. Consider making these configurable via environment variables.

+# Default retry settings
+: "${MAX_HEALTH_RETRIES:=200}"
+: "${HEALTH_RETRY_INTERVAL:=2}"
+
 is_appsmith_instance_ready() {
-  local max_retries=200
+  local max_retries="$MAX_HEALTH_RETRIES"
   local retry_count=0
   local response_code
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0e6555f and f1cb8ea.

📒 Files selected for processing (2)
  • deploy/docker/tests/pg-test-utils.sh (1 hunks)
  • deploy/docker/tests/test-pg-auth.sh (3 hunks)
🧰 Additional context used
🪛 Shellcheck (0.10.0)
deploy/docker/tests/pg-test-utils.sh

[error] 1-1: Tips depend on target shell and yours is unknown. Add a shebang or a 'shell' directive.

(SC2148)


[warning] 26-26: container_name is referenced but not assigned.

(SC2154)

🔇 Additional comments (2)
deploy/docker/tests/test-pg-auth.sh (2)

123-124: LGTM: Proper sequencing of operations

The wait_for_postgres call before checking user existence ensures proper test setup.


201-208: ⚠️ Potential issue

Add error handling for check_user_exists

Similar to the previous instance, add error handling here as well.

-      check_user_exists appsmith
+      if ! check_user_exists appsmith; then
+          echo "Appsmith user does not exist"
+          echo "Test ${FUNCNAME[0]} Failed ❌"
+          exit 1
+      fi
       # Check if the Appsmith user has read access to databases

@abhvsn abhvsn merged commit 6eb44a1 into release Dec 13, 2024
18 checks passed
@abhvsn abhvsn deleted the chore/add-delay-for-appsmith-user-setup branch December 13, 2024 05:21
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