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.

key.go 8.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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/context"
  16. "code.gitea.io/gitea/modules/setting"
  17. api "code.gitea.io/gitea/modules/structs"
  18. "code.gitea.io/gitea/modules/web"
  19. "code.gitea.io/gitea/routers/api/v1/utils"
  20. asymkey_service "code.gitea.io/gitea/services/asymkey"
  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, err := asymkey_model.ListDeployKeys(ctx, opts)
  86. if err != nil {
  87. ctx.InternalServerError(err)
  88. return
  89. }
  90. count, err := asymkey_model.CountDeployKeys(opts)
  91. if err != nil {
  92. ctx.InternalServerError(err)
  93. return
  94. }
  95. apiLink := composeDeployKeysAPILink(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  96. apiKeys := make([]*api.DeployKey, len(keys))
  97. for i := range keys {
  98. if err := keys[i].GetContent(); err != nil {
  99. ctx.Error(http.StatusInternalServerError, "GetContent", err)
  100. return
  101. }
  102. apiKeys[i] = convert.ToDeployKey(apiLink, keys[i])
  103. if ctx.Doer.IsAdmin || ((ctx.Repo.Repository.ID == keys[i].RepoID) && (ctx.Doer.ID == ctx.Repo.Owner.ID)) {
  104. apiKeys[i], _ = appendPrivateInformation(ctx, apiKeys[i], keys[i], ctx.Repo.Repository)
  105. }
  106. }
  107. ctx.SetTotalCountHeader(count)
  108. ctx.JSON(http.StatusOK, &apiKeys)
  109. }
  110. // GetDeployKey get a deploy key by id
  111. func GetDeployKey(ctx *context.APIContext) {
  112. // swagger:operation GET /repos/{owner}/{repo}/keys/{id} repository repoGetKey
  113. // ---
  114. // summary: Get a repository's key by id
  115. // produces:
  116. // - application/json
  117. // parameters:
  118. // - name: owner
  119. // in: path
  120. // description: owner of the repo
  121. // type: string
  122. // required: true
  123. // - name: repo
  124. // in: path
  125. // description: name of the repo
  126. // type: string
  127. // required: true
  128. // - name: id
  129. // in: path
  130. // description: id of the key to get
  131. // type: integer
  132. // format: int64
  133. // required: true
  134. // responses:
  135. // "200":
  136. // "$ref": "#/responses/DeployKey"
  137. // "404":
  138. // "$ref": "#/responses/notFound"
  139. key, err := asymkey_model.GetDeployKeyByID(ctx, ctx.ParamsInt64(":id"))
  140. if err != nil {
  141. if asymkey_model.IsErrDeployKeyNotExist(err) {
  142. ctx.NotFound()
  143. } else {
  144. ctx.Error(http.StatusInternalServerError, "GetDeployKeyByID", err)
  145. }
  146. return
  147. }
  148. if err = key.GetContent(); err != nil {
  149. ctx.Error(http.StatusInternalServerError, "GetContent", 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.Error(http.StatusUnprocessableEntity, "", "SSH is disabled")
  163. } else if asymkey_model.IsErrKeyUnableVerify(err) {
  164. ctx.Error(http.StatusUnprocessableEntity, "", "Unable to verify key content")
  165. } else {
  166. ctx.Error(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.Error(http.StatusUnprocessableEntity, "", "This key has already been added to this repository")
  174. case asymkey_model.IsErrKeyAlreadyExist(err):
  175. ctx.Error(http.StatusUnprocessableEntity, "", "Key content has been used as non-deploy key")
  176. case asymkey_model.IsErrKeyNameAlreadyUsed(err):
  177. ctx.Error(http.StatusUnprocessableEntity, "", "Key title has been used")
  178. case asymkey_model.IsErrDeployKeyNameAlreadyUsed(err):
  179. ctx.Error(http.StatusUnprocessableEntity, "", "A key with the same name already exists")
  180. default:
  181. ctx.Error(http.StatusInternalServerError, "AddKey", 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.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.Doer, ctx.ParamsInt64(":id")); err != nil {
  260. if asymkey_model.IsErrKeyAccessDenied(err) {
  261. ctx.Error(http.StatusForbidden, "", "You do not have access to this key")
  262. } else {
  263. ctx.Error(http.StatusInternalServerError, "DeleteDeployKey", err)
  264. }
  265. return
  266. }
  267. ctx.Status(http.StatusNoContent)
  268. }