gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package setting
  4. import (
  5. "math"
  6. "path/filepath"
  7. "sync/atomic"
  8. "code.gitea.io/gitea/modules/generate"
  9. "code.gitea.io/gitea/modules/log"
  10. )
  11. // OAuth2UsernameType is enum describing the way gitea generates its 'username' from oauth2 data
  12. type OAuth2UsernameType string
  13. const (
  14. OAuth2UsernameUserid OAuth2UsernameType = "userid" // use user id (sub) field as gitea's username
  15. OAuth2UsernameNickname OAuth2UsernameType = "nickname" // use nickname field
  16. OAuth2UsernameEmail OAuth2UsernameType = "email" // use email field
  17. OAuth2UsernamePreferredUsername OAuth2UsernameType = "preferred_username" // use preferred_username field
  18. )
  19. func (username OAuth2UsernameType) isValid() bool {
  20. switch username {
  21. case OAuth2UsernameUserid, OAuth2UsernameNickname, OAuth2UsernameEmail, OAuth2UsernamePreferredUsername:
  22. return true
  23. }
  24. return false
  25. }
  26. // OAuth2AccountLinkingType is enum describing behaviour of linking with existing account
  27. type OAuth2AccountLinkingType string
  28. const (
  29. // OAuth2AccountLinkingDisabled error will be displayed if account exist
  30. OAuth2AccountLinkingDisabled OAuth2AccountLinkingType = "disabled"
  31. // OAuth2AccountLinkingLogin account linking login will be displayed if account exist
  32. OAuth2AccountLinkingLogin OAuth2AccountLinkingType = "login"
  33. // OAuth2AccountLinkingAuto account will be automatically linked if account exist
  34. OAuth2AccountLinkingAuto OAuth2AccountLinkingType = "auto"
  35. )
  36. func (accountLinking OAuth2AccountLinkingType) isValid() bool {
  37. switch accountLinking {
  38. case OAuth2AccountLinkingDisabled, OAuth2AccountLinkingLogin, OAuth2AccountLinkingAuto:
  39. return true
  40. }
  41. return false
  42. }
  43. // OAuth2Client settings
  44. var OAuth2Client struct {
  45. RegisterEmailConfirm bool
  46. OpenIDConnectScopes []string
  47. EnableAutoRegistration bool
  48. Username OAuth2UsernameType
  49. UpdateAvatar bool
  50. AccountLinking OAuth2AccountLinkingType
  51. }
  52. func loadOAuth2ClientFrom(rootCfg ConfigProvider) {
  53. sec := rootCfg.Section("oauth2_client")
  54. OAuth2Client.RegisterEmailConfirm = sec.Key("REGISTER_EMAIL_CONFIRM").MustBool(Service.RegisterEmailConfirm)
  55. OAuth2Client.OpenIDConnectScopes = parseScopes(sec, "OPENID_CONNECT_SCOPES")
  56. OAuth2Client.EnableAutoRegistration = sec.Key("ENABLE_AUTO_REGISTRATION").MustBool()
  57. OAuth2Client.Username = OAuth2UsernameType(sec.Key("USERNAME").MustString(string(OAuth2UsernameNickname)))
  58. if !OAuth2Client.Username.isValid() {
  59. OAuth2Client.Username = OAuth2UsernameNickname
  60. log.Warn("[oauth2_client].USERNAME setting is invalid, falls back to %q", OAuth2Client.Username)
  61. }
  62. OAuth2Client.UpdateAvatar = sec.Key("UPDATE_AVATAR").MustBool()
  63. OAuth2Client.AccountLinking = OAuth2AccountLinkingType(sec.Key("ACCOUNT_LINKING").MustString(string(OAuth2AccountLinkingLogin)))
  64. if !OAuth2Client.AccountLinking.isValid() {
  65. log.Warn("Account linking setting is not valid: '%s', will fallback to '%s'", OAuth2Client.AccountLinking, OAuth2AccountLinkingLogin)
  66. OAuth2Client.AccountLinking = OAuth2AccountLinkingLogin
  67. }
  68. }
  69. func parseScopes(sec ConfigSection, name string) []string {
  70. parts := sec.Key(name).Strings(" ")
  71. scopes := make([]string, 0, len(parts))
  72. for _, scope := range parts {
  73. if scope != "" {
  74. scopes = append(scopes, scope)
  75. }
  76. }
  77. return scopes
  78. }
  79. var OAuth2 = struct {
  80. Enabled bool
  81. AccessTokenExpirationTime int64
  82. RefreshTokenExpirationTime int64
  83. InvalidateRefreshTokens bool
  84. JWTSigningAlgorithm string `ini:"JWT_SIGNING_ALGORITHM"`
  85. JWTSigningPrivateKeyFile string `ini:"JWT_SIGNING_PRIVATE_KEY_FILE"`
  86. MaxTokenLength int
  87. DefaultApplications []string
  88. }{
  89. Enabled: true,
  90. AccessTokenExpirationTime: 3600,
  91. RefreshTokenExpirationTime: 730,
  92. InvalidateRefreshTokens: false,
  93. JWTSigningAlgorithm: "RS256",
  94. JWTSigningPrivateKeyFile: "jwt/private.pem",
  95. MaxTokenLength: math.MaxInt16,
  96. DefaultApplications: []string{"git-credential-oauth", "git-credential-manager", "tea"},
  97. }
  98. func loadOAuth2From(rootCfg ConfigProvider) {
  99. sec := rootCfg.Section("oauth2")
  100. if err := sec.MapTo(&OAuth2); err != nil {
  101. log.Fatal("Failed to map OAuth2 settings: %v", err)
  102. return
  103. }
  104. if sec.HasKey("DEFAULT_APPLICATIONS") && sec.Key("DEFAULT_APPLICATIONS").String() == "" {
  105. OAuth2.DefaultApplications = nil
  106. }
  107. // Handle the rename of ENABLE to ENABLED
  108. deprecatedSetting(rootCfg, "oauth2", "ENABLE", "oauth2", "ENABLED", "v1.23.0")
  109. if sec.HasKey("ENABLE") && !sec.HasKey("ENABLED") {
  110. OAuth2.Enabled = sec.Key("ENABLE").MustBool(OAuth2.Enabled)
  111. }
  112. if !filepath.IsAbs(OAuth2.JWTSigningPrivateKeyFile) {
  113. OAuth2.JWTSigningPrivateKeyFile = filepath.Join(AppDataPath, OAuth2.JWTSigningPrivateKeyFile)
  114. }
  115. // FIXME: at the moment, no matter oauth2 is enabled or not, it must generate a "oauth2 JWT_SECRET"
  116. // Because this secret is also used as GeneralTokenSigningSecret (as a quick not-that-breaking fix for some legacy problems).
  117. // Including: CSRF token, account validation token, etc ...
  118. // In main branch, the signing token should be refactored (eg: one unique for LFS/OAuth2/etc ...)
  119. jwtSecretBase64 := loadSecret(sec, "JWT_SECRET_URI", "JWT_SECRET")
  120. if InstallLock {
  121. jwtSecretBytes, err := generate.DecodeJwtSecretBase64(jwtSecretBase64)
  122. if err != nil {
  123. jwtSecretBytes, jwtSecretBase64, err = generate.NewJwtSecretWithBase64()
  124. if err != nil {
  125. log.Fatal("error generating JWT secret: %v", err)
  126. }
  127. saveCfg, err := rootCfg.PrepareSaving()
  128. if err != nil {
  129. log.Fatal("save oauth2.JWT_SECRET failed: %v", err)
  130. }
  131. rootCfg.Section("oauth2").Key("JWT_SECRET").SetValue(jwtSecretBase64)
  132. saveCfg.Section("oauth2").Key("JWT_SECRET").SetValue(jwtSecretBase64)
  133. if err := saveCfg.Save(); err != nil {
  134. log.Fatal("save oauth2.JWT_SECRET failed: %v", err)
  135. }
  136. }
  137. generalSigningSecret.Store(&jwtSecretBytes)
  138. }
  139. }
  140. var generalSigningSecret atomic.Pointer[[]byte]
  141. func GetGeneralTokenSigningSecret() []byte {
  142. old := generalSigningSecret.Load()
  143. if old == nil || len(*old) == 0 {
  144. jwtSecret, _, err := generate.NewJwtSecretWithBase64()
  145. if err != nil {
  146. log.Fatal("Unable to generate general JWT secret: %v", err)
  147. }
  148. if generalSigningSecret.CompareAndSwap(old, &jwtSecret) {
  149. return jwtSecret
  150. }
  151. return *generalSigningSecret.Load()
  152. }
  153. return *old
  154. }