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.

ssh_key_deploy.go 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "fmt"
  7. "time"
  8. "code.gitea.io/gitea/modules/timeutil"
  9. "xorm.io/builder"
  10. "xorm.io/xorm"
  11. )
  12. // ________ .__ ____ __.
  13. // \______ \ ____ ______ | | ____ ___.__.| |/ _|____ ___.__.
  14. // | | \_/ __ \\____ \| | / _ < | || <_/ __ < | |
  15. // | ` \ ___/| |_> > |_( <_> )___ || | \ ___/\___ |
  16. // /_______ /\___ > __/|____/\____// ____||____|__ \___ > ____|
  17. // \/ \/|__| \/ \/ \/\/
  18. //
  19. // This file contains functions specific to DeployKeys
  20. // DeployKey represents deploy key information and its relation with repository.
  21. type DeployKey struct {
  22. ID int64 `xorm:"pk autoincr"`
  23. KeyID int64 `xorm:"UNIQUE(s) INDEX"`
  24. RepoID int64 `xorm:"UNIQUE(s) INDEX"`
  25. Name string
  26. Fingerprint string
  27. Content string `xorm:"-"`
  28. Mode AccessMode `xorm:"NOT NULL DEFAULT 1"`
  29. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  30. UpdatedUnix timeutil.TimeStamp `xorm:"updated"`
  31. HasRecentActivity bool `xorm:"-"`
  32. HasUsed bool `xorm:"-"`
  33. }
  34. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  35. func (key *DeployKey) AfterLoad() {
  36. key.HasUsed = key.UpdatedUnix > key.CreatedUnix
  37. key.HasRecentActivity = key.UpdatedUnix.AddDuration(7*24*time.Hour) > timeutil.TimeStampNow()
  38. }
  39. // GetContent gets associated public key content.
  40. func (key *DeployKey) GetContent() error {
  41. pkey, err := GetPublicKeyByID(key.KeyID)
  42. if err != nil {
  43. return err
  44. }
  45. key.Content = pkey.Content
  46. return nil
  47. }
  48. // IsReadOnly checks if the key can only be used for read operations
  49. func (key *DeployKey) IsReadOnly() bool {
  50. return key.Mode == AccessModeRead
  51. }
  52. func checkDeployKey(e Engine, keyID, repoID int64, name string) error {
  53. // Note: We want error detail, not just true or false here.
  54. has, err := e.
  55. Where("key_id = ? AND repo_id = ?", keyID, repoID).
  56. Get(new(DeployKey))
  57. if err != nil {
  58. return err
  59. } else if has {
  60. return ErrDeployKeyAlreadyExist{keyID, repoID}
  61. }
  62. has, err = e.
  63. Where("repo_id = ? AND name = ?", repoID, name).
  64. Get(new(DeployKey))
  65. if err != nil {
  66. return err
  67. } else if has {
  68. return ErrDeployKeyNameAlreadyUsed{repoID, name}
  69. }
  70. return nil
  71. }
  72. // addDeployKey adds new key-repo relation.
  73. func addDeployKey(e *xorm.Session, keyID, repoID int64, name, fingerprint string, mode AccessMode) (*DeployKey, error) {
  74. if err := checkDeployKey(e, keyID, repoID, name); err != nil {
  75. return nil, err
  76. }
  77. key := &DeployKey{
  78. KeyID: keyID,
  79. RepoID: repoID,
  80. Name: name,
  81. Fingerprint: fingerprint,
  82. Mode: mode,
  83. }
  84. _, err := e.Insert(key)
  85. return key, err
  86. }
  87. // HasDeployKey returns true if public key is a deploy key of given repository.
  88. func HasDeployKey(keyID, repoID int64) bool {
  89. has, _ := x.
  90. Where("key_id = ? AND repo_id = ?", keyID, repoID).
  91. Get(new(DeployKey))
  92. return has
  93. }
  94. // AddDeployKey add new deploy key to database and authorized_keys file.
  95. func AddDeployKey(repoID int64, name, content string, readOnly bool) (*DeployKey, error) {
  96. fingerprint, err := calcFingerprint(content)
  97. if err != nil {
  98. return nil, err
  99. }
  100. accessMode := AccessModeRead
  101. if !readOnly {
  102. accessMode = AccessModeWrite
  103. }
  104. sess := x.NewSession()
  105. defer sess.Close()
  106. if err = sess.Begin(); err != nil {
  107. return nil, err
  108. }
  109. pkey := &PublicKey{
  110. Fingerprint: fingerprint,
  111. }
  112. has, err := sess.Get(pkey)
  113. if err != nil {
  114. return nil, err
  115. }
  116. if has {
  117. if pkey.Type != KeyTypeDeploy {
  118. return nil, ErrKeyAlreadyExist{0, fingerprint, ""}
  119. }
  120. } else {
  121. // First time use this deploy key.
  122. pkey.Mode = accessMode
  123. pkey.Type = KeyTypeDeploy
  124. pkey.Content = content
  125. pkey.Name = name
  126. if err = addKey(sess, pkey); err != nil {
  127. return nil, fmt.Errorf("addKey: %v", err)
  128. }
  129. }
  130. key, err := addDeployKey(sess, pkey.ID, repoID, name, pkey.Fingerprint, accessMode)
  131. if err != nil {
  132. return nil, err
  133. }
  134. return key, sess.Commit()
  135. }
  136. // GetDeployKeyByID returns deploy key by given ID.
  137. func GetDeployKeyByID(id int64) (*DeployKey, error) {
  138. return getDeployKeyByID(x, id)
  139. }
  140. func getDeployKeyByID(e Engine, id int64) (*DeployKey, error) {
  141. key := new(DeployKey)
  142. has, err := e.ID(id).Get(key)
  143. if err != nil {
  144. return nil, err
  145. } else if !has {
  146. return nil, ErrDeployKeyNotExist{id, 0, 0}
  147. }
  148. return key, nil
  149. }
  150. // GetDeployKeyByRepo returns deploy key by given public key ID and repository ID.
  151. func GetDeployKeyByRepo(keyID, repoID int64) (*DeployKey, error) {
  152. return getDeployKeyByRepo(x, keyID, repoID)
  153. }
  154. func getDeployKeyByRepo(e Engine, keyID, repoID int64) (*DeployKey, error) {
  155. key := &DeployKey{
  156. KeyID: keyID,
  157. RepoID: repoID,
  158. }
  159. has, err := e.Get(key)
  160. if err != nil {
  161. return nil, err
  162. } else if !has {
  163. return nil, ErrDeployKeyNotExist{0, keyID, repoID}
  164. }
  165. return key, nil
  166. }
  167. // UpdateDeployKeyCols updates deploy key information in the specified columns.
  168. func UpdateDeployKeyCols(key *DeployKey, cols ...string) error {
  169. _, err := x.ID(key.ID).Cols(cols...).Update(key)
  170. return err
  171. }
  172. // UpdateDeployKey updates deploy key information.
  173. func UpdateDeployKey(key *DeployKey) error {
  174. _, err := x.ID(key.ID).AllCols().Update(key)
  175. return err
  176. }
  177. // DeleteDeployKey deletes deploy key from its repository authorized_keys file if needed.
  178. func DeleteDeployKey(doer *User, id int64) error {
  179. sess := x.NewSession()
  180. defer sess.Close()
  181. if err := sess.Begin(); err != nil {
  182. return err
  183. }
  184. if err := deleteDeployKey(sess, doer, id); err != nil {
  185. return err
  186. }
  187. return sess.Commit()
  188. }
  189. func deleteDeployKey(sess Engine, doer *User, id int64) error {
  190. key, err := getDeployKeyByID(sess, id)
  191. if err != nil {
  192. if IsErrDeployKeyNotExist(err) {
  193. return nil
  194. }
  195. return fmt.Errorf("GetDeployKeyByID: %v", err)
  196. }
  197. // Check if user has access to delete this key.
  198. if !doer.IsAdmin {
  199. repo, err := getRepositoryByID(sess, key.RepoID)
  200. if err != nil {
  201. return fmt.Errorf("GetRepositoryByID: %v", err)
  202. }
  203. has, err := isUserRepoAdmin(sess, repo, doer)
  204. if err != nil {
  205. return fmt.Errorf("GetUserRepoPermission: %v", err)
  206. } else if !has {
  207. return ErrKeyAccessDenied{doer.ID, key.ID, "deploy"}
  208. }
  209. }
  210. if _, err = sess.ID(key.ID).Delete(new(DeployKey)); err != nil {
  211. return fmt.Errorf("delete deploy key [%d]: %v", key.ID, err)
  212. }
  213. // Check if this is the last reference to same key content.
  214. has, err := sess.
  215. Where("key_id = ?", key.KeyID).
  216. Get(new(DeployKey))
  217. if err != nil {
  218. return err
  219. } else if !has {
  220. if err = deletePublicKeys(sess, key.KeyID); err != nil {
  221. return err
  222. }
  223. // after deleted the public keys, should rewrite the public keys file
  224. if err = rewriteAllPublicKeys(sess); err != nil {
  225. return err
  226. }
  227. }
  228. return nil
  229. }
  230. // ListDeployKeysOptions are options for ListDeployKeys
  231. type ListDeployKeysOptions struct {
  232. ListOptions
  233. RepoID int64
  234. KeyID int64
  235. Fingerprint string
  236. }
  237. func (opt ListDeployKeysOptions) toCond() builder.Cond {
  238. cond := builder.NewCond()
  239. if opt.RepoID != 0 {
  240. cond = cond.And(builder.Eq{"repo_id": opt.RepoID})
  241. }
  242. if opt.KeyID != 0 {
  243. cond = cond.And(builder.Eq{"key_id": opt.KeyID})
  244. }
  245. if opt.Fingerprint != "" {
  246. cond = cond.And(builder.Eq{"fingerprint": opt.Fingerprint})
  247. }
  248. return cond
  249. }
  250. // ListDeployKeys returns a list of deploy keys matching the provided arguments.
  251. func ListDeployKeys(opts *ListDeployKeysOptions) ([]*DeployKey, error) {
  252. return listDeployKeys(x, opts)
  253. }
  254. func listDeployKeys(e Engine, opts *ListDeployKeysOptions) ([]*DeployKey, error) {
  255. sess := e.Where(opts.toCond())
  256. if opts.Page != 0 {
  257. sess = opts.setSessionPagination(sess)
  258. keys := make([]*DeployKey, 0, opts.PageSize)
  259. return keys, sess.Find(&keys)
  260. }
  261. keys := make([]*DeployKey, 0, 5)
  262. return keys, sess.Find(&keys)
  263. }
  264. // CountDeployKeys returns count deploy keys matching the provided arguments.
  265. func CountDeployKeys(opts *ListDeployKeysOptions) (int64, error) {
  266. return x.Where(opts.toCond()).Count(&DeployKey{})
  267. }