gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package auth
  5. import (
  6. "context"
  7. "fmt"
  8. "reflect"
  9. "code.gitea.io/gitea/models/db"
  10. "code.gitea.io/gitea/modules/log"
  11. "code.gitea.io/gitea/modules/optional"
  12. "code.gitea.io/gitea/modules/timeutil"
  13. "code.gitea.io/gitea/modules/util"
  14. "xorm.io/builder"
  15. "xorm.io/xorm"
  16. "xorm.io/xorm/convert"
  17. )
  18. // Type represents an login type.
  19. type Type int
  20. // Note: new type must append to the end of list to maintain compatibility.
  21. const (
  22. NoType Type = iota
  23. Plain // 1
  24. LDAP // 2
  25. SMTP // 3
  26. PAM // 4
  27. DLDAP // 5
  28. OAuth2 // 6
  29. SSPI // 7
  30. )
  31. // String returns the string name of the LoginType
  32. func (typ Type) String() string {
  33. return Names[typ]
  34. }
  35. // Int returns the int value of the LoginType
  36. func (typ Type) Int() int {
  37. return int(typ)
  38. }
  39. // Names contains the name of LoginType values.
  40. var Names = map[Type]string{
  41. LDAP: "LDAP (via BindDN)",
  42. DLDAP: "LDAP (simple auth)", // Via direct bind
  43. SMTP: "SMTP",
  44. PAM: "PAM",
  45. OAuth2: "OAuth2",
  46. SSPI: "SPNEGO with SSPI",
  47. }
  48. // Config represents login config as far as the db is concerned
  49. type Config interface {
  50. convert.Conversion
  51. SetAuthSource(*Source)
  52. }
  53. type ConfigBase struct {
  54. AuthSource *Source
  55. }
  56. func (p *ConfigBase) SetAuthSource(s *Source) {
  57. p.AuthSource = s
  58. }
  59. // SkipVerifiable configurations provide a IsSkipVerify to check if SkipVerify is set
  60. type SkipVerifiable interface {
  61. IsSkipVerify() bool
  62. }
  63. // HasTLSer configurations provide a HasTLS to check if TLS can be enabled
  64. type HasTLSer interface {
  65. HasTLS() bool
  66. }
  67. // UseTLSer configurations provide a HasTLS to check if TLS is enabled
  68. type UseTLSer interface {
  69. UseTLS() bool
  70. }
  71. // SSHKeyProvider configurations provide ProvidesSSHKeys to check if they provide SSHKeys
  72. type SSHKeyProvider interface {
  73. ProvidesSSHKeys() bool
  74. }
  75. // RegisterableSource configurations provide RegisterSource which needs to be run on creation
  76. type RegisterableSource interface {
  77. RegisterSource() error
  78. UnregisterSource() error
  79. }
  80. var registeredConfigs = map[Type]func() Config{}
  81. // RegisterTypeConfig register a config for a provided type
  82. func RegisterTypeConfig(typ Type, exemplar Config) {
  83. if reflect.TypeOf(exemplar).Kind() == reflect.Ptr {
  84. // Pointer:
  85. registeredConfigs[typ] = func() Config {
  86. return reflect.New(reflect.ValueOf(exemplar).Elem().Type()).Interface().(Config)
  87. }
  88. return
  89. }
  90. // Not a Pointer
  91. registeredConfigs[typ] = func() Config {
  92. return reflect.New(reflect.TypeOf(exemplar)).Elem().Interface().(Config)
  93. }
  94. }
  95. // Source represents an external way for authorizing users.
  96. type Source struct {
  97. ID int64 `xorm:"pk autoincr"`
  98. Type Type
  99. Name string `xorm:"UNIQUE"`
  100. IsActive bool `xorm:"INDEX NOT NULL DEFAULT false"`
  101. IsSyncEnabled bool `xorm:"INDEX NOT NULL DEFAULT false"`
  102. TwoFactorPolicy string `xorm:"two_factor_policy NOT NULL DEFAULT ''"`
  103. Cfg Config `xorm:"TEXT"`
  104. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  105. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  106. }
  107. // TableName xorm will read the table name from this method
  108. func (Source) TableName() string {
  109. return "login_source"
  110. }
  111. func init() {
  112. db.RegisterModel(new(Source))
  113. }
  114. // BeforeSet is invoked from XORM before setting the value of a field of this object.
  115. func (source *Source) BeforeSet(colName string, val xorm.Cell) {
  116. if colName == "type" {
  117. typ := Type(db.Cell2Int64(val))
  118. constructor, ok := registeredConfigs[typ]
  119. if !ok {
  120. return
  121. }
  122. source.Cfg = constructor()
  123. source.Cfg.SetAuthSource(source)
  124. }
  125. }
  126. // TypeName return name of this login source type.
  127. func (source *Source) TypeName() string {
  128. return Names[source.Type]
  129. }
  130. // IsLDAP returns true of this source is of the LDAP type.
  131. func (source *Source) IsLDAP() bool {
  132. return source.Type == LDAP
  133. }
  134. // IsDLDAP returns true of this source is of the DLDAP type.
  135. func (source *Source) IsDLDAP() bool {
  136. return source.Type == DLDAP
  137. }
  138. // IsSMTP returns true of this source is of the SMTP type.
  139. func (source *Source) IsSMTP() bool {
  140. return source.Type == SMTP
  141. }
  142. // IsPAM returns true of this source is of the PAM type.
  143. func (source *Source) IsPAM() bool {
  144. return source.Type == PAM
  145. }
  146. // IsOAuth2 returns true of this source is of the OAuth2 type.
  147. func (source *Source) IsOAuth2() bool {
  148. return source.Type == OAuth2
  149. }
  150. // IsSSPI returns true of this source is of the SSPI type.
  151. func (source *Source) IsSSPI() bool {
  152. return source.Type == SSPI
  153. }
  154. // HasTLS returns true of this source supports TLS.
  155. func (source *Source) HasTLS() bool {
  156. hasTLSer, ok := source.Cfg.(HasTLSer)
  157. return ok && hasTLSer.HasTLS()
  158. }
  159. // UseTLS returns true of this source is configured to use TLS.
  160. func (source *Source) UseTLS() bool {
  161. useTLSer, ok := source.Cfg.(UseTLSer)
  162. return ok && useTLSer.UseTLS()
  163. }
  164. // SkipVerify returns true if this source is configured to skip SSL
  165. // verification.
  166. func (source *Source) SkipVerify() bool {
  167. skipVerifiable, ok := source.Cfg.(SkipVerifiable)
  168. return ok && skipVerifiable.IsSkipVerify()
  169. }
  170. func (source *Source) TwoFactorShouldSkip() bool {
  171. return source.TwoFactorPolicy == "skip"
  172. }
  173. // CreateSource inserts a AuthSource in the DB if not already
  174. // existing with the given name.
  175. func CreateSource(ctx context.Context, source *Source) error {
  176. has, err := db.GetEngine(ctx).Where("name=?", source.Name).Exist(new(Source))
  177. if err != nil {
  178. return err
  179. } else if has {
  180. return ErrSourceAlreadyExist{source.Name}
  181. }
  182. // Synchronization is only available with LDAP for now
  183. if !source.IsLDAP() && !source.IsOAuth2() {
  184. source.IsSyncEnabled = false
  185. }
  186. _, err = db.GetEngine(ctx).Insert(source)
  187. if err != nil {
  188. return err
  189. }
  190. if !source.IsActive {
  191. return nil
  192. }
  193. source.Cfg.SetAuthSource(source)
  194. registerableSource, ok := source.Cfg.(RegisterableSource)
  195. if !ok {
  196. return nil
  197. }
  198. err = registerableSource.RegisterSource()
  199. if err != nil {
  200. // remove the AuthSource in case of errors while registering configuration
  201. if _, err := db.GetEngine(ctx).ID(source.ID).Delete(new(Source)); err != nil {
  202. log.Error("CreateSource: Error while wrapOpenIDConnectInitializeError: %v", err)
  203. }
  204. }
  205. return err
  206. }
  207. type FindSourcesOptions struct {
  208. db.ListOptions
  209. IsActive optional.Option[bool]
  210. LoginType Type
  211. }
  212. func (opts FindSourcesOptions) ToConds() builder.Cond {
  213. conds := builder.NewCond()
  214. if opts.IsActive.Has() {
  215. conds = conds.And(builder.Eq{"is_active": opts.IsActive.Value()})
  216. }
  217. if opts.LoginType != NoType {
  218. conds = conds.And(builder.Eq{"`type`": opts.LoginType})
  219. }
  220. return conds
  221. }
  222. // IsSSPIEnabled returns true if there is at least one activated login
  223. // source of type LoginSSPI
  224. func IsSSPIEnabled(ctx context.Context) bool {
  225. exist, err := db.Exist[Source](ctx, FindSourcesOptions{
  226. IsActive: optional.Some(true),
  227. LoginType: SSPI,
  228. }.ToConds())
  229. if err != nil {
  230. log.Error("IsSSPIEnabled: failed to query active SSPI sources: %v", err)
  231. return false
  232. }
  233. return exist
  234. }
  235. // GetSourceByID returns login source by given ID.
  236. func GetSourceByID(ctx context.Context, id int64) (*Source, error) {
  237. source := new(Source)
  238. if id == 0 {
  239. source.Cfg = registeredConfigs[NoType]()
  240. // Set this source to active
  241. // FIXME: allow disabling of db based password authentication in future
  242. source.IsActive = true
  243. return source, nil
  244. }
  245. has, err := db.GetEngine(ctx).ID(id).Get(source)
  246. if err != nil {
  247. return nil, err
  248. } else if !has {
  249. return nil, ErrSourceNotExist{id}
  250. }
  251. return source, nil
  252. }
  253. // UpdateSource updates a Source record in DB.
  254. func UpdateSource(ctx context.Context, source *Source) error {
  255. var originalSource *Source
  256. if source.IsOAuth2() {
  257. // keep track of the original values so we can restore in case of errors while registering OAuth2 providers
  258. var err error
  259. if originalSource, err = GetSourceByID(ctx, source.ID); err != nil {
  260. return err
  261. }
  262. }
  263. has, err := db.GetEngine(ctx).Where("name=? AND id!=?", source.Name, source.ID).Exist(new(Source))
  264. if err != nil {
  265. return err
  266. } else if has {
  267. return ErrSourceAlreadyExist{source.Name}
  268. }
  269. _, err = db.GetEngine(ctx).ID(source.ID).AllCols().Update(source)
  270. if err != nil {
  271. return err
  272. }
  273. if !source.IsActive {
  274. return nil
  275. }
  276. source.Cfg.SetAuthSource(source)
  277. registerableSource, ok := source.Cfg.(RegisterableSource)
  278. if !ok {
  279. return nil
  280. }
  281. err = registerableSource.RegisterSource()
  282. if err != nil {
  283. // restore original values since we cannot update the provider itself
  284. if _, err := db.GetEngine(ctx).ID(source.ID).AllCols().Update(originalSource); err != nil {
  285. log.Error("UpdateSource: Error while wrapOpenIDConnectInitializeError: %v", err)
  286. }
  287. }
  288. return err
  289. }
  290. // ErrSourceNotExist represents a "SourceNotExist" kind of error.
  291. type ErrSourceNotExist struct {
  292. ID int64
  293. }
  294. // IsErrSourceNotExist checks if an error is a ErrSourceNotExist.
  295. func IsErrSourceNotExist(err error) bool {
  296. _, ok := err.(ErrSourceNotExist)
  297. return ok
  298. }
  299. func (err ErrSourceNotExist) Error() string {
  300. return fmt.Sprintf("login source does not exist [id: %d]", err.ID)
  301. }
  302. // Unwrap unwraps this as a ErrNotExist err
  303. func (err ErrSourceNotExist) Unwrap() error {
  304. return util.ErrNotExist
  305. }
  306. // ErrSourceAlreadyExist represents a "SourceAlreadyExist" kind of error.
  307. type ErrSourceAlreadyExist struct {
  308. Name string
  309. }
  310. // IsErrSourceAlreadyExist checks if an error is a ErrSourceAlreadyExist.
  311. func IsErrSourceAlreadyExist(err error) bool {
  312. _, ok := err.(ErrSourceAlreadyExist)
  313. return ok
  314. }
  315. func (err ErrSourceAlreadyExist) Error() string {
  316. return fmt.Sprintf("login source already exists [name: %s]", err.Name)
  317. }
  318. // Unwrap unwraps this as a ErrExist err
  319. func (err ErrSourceAlreadyExist) Unwrap() error {
  320. return util.ErrAlreadyExist
  321. }
  322. // ErrSourceInUse represents a "SourceInUse" kind of error.
  323. type ErrSourceInUse struct {
  324. ID int64
  325. }
  326. // IsErrSourceInUse checks if an error is a ErrSourceInUse.
  327. func IsErrSourceInUse(err error) bool {
  328. _, ok := err.(ErrSourceInUse)
  329. return ok
  330. }
  331. func (err ErrSourceInUse) Error() string {
  332. return fmt.Sprintf("login source is still used by some users [id: %d]", err.ID)
  333. }