How do you handle a situation where you accidentally committed sensitive information (like passwords) to a repository?

Handling an accidentally committed secret means treating it as compromised immediately, purging it from Git history, and rotating the credential, since simply deleting the file in a new commit leaves it visible in prior history.

Key Points: • Remove the sensitive file or line from the current codebase right away with a normal commit, but understand this alone doesn't erase it from history. • Use git filter-repo, git filter-branch, or the BFG Repo-Cleaner to rewrite history and strip the secret from every commit that ever contained it. • After rewriting history, force-push the cleaned branch and have every collaborator re-clone or hard-reset, since the commit hashes have all changed. • Immediately rotate or revoke the exposed credential regardless of history cleanup, because it may already have been scraped by bots or cached elsewhere. • Prevent recurrence with a .gitignore for secret files, environment variables for real deployments, and a pre-commit secret scanner like gitleaks.

Example: A developer accidentally commits a database password in application.properties; the team runs BFG Repo-Cleaner to strip it from history, force-pushes the cleaned repository, and immediately rotates the database password since it must be assumed leaked.

Code Example:

java -jar bfg.jar --replace-text passwords.txt my-repo.git
git push --force

Interview Tip: A concise interview answer is:

"The first thing I'd do is rotate the exposed credential immediately, since it has to be treated as compromised. Then I'd use a tool like BFG Repo-Cleaner or git filter-repo to strip it from history, force-push the cleaned repo, and have the team re-clone."