You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

oauth2.go 6.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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 'name' should be generated from oauth2 data
  12. type OAuth2UsernameType string
  13. const (
  14. // OAuth2UsernameUserid oauth2 userid field will be used as gitea name
  15. OAuth2UsernameUserid OAuth2UsernameType = "userid"
  16. // OAuth2UsernameNickname oauth2 nickname field will be used as gitea name
  17. OAuth2UsernameNickname OAuth2UsernameType = "nickname"
  18. // OAuth2UsernameEmail username of oauth2 email field will be used as gitea name
  19. OAuth2UsernameEmail OAuth2UsernameType = "email"
  20. // OAuth2UsernameEmail username of oauth2 preferred_username field will be used as gitea name
  21. OAuth2UsernamePreferredUsername OAuth2UsernameType = "preferred_username"
  22. )
  23. func (username OAuth2UsernameType) isValid() bool {
  24. switch username {
  25. case OAuth2UsernameUserid, OAuth2UsernameNickname, OAuth2UsernameEmail, OAuth2UsernamePreferredUsername:
  26. return true
  27. }
  28. return false
  29. }
  30. // OAuth2AccountLinkingType is enum describing behaviour of linking with existing account
  31. type OAuth2AccountLinkingType string
  32. const (
  33. // OAuth2AccountLinkingDisabled error will be displayed if account exist
  34. OAuth2AccountLinkingDisabled OAuth2AccountLinkingType = "disabled"
  35. // OAuth2AccountLinkingLogin account linking login will be displayed if account exist
  36. OAuth2AccountLinkingLogin OAuth2AccountLinkingType = "login"
  37. // OAuth2AccountLinkingAuto account will be automatically linked if account exist
  38. OAuth2AccountLinkingAuto OAuth2AccountLinkingType = "auto"
  39. )
  40. func (accountLinking OAuth2AccountLinkingType) isValid() bool {
  41. switch accountLinking {
  42. case OAuth2AccountLinkingDisabled, OAuth2AccountLinkingLogin, OAuth2AccountLinkingAuto:
  43. return true
  44. }
  45. return false
  46. }
  47. // OAuth2Client settings
  48. var OAuth2Client struct {
  49. RegisterEmailConfirm bool
  50. OpenIDConnectScopes []string
  51. EnableAutoRegistration bool
  52. Username OAuth2UsernameType
  53. UpdateAvatar bool
  54. AccountLinking OAuth2AccountLinkingType
  55. }
  56. func loadOAuth2ClientFrom(rootCfg ConfigProvider) {
  57. sec := rootCfg.Section("oauth2_client")
  58. OAuth2Client.RegisterEmailConfirm = sec.Key("REGISTER_EMAIL_CONFIRM").MustBool(Service.RegisterEmailConfirm)
  59. OAuth2Client.OpenIDConnectScopes = parseScopes(sec, "OPENID_CONNECT_SCOPES")
  60. OAuth2Client.EnableAutoRegistration = sec.Key("ENABLE_AUTO_REGISTRATION").MustBool()
  61. OAuth2Client.Username = OAuth2UsernameType(sec.Key("USERNAME").MustString(string(OAuth2UsernameNickname)))
  62. if !OAuth2Client.Username.isValid() {
  63. log.Warn("Username setting is not valid: '%s', will fallback to '%s'", OAuth2Client.Username, OAuth2UsernameNickname)
  64. OAuth2Client.Username = OAuth2UsernameNickname
  65. }
  66. OAuth2Client.UpdateAvatar = sec.Key("UPDATE_AVATAR").MustBool()
  67. OAuth2Client.AccountLinking = OAuth2AccountLinkingType(sec.Key("ACCOUNT_LINKING").MustString(string(OAuth2AccountLinkingLogin)))
  68. if !OAuth2Client.AccountLinking.isValid() {
  69. log.Warn("Account linking setting is not valid: '%s', will fallback to '%s'", OAuth2Client.AccountLinking, OAuth2AccountLinkingLogin)
  70. OAuth2Client.AccountLinking = OAuth2AccountLinkingLogin
  71. }
  72. }
  73. func parseScopes(sec ConfigSection, name string) []string {
  74. parts := sec.Key(name).Strings(" ")
  75. scopes := make([]string, 0, len(parts))
  76. for _, scope := range parts {
  77. if scope != "" {
  78. scopes = append(scopes, scope)
  79. }
  80. }
  81. return scopes
  82. }
  83. var OAuth2 = struct {
  84. Enabled bool
  85. AccessTokenExpirationTime int64
  86. RefreshTokenExpirationTime int64
  87. InvalidateRefreshTokens bool
  88. JWTSigningAlgorithm string `ini:"JWT_SIGNING_ALGORITHM"`
  89. JWTSigningPrivateKeyFile string `ini:"JWT_SIGNING_PRIVATE_KEY_FILE"`
  90. MaxTokenLength int
  91. DefaultApplications []string
  92. }{
  93. Enabled: true,
  94. AccessTokenExpirationTime: 3600,
  95. RefreshTokenExpirationTime: 730,
  96. InvalidateRefreshTokens: false,
  97. JWTSigningAlgorithm: "RS256",
  98. JWTSigningPrivateKeyFile: "jwt/private.pem",
  99. MaxTokenLength: math.MaxInt16,
  100. DefaultApplications: []string{"git-credential-oauth", "git-credential-manager", "tea"},
  101. }
  102. func loadOAuth2From(rootCfg ConfigProvider) {
  103. sec := rootCfg.Section("oauth2")
  104. if err := sec.MapTo(&OAuth2); err != nil {
  105. log.Fatal("Failed to map OAuth2 settings: %v", err)
  106. return
  107. }
  108. if sec.HasKey("DEFAULT_APPLICATIONS") && sec.Key("DEFAULT_APPLICATIONS").String() == "" {
  109. OAuth2.DefaultApplications = nil
  110. }
  111. // Handle the rename of ENABLE to ENABLED
  112. deprecatedSetting(rootCfg, "oauth2", "ENABLE", "oauth2", "ENABLED", "v1.23.0")
  113. if sec.HasKey("ENABLE") && !sec.HasKey("ENABLED") {
  114. OAuth2.Enabled = sec.Key("ENABLE").MustBool(OAuth2.Enabled)
  115. }
  116. if !OAuth2.Enabled {
  117. return
  118. }
  119. jwtSecretBase64 := loadSecret(sec, "JWT_SECRET_URI", "JWT_SECRET")
  120. if !filepath.IsAbs(OAuth2.JWTSigningPrivateKeyFile) {
  121. OAuth2.JWTSigningPrivateKeyFile = filepath.Join(AppDataPath, OAuth2.JWTSigningPrivateKeyFile)
  122. }
  123. if InstallLock {
  124. jwtSecretBytes, err := generate.DecodeJwtSecretBase64(jwtSecretBase64)
  125. if err != nil {
  126. jwtSecretBytes, jwtSecretBase64, err = generate.NewJwtSecretWithBase64()
  127. if err != nil {
  128. log.Fatal("error generating JWT secret: %v", err)
  129. }
  130. saveCfg, err := rootCfg.PrepareSaving()
  131. if err != nil {
  132. log.Fatal("save oauth2.JWT_SECRET failed: %v", err)
  133. }
  134. rootCfg.Section("oauth2").Key("JWT_SECRET").SetValue(jwtSecretBase64)
  135. saveCfg.Section("oauth2").Key("JWT_SECRET").SetValue(jwtSecretBase64)
  136. if err := saveCfg.Save(); err != nil {
  137. log.Fatal("save oauth2.JWT_SECRET failed: %v", err)
  138. }
  139. }
  140. generalSigningSecret.Store(&jwtSecretBytes)
  141. }
  142. }
  143. // generalSigningSecret is used as container for a []byte value
  144. // instead of an additional mutex, we use CompareAndSwap func to change the value thread save
  145. var generalSigningSecret atomic.Pointer[[]byte]
  146. func GetGeneralTokenSigningSecret() []byte {
  147. old := generalSigningSecret.Load()
  148. if old == nil || len(*old) == 0 {
  149. jwtSecret, _, err := generate.NewJwtSecretWithBase64()
  150. if err != nil {
  151. log.Fatal("Unable to generate general JWT secret: %s", err.Error())
  152. }
  153. if generalSigningSecret.CompareAndSwap(old, &jwtSecret) {
  154. // FIXME: in main branch, the signing token should be refactored (eg: one unique for LFS/OAuth2/etc ...)
  155. logStartupProblem(1, log.WARN, "OAuth2 is not enabled, unable to use a persistent signing secret, a new one is generated, which is not persistent between restarts and cluster nodes")
  156. return jwtSecret
  157. }
  158. return *generalSigningSecret.Load()
  159. }
  160. return *old
  161. }