Published on

Ngăn chặn việc vô tình push secret keys lên remote repositories

Authors

Vấn đề 🤧

Khi làm việc với nhiều project, chúng ta thường sử dụng các secret keys để kết nối với các services như AWS, Firebase, Google Cloud,... Điều này dẫn đến việc có thể vô tình push secret keys lên remote repositories như github/gitlab và bị lộ thông tin. Điều này rất nguy hiểm vì ai cũng có thể clone project của bạn và sử dụng secret keys đó để tấn công vào hệ thống của bạn.

Giải quyết vấn đề 🤞

  • Sử dụng công cụ của Python là detect-secrets để scan project tìm secret keys.
  • Sau đấy thì config với husky và setup pre-commit để tự động scan trước khi commit code.
  • Khi phát hiện ra secret keys => hiển thị lỗi => không cho commit nữa.
  • Ngược lại thì cho phép commit và push code.

Cách config 🥝🥝

Cài Python và detect-secrets

  • Download Python tại official Python website
  • Verify Python đã được cài đặt thành công bằng cách chạy python --version
  • Cài đặt Pip dependencies:
    python -m ensurepip --upgrade
    python -m pip install --upgrade pip
    
  • Cuối cùng là cài đặt detect-secrets sử dụng pip:
    pip install detect-secrets
    
  • Verify lại Python và detect-secrets đã được cài đặt thành công hay chưa: Install Python và detect-secrets

Cài husky và setup pre-commit

  • Lưu ý là đã git init từ trước rồi nhé
  • Cài đặt huskylint-staged dependencies
  • Chỉ cần cài --save-dev là được rùi nhé vì chỉ cần chạy ở local thôi mà :v
    npm install --save-dev husky lint-staged
    
  • Setup .husky folder:
    npx husky install
    
  • Tạo mới một file ở .husky/pre-commit và cấp quyền:
    touch .husky/pre-commit
    chmod +x .husky/pre-commit
    
  • Thêm đoạn script sau tới file .husky/pre-commit:
    npm run scan-secrets-key
    npx lint-staged
    

Setup script và lint-staged ở package.json file

  • Thêm đoạn script sau vào trong "scripts" object:
    "scripts": {
      ...
      "detect-secrets": "detect-secrets-hook --baseline .secrets.baseline",
      "scan-secrets-key": "detect-secrets scan --exclude-files package.json > .secrets.baseline"
    }
    
  • Cuối cùng là thêm đoạn sau vào trong "lint-staged" object:
    ...
    "lint-staged": {
      "*": "npm run detect-secrets"
    }
    

OK rồi, giờ thì test thử xem nào 🚀🚀

  • Thêm fake AWS secret key vào file src/App.tsx: Add fake secret key
  • Add và commit code:
    git add . && git commit -m "Setup husky and detect-secrets"
    
  • Bugs sẽ hiển thị ở terminal và chặn quá trình commit: Add fake secret key
  • Okii vậy là chúng ta đã chặn được việc vô tình push secret keys lên github/gitlab rồi đó 🎉🎉:

Lời kết 🎉🎉

Việc vô tình push secret keys lên github/gitlab là một vấn đề rất nguy hiểm. Vì vậy, việc setup project với husky để scan project tìm secret keys, tự động run test, lint code trước khi push code lên github là một cách hiệu quả để ngăn chặn việc này. Hy vọng bài viết này sẽ giúp ích cho bạn 🤗🤗.