gitea源码

repo_gpg.go 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package git
  5. import (
  6. "fmt"
  7. "os"
  8. "strings"
  9. "code.gitea.io/gitea/modules/git/gitcmd"
  10. "code.gitea.io/gitea/modules/process"
  11. )
  12. // LoadPublicKeyContent will load the key from gpg
  13. func (gpgSettings *GPGSettings) LoadPublicKeyContent() error {
  14. if gpgSettings.Format == SigningKeyFormatSSH {
  15. content, err := os.ReadFile(gpgSettings.KeyID)
  16. if err != nil {
  17. return fmt.Errorf("unable to read SSH public key file: %s, %w", gpgSettings.KeyID, err)
  18. }
  19. gpgSettings.PublicKeyContent = string(content)
  20. return nil
  21. }
  22. content, stderr, err := process.GetManager().Exec(
  23. "gpg -a --export",
  24. "gpg", "-a", "--export", gpgSettings.KeyID)
  25. if err != nil {
  26. return fmt.Errorf("unable to get default signing key: %s, %s, %w", gpgSettings.KeyID, stderr, err)
  27. }
  28. gpgSettings.PublicKeyContent = content
  29. return nil
  30. }
  31. // GetDefaultPublicGPGKey will return and cache the default public GPG settings for this repository
  32. func (repo *Repository) GetDefaultPublicGPGKey(forceUpdate bool) (*GPGSettings, error) {
  33. if repo.gpgSettings != nil && !forceUpdate {
  34. return repo.gpgSettings, nil
  35. }
  36. gpgSettings := &GPGSettings{
  37. Sign: true,
  38. }
  39. value, _, _ := gitcmd.NewCommand("config", "--get", "commit.gpgsign").RunStdString(repo.Ctx, &gitcmd.RunOpts{Dir: repo.Path})
  40. sign, valid := ParseBool(strings.TrimSpace(value))
  41. if !sign || !valid {
  42. gpgSettings.Sign = false
  43. repo.gpgSettings = gpgSettings
  44. return gpgSettings, nil
  45. }
  46. signingKey, _, _ := gitcmd.NewCommand("config", "--get", "user.signingkey").RunStdString(repo.Ctx, &gitcmd.RunOpts{Dir: repo.Path})
  47. gpgSettings.KeyID = strings.TrimSpace(signingKey)
  48. format, _, _ := gitcmd.NewCommand("config", "--default", SigningKeyFormatOpenPGP, "--get", "gpg.format").RunStdString(repo.Ctx, &gitcmd.RunOpts{Dir: repo.Path})
  49. gpgSettings.Format = strings.TrimSpace(format)
  50. defaultEmail, _, _ := gitcmd.NewCommand("config", "--get", "user.email").RunStdString(repo.Ctx, &gitcmd.RunOpts{Dir: repo.Path})
  51. gpgSettings.Email = strings.TrimSpace(defaultEmail)
  52. defaultName, _, _ := gitcmd.NewCommand("config", "--get", "user.name").RunStdString(repo.Ctx, &gitcmd.RunOpts{Dir: repo.Path})
  53. gpgSettings.Name = strings.TrimSpace(defaultName)
  54. if err := gpgSettings.LoadPublicKeyContent(); err != nil {
  55. return nil, err
  56. }
  57. repo.gpgSettings = gpgSettings
  58. return repo.gpgSettings, nil
  59. }