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

🔧 feat(casaos-update-database-password): Add script to update database password #21

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

dragonfire1119
Copy link
Contributor

@dragonfire1119 dragonfire1119 commented Nov 15, 2024

This is a work in progress

This pull request adds a new script run.sh that allows users to update the database password for their CasaOS application. The script supports both PostgreSQL and MySQL/MariaDB databases, and it provides instructions for updating the password in the docker-compose.yml file.

The key features of this script include:

  • Checking if the script is run as root
  • Displaying a user-friendly introduction and instructions
  • Allowing the user to select the database container to update
  • Prompting the user to enter a new password
  • Updating the password in the database container
  • Providing an option to edit the docker-compose.yml file using the user's preferred editor (nano or vim)
  • Applying the changes using the casaos-cli tool

This script aims to simplify the process of updating the database password for CasaOS users, making it more accessible and user-friendly.

Summary by CodeRabbit

  • New Features

    • Introduced a new script for updating database passwords for PostgreSQL and MySQL/MariaDB containers.
    • Added interactive selection for running database containers and secure password input.
    • Provided a command snippet for easy execution of the script.
  • Documentation

    • Added a comprehensive README.md detailing the script's purpose, features, and usage instructions.

…e password

This commit adds a new script `run.sh` that allows users to update the database password for their CasaOS application. The script supports both PostgreSQL and MySQL/MariaDB databases, and it provides instructions for updating the password in the `docker-compose.yml` file.

The key features of this script include:

- Checking if the script is run as root
- Displaying a user-friendly introduction and instructions
- Allowing the user to select the database container to update
- Prompting the user to enter a new password
- Updating the password in the database container
- Updating the `.env` file if it exists
- Providing an option to edit the `docker-compose.yml` file using the user's preferred editor (nano or vim)
- Applying the changes using the `casaos-cli` tool

This script aims to simplify the process of updating the database password for CasaOS users, making it more accessible and user-friendly.
Copy link

coderabbitai bot commented Nov 15, 2024

Walkthrough

The changes introduce a new script, casaos-update-database-password, along with its accompanying README.md file. The README provides detailed information about the script's purpose, which is to update the root/admin passwords for PostgreSQL, MySQL, and MariaDB containers managed by Docker. The script includes features such as automatic detection of running containers, an interactive selection process, and secure password input. It also includes error handling and user guidance for editing the docker-compose.yml file post-update.

Changes

File Change Summary
casaos-update-database-password/README.md Added a new README.md file that describes the purpose, features, and usage instructions for the casaos-update-database-password script.
casaos-update-database-password/run.sh Introduced a new script to update database passwords for PostgreSQL and MySQL/MariaDB containers, including error handling and user prompts.

Possibly related PRs

🐇 In the garden, passwords bloom,
With scripts to chase away the gloom.
Containers dance, a secure delight,
Updating secrets, all done right!
So hop along, don't delay,
A safer database is here to stay! 🌼

Warning

Rate limit exceeded

@dragonfire1119 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 4 minutes and 28 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 43e996b and 1084d9c.


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.

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.

Removes the functionality to update the .env file with the new database
password. This change simplifies the script and focuses on the core
functionality of updating the database password.
env file update

This change updates the README file for the casaos-update-database-
password script to remove the mention of automatically updating the
corresponding .env file. The script now only updates the root/admin
password for the running database containers.
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: 5

🧹 Outside diff range and nitpick comments (3)
casaos-update-database-password/run.sh (3)

5-8: Remove unused color variables

The GREEN and YELLOW color variables are defined but never used in the script.

# Set text colors
RED='\033[0;31m'
-GREEN='\033[0;32m'
-YELLOW='\033[1;33m'
NC='\033[0m' # No Color
🧰 Tools
🪛 Shellcheck

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

(SC2034)


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

(SC2034)


27-27: Define version as a variable

Consider defining the version number as a variable at the top of the script for easier maintenance.

