เหตุใดต้อง Sign Commits ด้วย GPG?
GPG signing เป็นวิธีการยืนยันตัวตนของผู้เขียน commit เป็นการสร้างความมั่นใจว่า commit นั้นมาจากคนที่ถูกต้องจริง ๆ โดยไม่ถูก tampering ด้วยการใช้คู่ GPG keys (public/private) เช่นเดียวกับ SSH authentication แต่ GPG signature สามารถตรวจสอบได้บน GitHub GitLab และ repository server อื่น ๆ และจะแสดงป้ายเศษ “Verified” ใน commit history
ข้อดีของการ Sign Commits
การ sign commits มีข้อดีหลายประการ
- ความน่าเชื่อถือ – ผู้อื่นสามารถตรวจสอบว่า commit นั้นมาจากคุณจริง ๆ
- ความปลอดภัย – ป้องกันการ impersonate หรือปลอมแปลง commit
- Verified Badge – GitHub และ GitLab จะแสดงป้ายเศษ “Verified” บน commits ที่ signed
- Audit Trail – สร้าง trail ของการเปลี่ยนแปลง code ที่ verified
สร้าง GPG Key
ขั้นแรกต้องสร้าง GPG key บน VPS หรือ local machine ของคุณ ใช้คำสั่ง
gpg --full-generate-key
คำสั่งนี้จะเปิด interactive menu ให้คุณเลือก key type (ปกติเลือก RSA 4096), expiration date, name, email, และ passphrase
gpg (GnuPG) 2.2.19
Please select what kind of key you want:
(1) RSA and RSA
(2) DSA and Elgamal
(3) DSA (sign only)
(4) RSA (sign only)
Your selection? 1
หลังจากสร้าง key เสร็จแล้ว ให้ลิสต์ keys ทั้งหมด
gpg --list-secret-keys --keyid-format=long
คำสั่งนี้จะแสดง key ID ของคุณ เช่น 3AA5C34371567BD2
ตั้งค่า Git ให้ใช้ GPG Key
ตั้งค่า Git โดยบอก Git ว่า GPG key ID ไหนที่ต้องใช้สำหรับ signing commits
git config --global user.signingkey 3AA5C34371567BD2
ตั้งค่านี้จะบอก Git ให้ใช้ GPG key นี้สำหรับการ sign commits ทั้งหมด
Sign Commits ด้วย -S Flag
เมื่อต้องการสร้าง commit ที่ signed ให้ใช้ flag -S (uppercase S) ร่วมกับ commit command
git commit -S -m "Your commit message"
Git จะขอให้คุณใส่ passphrase ของ GPG key จึงจะสร้าง signature ได้
Auto-sign All Commits
ถ้าต้องการให้ Git auto-sign ทุก commits โดยไม่ต้องพิมพ์ -S ทุกครั้ง ให้ตั้งค่า
git config --global commit.gpgsign true
ตั้งแต่นี้เป็นต้นไป ทุก commits ของคุณจะถูก sign โดยอัตโนมัติ
Sign Tags
นอกจาก commits คุณยังสามารถ sign tags ได้โดยใช้ -s flag (lowercase s)
git tag -s v1.0.0 -m "Release version 1.0.0"
tag ที่ signed จะถูก verify เมื่อ checkout
ตรวจสอบ Signatures
ตรวจสอบว่า commits มีสัญลักษณ์ที่ถูกต้องหรือไม่ ใช้คำสั่ง
git log --show-signature
คำสั่งนี้จะแสดง signature information ของแต่ละ commit รวมถึง GPG key ID ที่ใช้
git log --oneline --show-signature
GitHub/GitLab Verified Badge
เมื่อ push commits ที่ signed ไปยัง GitHub หรือ GitLab GitHub จะตรวจสอบ signature โดยอัตโนมัติ และแสดงป้ายเศษ “Verified” ข้าง commit message ถ้า signature valid
ขั้นแรกต้องเพิ่ม public GPG key ไปยัง GitHub ไปที่ Settings > SSH and GPG keys > Add new GPG key และ paste public key
gpg --armor --export 3AA5C34371567BD2
