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 10.0KB

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