+# Script version
+VERSION="0.0.1"
+
 # Function to display menu
 show_intro() {
     clear
-    print_header "BigBearCasaOS Database Password Update Tool V0.0.1"
+    print_header "BigBearCasaOS Database Password Update Tool V${VERSION}"

42-43: Enhance error handling

Consider adding set -u to exit on undefined variables and catch potential issues early.

# Set error handling
set -e
+set -u
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 43e996b and 1084d9c.

📒 Files selected for processing (2)
  • casaos-update-database-password/README.md (1 hunks)
  • casaos-update-database-password/run.sh (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • casaos-update-database-password/README.md
🧰 Additional context used
🪛 Shellcheck
casaos-update-database-password/run.sh

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

(SC2034)


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

(SC2034)


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

(SC2154)

🔇 Additional comments (1)
casaos-update-database-password/run.sh (1)

10-14: LGTM! Root privilege check is properly implemented.

The script correctly verifies root privileges which is essential for Docker operations.

fi

# Show instructions before editing
show_instructions "$container_name"
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix undefined variable container_name

The container_name variable is referenced but not assigned. This should be container based on the selection logic.

-  show_instructions "$container_name"
+  show_instructions "$container"
📝 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
show_instructions "$container_name"
show_instructions "$container"
🧰 Tools
🪛 Shellcheck

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

(SC2154)

edit_docker_compose() {
local service_name=$1
local editor_choice=$2
local docker_compose_path="${APPS_DIR}/${service_name}/docker-compose.yml"
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix undefined variable APPS_DIR

The APPS_DIR variable is used but never defined. This could cause the script to fail.

Add this at the beginning of the script:

+# Configuration
+APPS_DIR="/var/lib/casaos/apps"  # Adjust this path according to your CasaOS installation

Committable suggestion skipped: line range outside the PR's diff.

docker exec -it $container psql -U postgres -c "ALTER USER postgres WITH PASSWORD '$NEW_PASSWORD';"
elif [[ $container == *"mysql"* ]] || [[ $container == *"mariadb"* ]]; then
echo "Updating MySQL/MariaDB password..."
docker exec -it $container mysql -u root -pDB_PASSWORD_CHANGEME -e "ALTER USER 'root'@'%' IDENTIFIED BY '$NEW_PASSWORD';"
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove hardcoded default password and add error handling

The script uses a hardcoded default password 'DB_PASSWORD_CHANGEME' which is insecure. Also, add error handling for the password update operation.

-    docker exec -it $container mysql -u root -pDB_PASSWORD_CHANGEME -e "ALTER USER 'root'@'%' IDENTIFIED BY '$NEW_PASSWORD';"
+    # First try with empty password (common default)
+    if ! docker exec -it $container mysql -u root -e "ALTER USER 'root'@'%' IDENTIFIED BY '$NEW_PASSWORD';" 2>/dev/null; then
+        # If that fails, prompt for current password
+        read -sp "Enter current MySQL root password: " CURRENT_PASSWORD
+        echo
+        if ! docker exec -it $container mysql -u root -p"$CURRENT_PASSWORD" -e "ALTER USER 'root'@'%' IDENTIFIED BY '$NEW_PASSWORD';"; then
+            echo "Failed to update MySQL password. Please verify your current password."
+            exit 1
+        fi
+    fi
📝 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
docker exec -it $container mysql -u root -pDB_PASSWORD_CHANGEME -e "ALTER USER 'root'@'%' IDENTIFIED BY '$NEW_PASSWORD';"
# First try with empty password (common default)
if ! docker exec -it $container mysql -u root -e "ALTER USER 'root'@'%' IDENTIFIED BY '$NEW_PASSWORD';" 2>/dev/null; then
# If that fails, prompt for current password
read -sp "Enter current MySQL root password: " CURRENT_PASSWORD
echo
if ! docker exec -it $container mysql -u root -p"$CURRENT_PASSWORD" -e "ALTER USER 'root'@'%' IDENTIFIED BY '$NEW_PASSWORD';"; then
echo "Failed to update MySQL password. Please verify your current password."
exit 1
fi
fi

Comment on lines +117 to +118
read -sp "Enter new password: " NEW_PASSWORD
echo
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add password validation

The script should validate password complexity to ensure security. Consider adding checks for minimum length, special characters, etc.

+# Password validation function
+validate_password() {
+    local pass="$1"
+    if [[ ${#pass} -lt 8 ]]; then
+        echo "Password must be at least 8 characters long"
+        return 1
+    fi
+    if ! [[ "$pass" =~ [0-9] ]]; then
+        echo "Password must contain at least one number"
+        return 1
+    fi
+    if ! [[ "$pass" =~ [A-Z] ]]; then
+        echo "Password must contain at least one uppercase letter"
+        return 1
+    fi
+    return 0
+}

 # Get new password
-read -sp "Enter new password: " NEW_PASSWORD
+while true; do
+    read -sp "Enter new password: " NEW_PASSWORD
+    echo
+    if validate_password "$NEW_PASSWORD"; then
+        break
+    fi
+done
-echo

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +68 to +97
edit_docker_compose() {
local service_name=$1
local editor_choice=$2
local docker_compose_path="${APPS_DIR}/${service_name}/docker-compose.yml"

if [[ ! -f "$docker_compose_path" ]]; then
echo "Error: The docker-compose.yml file does not exist for the service: $service_name"
exit 1
fi

# Check if the chosen editor is installed
if ! command -v "$editor_choice" &> /dev/null; then
echo "Error: $editor_choice is not installed. Please install it or choose another editor."
exit 1
fi

# Show instructions before editing
show_instructions "$container_name"

# Open the editor
"$editor_choice" "$docker_compose_path"

# Apply the changes using casaos-cli
if casaos-cli app-management apply "$service_name" --file="$docker_compose_path"; then
echo "Changes applied successfully."
else
echo "Error: Failed to apply changes. Please check the docker-compose file for errors."
exit 1
fi
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add safety measures for docker-compose editing

Consider adding these safety features:

  1. Backup the docker-compose file before editing
  2. Validate the docker-compose file after editing
 edit_docker_compose() {
   local service_name=$1
   local editor_choice=$2
   local docker_compose_path="${APPS_DIR}/${service_name}/docker-compose.yml"

+  # Create backup
+  cp "$docker_compose_path" "${docker_compose_path}.bak"
+  echo "Created backup at ${docker_compose_path}.bak"
+
   if [[ ! -f "$docker_compose_path" ]]; then
     echo "Error: The docker-compose.yml file does not exist for the service: $service_name"
     exit 1
   fi

   # Check if the chosen editor is installed
   if ! command -v "$editor_choice" &> /dev/null; then
     echo "Error: $editor_choice is not installed. Please install it or choose another editor."
     exit 1
   fi

   # Show instructions before editing
   show_instructions "$container"

   # Open the editor
   "$editor_choice" "$docker_compose_path"

+  # Validate docker-compose file
+  if ! docker-compose -f "$docker_compose_path" config > /dev/null 2>&1; then
+    echo "Error: Invalid docker-compose file. Restoring backup..."
+    cp "${docker_compose_path}.bak" "$docker_compose_path"
+    exit 1
+  fi
+
   # Apply the changes using casaos-cli
   if casaos-cli app-management apply "$service_name" --file="$docker_compose_path"; then
     echo "Changes applied successfully."
+    rm "${docker_compose_path}.bak"
   else
     echo "Error: Failed to apply changes. Please check the docker-compose file for errors."
+    echo "Restoring backup..."
+    cp "${docker_compose_path}.bak" "$docker_compose_path"
     exit 1
   fi
 }

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Shellcheck

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

(SC2154)

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.

1 participant