gpg_verification.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2025 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package database
  5. import (
  6. "context"
  7. "github.com/pkg/errors"
  8. "gogs.io/gogs/internal/gpgutil"
  9. )
  10. // VerifyCommitSignature verifies a commit signature against the user's GPG keys.
  11. // It returns verification information including whether the signature is valid.
  12. func (db *DB) VerifyCommitSignature(ctx context.Context, commitContent string, authorEmail string) (*gpgutil.CommitVerification, error) {
  13. // Extract signature from commit
  14. signature, payload, hasSig := gpgutil.ExtractSignature(commitContent)
  15. if !hasSig {
  16. return &gpgutil.CommitVerification{
  17. Verified: false,
  18. Reason: "no signature",
  19. }, nil
  20. }
  21. // Find user by email
  22. user, err := db.Users().GetByEmail(ctx, authorEmail)
  23. if err != nil {
  24. return &gpgutil.CommitVerification{
  25. Verified: false,
  26. Reason: "user not found",
  27. }, nil
  28. }
  29. // Get all GPG keys for the user
  30. keys, err := db.GPGKeys().List(ctx, user.ID)
  31. if err != nil {
  32. return nil, errors.Wrap(err, "list GPG keys")
  33. }
  34. if len(keys) == 0 {
  35. return &gpgutil.CommitVerification{
  36. Verified: false,
  37. Reason: "no GPG keys found",
  38. }, nil
  39. }
  40. // Create keyring from user's GPG keys
  41. var armoredKeys []string
  42. for _, key := range keys {
  43. if key.CanSign && !key.IsExpired() {
  44. armoredKeys = append(armoredKeys, key.Content)
  45. }
  46. }
  47. if len(armoredKeys) == 0 {
  48. return &gpgutil.CommitVerification{
  49. Verified: false,
  50. Reason: "no valid signing keys found",
  51. }, nil
  52. }
  53. keyring, err := gpgutil.CreateKeyring(armoredKeys)
  54. if err != nil {
  55. return nil, errors.Wrap(err, "create keyring")
  56. }
  57. // Verify the signature
  58. verification, err := gpgutil.VerifyCommitSignature(signature, payload, keyring)
  59. if err != nil {
  60. return nil, errors.Wrap(err, "verify signature")
  61. }
  62. return verification, nil
  63. }