gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2020 The Gitea Authors.
  3. // SPDX-License-Identifier: MIT
  4. package repo
  5. import (
  6. stdCtx "context"
  7. "fmt"
  8. "net/http"
  9. "net/url"
  10. asymkey_model "code.gitea.io/gitea/models/asymkey"
  11. "code.gitea.io/gitea/models/db"
  12. "code.gitea.io/gitea/models/perm"
  13. access_model "code.gitea.io/gitea/models/perm/access"
  14. repo_model "code.gitea.io/gitea/models/repo"
  15. "code.gitea.io/gitea/modules/setting"
  16. api "code.gitea.io/gitea/modules/structs"
  17. "code.gitea.io/gitea/modules/web"
  18. "code.gitea.io/gitea/routers/api/v1/utils"
  19. asymkey_service "code.gitea.io/gitea/services/asymkey"
  20. "code.gitea.io/gitea/services/context"
  21. "code.gitea.io/gitea/services/convert"
  22. )
  23. // appendPrivateInformation appends the owner and key type information to api.PublicKey
  24. func appendPrivateInformation(ctx stdCtx.Context, apiKey *api.DeployKey, key *asymkey_model.DeployKey, repository *repo_model.Repository) (*api.DeployKey, error) {
  25. apiKey.ReadOnly = key.Mode == perm.AccessModeRead
  26. if repository.ID == key.RepoID {
  27. apiKey.Repository = convert.ToRepo(ctx, repository, access_model.Permission{AccessMode: key.Mode})
  28. } else {
  29. repo, err := repo_model.GetRepositoryByID(ctx, key.RepoID)
  30. if err != nil {
  31. return apiKey, err
  32. }
  33. apiKey.Repository = convert.ToRepo(ctx, repo, access_model.Permission{AccessMode: key.Mode})
  34. }
  35. return apiKey, nil
  36. }
  37. func composeDeployKeysAPILink(owner, name string) string {
  38. return setting.AppURL + "api/v1/repos/" + url.PathEscape(owner) + "/" + url.PathEscape(name) + "/keys/"
  39. }
  40. // ListDeployKeys list all the deploy keys of a repository
  41. func ListDeployKeys(ctx *context.APIContext) {
  42. // swagger:operation GET /repos/{owner}/{repo}/keys repository repoListKeys
  43. // ---
  44. // summary: List a repository's keys
  45. // produces:
  46. // - application/json
  47. // parameters:
  48. // - name: owner
  49. // in: path
  50. // description: owner of the repo
  51. // type: string
  52. // required: true
  53. // - name: repo
  54. // in: path
  55. // description: name of the repo
  56. // type: string
  57. // required: true
  58. // - name: key_id
  59. // in: query
  60. // description: the key_id to search for
  61. // type: integer
  62. // - name: fingerprint
  63. // in: query
  64. // description: fingerprint of the key
  65. // type: string
  66. // - name: page
  67. // in: query
  68. // description: page number of results to return (1-based)
  69. // type: integer
  70. // - name: limit
  71. // in: query
  72. // description: page size of results
  73. // type: integer
  74. // responses:
  75. // "200":
  76. // "$ref": "#/responses/DeployKeyList"
  77. // "404":
  78. // "$ref": "#/responses/notFound"
  79. opts := asymkey_model.ListDeployKeysOptions{
  80. ListOptions: utils.GetListOptions(ctx),
  81. RepoID: ctx.Repo.Repository.ID,
  82. KeyID: ctx.FormInt64("key_id"),
  83. Fingerprint: ctx.FormString("fingerprint"),
  84. }
  85. keys, count, err := db.FindAndCount[asymkey_model.DeployKey](ctx, opts)
  86. if err != nil {
  87. ctx.APIErrorInternal(err)
  88. return
  89. }
  90. apiLink := composeDeployKeysAPILink(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  91. apiKeys := make([]*api.DeployKey, len(keys))
  92. for i := range keys {
  93. if err := keys[i].GetContent(ctx); err != nil {
  94. ctx.APIErrorInternal(err)
  95. return
  96. }
  97. apiKeys[i] = convert.ToDeployKey(apiLink, keys[i])
  98. if ctx.Doer.IsAdmin || ((ctx.Repo.Repository.ID == keys[i].RepoID) && (ctx.Doer.ID == ctx.Repo.Owner.ID)) {
  99. apiKeys[i], _ = appendPrivateInformation(ctx, apiKeys[i], keys[i], ctx.Repo.Repository)
  100. }
  101. }
  102. ctx.SetTotalCountHeader(count)
  103. ctx.JSON(http.StatusOK, &apiKeys)
  104. }
  105. // GetDeployKey get a deploy key by id
  106. func GetDeployKey(ctx *context.APIContext) {
  107. // swagger:operation GET /repos/{owner}/{repo}/keys/{id} repository repoGetKey
  108. // ---
  109. // summary: Get a repository's key by id
  110. // produces:
  111. // - application/json
  112. // parameters:
  113. // - name: owner
  114. // in: path
  115. // description: owner of the repo
  116. // type: string
  117. // required: true
  118. // - name: repo
  119. // in: path
  120. // description: name of the repo
  121. // type: string
  122. // required: true
  123. // - name: id
  124. // in: path
  125. // description: id of the key to get
  126. // type: integer
  127. // format: int64
  128. // required: true
  129. // responses:
  130. // "200":
  131. // "$ref": "#/responses/DeployKey"
  132. // "404":
  133. // "$ref": "#/responses/notFound"
  134. key, err := asymkey_model.GetDeployKeyByID(ctx, ctx.PathParamInt64("id"))
  135. if err != nil {
  136. if asymkey_model.IsErrDeployKeyNotExist(err) {
  137. ctx.APIErrorNotFound()
  138. } else {
  139. ctx.APIErrorInternal(err)
  140. }
  141. return
  142. }
  143. // this check make it more consistent
  144. if key.RepoID != ctx.Repo.Repository.ID {
  145. ctx.APIErrorNotFound()
  146. return
  147. }
  148. if err = key.GetContent(ctx); err != nil {
  149. ctx.APIErrorInternal(err)
  150. return
  151. }
  152. apiLink := composeDeployKeysAPILink(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  153. apiKey := convert.ToDeployKey(apiLink, key)
  154. if ctx.Doer.IsAdmin || ((ctx.Repo.Repository.ID == key.RepoID) && (ctx.Doer.ID == ctx.Repo.Owner.ID)) {
  155. apiKey, _ = appendPrivateInformation(ctx, apiKey, key, ctx.Repo.Repository)
  156. }
  157. ctx.JSON(http.StatusOK, apiKey)
  158. }
  159. // HandleCheckKeyStringError handle check key error
  160. func HandleCheckKeyStringError(ctx *context.APIContext, err error) {
  161. if db.IsErrSSHDisabled(err) {
  162. ctx.APIError(http.StatusUnprocessableEntity, "SSH is disabled")
  163. } else if asymkey_model.IsErrKeyUnableVerify(err) {
  164. ctx.APIError(http.StatusUnprocessableEntity, "Unable to verify key content")
  165. } else {
  166. ctx.APIError(http.StatusUnprocessableEntity, fmt.Errorf("Invalid key content: %w", err))
  167. }
  168. }
  169. // HandleAddKeyError handle add key error
  170. func HandleAddKeyError(ctx *context.APIContext, err error) {
  171. switch {
  172. case asymkey_model.IsErrDeployKeyAlreadyExist(err):
  173. ctx.APIError(http.StatusUnprocessableEntity, "This key has already been added to this repository")
  174. case asymkey_model.IsErrKeyAlreadyExist(err):
  175. ctx.APIError(http.StatusUnprocessableEntity, "Key content has been used as non-deploy key")
  176. case asymkey_model.IsErrKeyNameAlreadyUsed(err):
  177. ctx.APIError(http.StatusUnprocessableEntity, "Key title has been used")
  178. case asymkey_model.IsErrDeployKeyNameAlreadyUsed(err):
  179. ctx.APIError(http.StatusUnprocessableEntity, "A key with the same name already exists")
  180. default:
  181. ctx.APIErrorInternal(err)
  182. }
  183. }
  184. // CreateDeployKey create deploy key for a repository
  185. func CreateDeployKey(ctx *context.APIContext) {
  186. // swagger:operation POST /repos/{owner}/{repo}/keys repository repoCreateKey
  187. // ---
  188. // summary: Add a key to a repository
  189. // consumes:
  190. // - application/json
  191. // produces:
  192. // - application/json
  193. // parameters:
  194. // - name: owner
  195. // in: path
  196. // description: owner of the repo
  197. // type: string
  198. // required: true
  199. // - name: repo
  200. // in: path
  201. // description: name of the repo
  202. // type: string
  203. // required: true
  204. // - name: body
  205. // in: body
  206. // schema:
  207. // "$ref": "#/definitions/CreateKeyOption"
  208. // responses:
  209. // "201":
  210. // "$ref": "#/responses/DeployKey"
  211. // "404":
  212. // "$ref": "#/responses/notFound"
  213. // "422":
  214. // "$ref": "#/responses/validationError"
  215. form := web.GetForm(ctx).(*api.CreateKeyOption)
  216. content, err := asymkey_model.CheckPublicKeyString(form.Key)
  217. if err != nil {
  218. HandleCheckKeyStringError(ctx, err)
  219. return
  220. }
  221. key, err := asymkey_model.AddDeployKey(ctx, ctx.Repo.Repository.ID, form.Title, content, form.ReadOnly)
  222. if err != nil {
  223. HandleAddKeyError(ctx, err)
  224. return
  225. }
  226. key.Content = content
  227. apiLink := composeDeployKeysAPILink(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  228. ctx.JSON(http.StatusCreated, convert.ToDeployKey(apiLink, key))
  229. }
  230. // DeleteDeploykey delete deploy key for a repository
  231. func DeleteDeploykey(ctx *context.APIContext) {
  232. // swagger:operation DELETE /repos/{owner}/{repo}/keys/{id} repository repoDeleteKey
  233. // ---
  234. // summary: Delete a key from a repository
  235. // parameters:
  236. // - name: owner
  237. // in: path
  238. // description: owner of the repo
  239. // type: string
  240. // required: true
  241. // - name: repo
  242. // in: path
  243. // description: name of the repo
  244. // type: string
  245. // required: true
  246. // - name: id
  247. // in: path
  248. // description: id of the key to delete
  249. // type: integer
  250. // format: int64
  251. // required: true
  252. // responses:
  253. // "204":
  254. // "$ref": "#/responses/empty"
  255. // "403":
  256. // "$ref": "#/responses/forbidden"
  257. // "404":
  258. // "$ref": "#/responses/notFound"
  259. if err := asymkey_service.DeleteDeployKey(ctx, ctx.Repo.Repository, ctx.PathParamInt64("id")); err != nil {
  260. if asymkey_model.IsErrKeyAccessDenied(err) {
  261. ctx.APIError(http.StatusForbidden, "You do not have access to this key")
  262. } else {
  263. ctx.APIErrorInternal(err)
  264. }
  265. return
  266. }
  267. ctx.Status(http.StatusNoContent)
  268. }