ในการใช้ Version Control อย่าง Git บางครั้งเราอาจจะพลาดใส่ไฟล์ที่มีข้อมูลความลับ ไฟล์พาสเวิร์ด เผลอ commit และ push ขึ้นไปยัง Public Repository อย่าง Github ถึงแม้เราจะ rm, commit และ push ไปแล้วก็ตาม ไฟล์นั้นจะยังอยู่ใน history เราจะแก้ไขอย่างไร
วิธีการแก้ไขสามารถทำได้โดยใช้คำสั่ง git filter-branch หรือใช้ tools ที่ชื่อว่า bfg ในเคสนี้เราจะแนะนำการใช้ bfg เพราะว่าง่ายและเร็วกว่า เรามาเริ่มกันเลย
1. ติดตั้งโปรแกรม
- install java
- download bfg
- backup repository, backup repository, backup repository และ backup
2. โคลน Repository มาใหม่ แบบ mirror
git clone --mirror https://github.com/gnoparus/bualabs.git
เราอาจจะ clone แบบ mirror มา backup ไว้อีกชุดก็ได้ เพื่อความสบายใจ
3. ลบ Folder ชื่อ secretfolder
java -jar bfg.jar --delete-folders secretfolder bualabs.git
เราไม่สามารถใส่ path1/path2 ได้ ใส่ได้แต่ชื่อ Folder ตรง ๆ
4. เข้าไปเคลียร์ค่าใน Folder แล้ว push
cd bualabs.git
git reflog expire --expire=now --all && git gc --prune=now --aggressive
git push
5. สำเร็จแล้ว
ลองเช็คดู history ในเว็บ github.com ไม่มี Folder ชื่อ secretfolder เหลืออยู่
แนะนำให้ทุกคนในทีม clone ใหม่ จะได้ไม่มีไฟล์ข้อมูลลับเก่าค้างอยู่ แล้ว commit กลับเข้ามาอีก
คำสั่งอื่น ๆ ที่น่าสนใจ
# ลบไฟล์ชื่อ secretfile
java -jar bfg.jar --delete-files secretfile my-repo.git
# ลบไฟล์ที่ใหญ่เกิน 100M
java -jar bfg.jar --strip-blobs-bigger-than 100M my-repo.git
# แทนที่ข้อความที่ตรงกับข้อความในไฟล์ passwords.txt ด้วยคำว่า ***REMOVED***
่java -jar bfg.jar --replace-text passwords.txt my-repo.git
หมายเหตุ
- หลีกเลี่ยงคำสั่ง
git add .
หรือgit commit -a
ควร add/rm ทีละไฟล์ เช่นgit add file1
หรือgit rm file2
- แก้ 1 วัตถุประสงค์ ต่อ 1 commit อย่าเอาหลาย ๆ อย่างมารวมเป็น commit เดียว จะงง
- commit บ่อย ๆ และเขียนคำอธิบายให้ชัดเจน
- โดย Default แล้ว bfg จะไม่ทำงานกับ commit ล่าสุด เนื่องจากเสี่ยงกวนกับโค้ดบน Production ให้ลองดูคำสั่งพวก git revert แทน
- ไฟล์ลับ หรือพาสเวิร์ด ที่หลุดออกไปอยู่ใน Public Repository แล้วถือว่า Compromised ไปแล้วให้รีบเปลี่ยน หรือยกเลิกทันที
เครดิต
- https://rtyley.github.io/bfg-repo-cleaner/
- https://help.github.com/en/articles/removing-sensitive-data-from-a-repository