Git Issue - Committing the password to Remote Repo

Git Issue - Committing the password to Remote Repo

There are high chances that beginners at times commit secrets, sensitive information or password to remote repo accidentally. In this article, we will see how we can revert back the accident. Also, we will see how we can make sure this won’t be repeated in the future.

If the commit was done recently, we can use the git’s command rebase.

git rebase -i HEAD~1

Post running the above command → choose ‘edit’ > remove the file > rebase.

Then run the command:

git push origin --force --all

The second way to get this done is using a python-based tool called git-filter-repo. Using this tool, we can remove a file from the complete commit history.

https://github.com/newren/git-filter-repo

git filter-repo --path <path_of_the_file_to_be_removed>

To run this command, we will need python installed in our system.

Post this command run the below command:

git push --force --all

Post this changes, you will need help from your teammates as well.

Ask your teammates to pull the recent changes which you have done.

# ask teammates to run this command
git fetch origin
git reset --hard origin/main

Voila.! issue resolved. Now let’s make sure how we can avoid this issue in the future.

We can use the feature called git pre-commit hook to make sure passwords are not committed into the repo by anyone.

How to get this setup?

  1. go to path/to/repo/.git/hooks/ folder in local repo

  2. run command ‘touch pre-commit’

  3. run command ‘chmod +x pre-commit‘

  4. write the below bash script

     #!/bin/bash
    
     # List of patterns to check for sensitive data
     PATTERNS=("password" "API_KEY" "SECRET" "TOKEN" "PRIVATE_KEY")
    
     # Check staged files for sensitive data
     for file in $(git diff --cached --name-only); do
         if [ -f "$file" ]; then
             for pattern in "${PATTERNS[@]}"; do
                 if grep -qi "$pattern" "$file"; then
                     echo "ERROR: Found sensitive pattern '$pattern' in $file"
                     echo "Commit rejected. Remove the secret before committing."
                     exit 1
                 fi
             done
         fi
     done
    
     echo "No secrets detected. Proceeding with commit."
     exit 0
    

    You can also write a python script as well - anything scripting language as per your requirement.