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.

source.go 9.9KB

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