gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package private
  4. import (
  5. "fmt"
  6. "net/http"
  7. "strings"
  8. asymkey_model "code.gitea.io/gitea/models/asymkey"
  9. "code.gitea.io/gitea/models/perm"
  10. access_model "code.gitea.io/gitea/models/perm/access"
  11. repo_model "code.gitea.io/gitea/models/repo"
  12. "code.gitea.io/gitea/models/unit"
  13. user_model "code.gitea.io/gitea/models/user"
  14. "code.gitea.io/gitea/modules/git"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/private"
  17. "code.gitea.io/gitea/modules/setting"
  18. "code.gitea.io/gitea/services/context"
  19. repo_service "code.gitea.io/gitea/services/repository"
  20. wiki_service "code.gitea.io/gitea/services/wiki"
  21. )
  22. // ServNoCommand returns information about the provided keyid
  23. func ServNoCommand(ctx *context.PrivateContext) {
  24. keyID := ctx.PathParamInt64("keyid")
  25. if keyID <= 0 {
  26. ctx.JSON(http.StatusBadRequest, private.Response{
  27. UserMsg: fmt.Sprintf("Bad key id: %d", keyID),
  28. })
  29. }
  30. results := private.KeyAndOwner{}
  31. key, err := asymkey_model.GetPublicKeyByID(ctx, keyID)
  32. if err != nil {
  33. if asymkey_model.IsErrKeyNotExist(err) {
  34. ctx.JSON(http.StatusUnauthorized, private.Response{
  35. UserMsg: fmt.Sprintf("Cannot find key: %d", keyID),
  36. })
  37. return
  38. }
  39. log.Error("Unable to get public key: %d Error: %v", keyID, err)
  40. ctx.JSON(http.StatusInternalServerError, private.Response{
  41. Err: err.Error(),
  42. })
  43. return
  44. }
  45. results.Key = key
  46. if key.Type == asymkey_model.KeyTypeUser || key.Type == asymkey_model.KeyTypePrincipal {
  47. user, err := user_model.GetUserByID(ctx, key.OwnerID)
  48. if err != nil {
  49. if user_model.IsErrUserNotExist(err) {
  50. ctx.JSON(http.StatusUnauthorized, private.Response{
  51. UserMsg: fmt.Sprintf("Cannot find owner with id: %d for key: %d", key.OwnerID, keyID),
  52. })
  53. return
  54. }
  55. log.Error("Unable to get owner with id: %d for public key: %d Error: %v", key.OwnerID, keyID, err)
  56. ctx.JSON(http.StatusInternalServerError, private.Response{
  57. Err: err.Error(),
  58. })
  59. return
  60. }
  61. if !user.IsActive || user.ProhibitLogin {
  62. ctx.JSON(http.StatusForbidden, private.Response{
  63. UserMsg: "Your account is disabled.",
  64. })
  65. return
  66. }
  67. results.Owner = user
  68. }
  69. ctx.JSON(http.StatusOK, &results)
  70. }
  71. // ServCommand returns information about the provided keyid
  72. func ServCommand(ctx *context.PrivateContext) {
  73. keyID := ctx.PathParamInt64("keyid")
  74. ownerName := ctx.PathParam("owner")
  75. repoName := ctx.PathParam("repo")
  76. mode := perm.AccessMode(ctx.FormInt("mode"))
  77. verb := ctx.FormString("verb")
  78. // Set the basic parts of the results to return
  79. results := private.ServCommandResults{
  80. RepoName: repoName,
  81. OwnerName: ownerName,
  82. KeyID: keyID,
  83. }
  84. // Now because we're not translating things properly let's just default some English strings here
  85. modeString := "read"
  86. if mode > perm.AccessModeRead {
  87. modeString = "write to"
  88. }
  89. // The default unit we're trying to look at is code
  90. unitType := unit.TypeCode
  91. // Unless we're a wiki...
  92. if strings.HasSuffix(repoName, ".wiki") {
  93. // in which case we need to look at the wiki
  94. unitType = unit.TypeWiki
  95. // And we'd better munge the reponame and tell downstream we're looking at a wiki
  96. results.IsWiki = true
  97. results.RepoName = repoName[:len(repoName)-5]
  98. }
  99. // Check if there is a user redirect for the requested owner
  100. redirectedUserID, err := user_model.LookupUserRedirect(ctx, results.OwnerName)
  101. if err == nil {
  102. owner, err := user_model.GetUserByID(ctx, redirectedUserID)
  103. if err == nil {
  104. log.Info("User %s has been redirected to %s", results.OwnerName, owner.Name)
  105. results.OwnerName = owner.Name
  106. } else {
  107. log.Warn("User %s has a redirect to user with ID %d, but no user with this ID could be found. Trying without redirect...", results.OwnerName, redirectedUserID)
  108. }
  109. }
  110. owner, err := user_model.GetUserByName(ctx, results.OwnerName)
  111. if err != nil {
  112. if user_model.IsErrUserNotExist(err) {
  113. // User is fetching/cloning a non-existent repository
  114. log.Warn("Failed authentication attempt (cannot find repository: %s/%s) from %s", results.OwnerName, results.RepoName, ctx.RemoteAddr())
  115. ctx.JSON(http.StatusNotFound, private.Response{
  116. UserMsg: fmt.Sprintf("Cannot find repository: %s/%s", results.OwnerName, results.RepoName),
  117. })
  118. return
  119. }
  120. log.Error("Unable to get repository owner: %s/%s Error: %v", results.OwnerName, results.RepoName, err)
  121. ctx.JSON(http.StatusForbidden, private.Response{
  122. UserMsg: fmt.Sprintf("Unable to get repository owner: %s/%s %v", results.OwnerName, results.RepoName, err),
  123. })
  124. return
  125. }
  126. if !owner.IsOrganization() && !owner.IsActive {
  127. ctx.JSON(http.StatusForbidden, private.Response{
  128. UserMsg: "Repository cannot be accessed, you could retry it later",
  129. })
  130. return
  131. }
  132. redirectedRepoID, err := repo_model.LookupRedirect(ctx, owner.ID, results.RepoName)
  133. if err == nil {
  134. redirectedRepo, err := repo_model.GetRepositoryByID(ctx, redirectedRepoID)
  135. if err == nil {
  136. log.Info("Repository %s/%s has been redirected to %s/%s", results.OwnerName, results.RepoName, redirectedRepo.OwnerName, redirectedRepo.Name)
  137. results.RepoName = redirectedRepo.Name
  138. results.OwnerName = redirectedRepo.OwnerName
  139. owner.ID = redirectedRepo.OwnerID
  140. } else {
  141. log.Warn("Repo %s/%s has a redirect to repo with ID %d, but no repo with this ID could be found. Trying without redirect...", results.OwnerName, results.RepoName, redirectedRepoID)
  142. }
  143. }
  144. // Now get the Repository and set the results section
  145. repoExist := true
  146. repo, err := repo_model.GetRepositoryByName(ctx, owner.ID, results.RepoName)
  147. if err != nil {
  148. if repo_model.IsErrRepoNotExist(err) {
  149. repoExist = false
  150. if mode == perm.AccessModeRead {
  151. // User is fetching/cloning a non-existent repository
  152. log.Warn("Failed authentication attempt (cannot find repository: %s/%s) from %s", results.OwnerName, results.RepoName, ctx.RemoteAddr())
  153. ctx.JSON(http.StatusNotFound, private.Response{
  154. UserMsg: fmt.Sprintf("Cannot find repository: %s/%s", results.OwnerName, results.RepoName),
  155. })
  156. return
  157. }
  158. // else fallthrough (push-to-create may kick in below)
  159. } else {
  160. log.Error("Unable to get repository: %s/%s Error: %v", results.OwnerName, results.RepoName, err)
  161. ctx.JSON(http.StatusInternalServerError, private.Response{
  162. Err: fmt.Sprintf("Unable to get repository: %s/%s %v", results.OwnerName, results.RepoName, err),
  163. })
  164. return
  165. }
  166. }
  167. if repoExist {
  168. repo.Owner = owner
  169. repo.OwnerName = ownerName
  170. results.RepoID = repo.ID
  171. if repo.IsBeingCreated() {
  172. ctx.JSON(http.StatusInternalServerError, private.Response{
  173. Err: "Repository is being created, you could retry after it finished",
  174. })
  175. return
  176. }
  177. if repo.IsBroken() {
  178. ctx.JSON(http.StatusInternalServerError, private.Response{
  179. Err: "Repository is in a broken state",
  180. })
  181. return
  182. }
  183. // We can shortcut at this point if the repo is a mirror
  184. if mode > perm.AccessModeRead && repo.IsMirror {
  185. ctx.JSON(http.StatusForbidden, private.Response{
  186. UserMsg: fmt.Sprintf("Mirror Repository %s/%s is read-only", results.OwnerName, results.RepoName),
  187. })
  188. return
  189. }
  190. }
  191. // Get the Public Key represented by the keyID
  192. key, err := asymkey_model.GetPublicKeyByID(ctx, keyID)
  193. if err != nil {
  194. if asymkey_model.IsErrKeyNotExist(err) {
  195. ctx.JSON(http.StatusNotFound, private.Response{
  196. UserMsg: fmt.Sprintf("Cannot find key: %d", keyID),
  197. })
  198. return
  199. }
  200. log.Error("Unable to get public key: %d Error: %v", keyID, err)
  201. ctx.JSON(http.StatusInternalServerError, private.Response{
  202. Err: fmt.Sprintf("Unable to get key: %d Error: %v", keyID, err),
  203. })
  204. return
  205. }
  206. results.KeyName = key.Name
  207. results.KeyID = key.ID
  208. results.UserID = key.OwnerID
  209. // If repo doesn't exist, deploy key doesn't make sense
  210. if !repoExist && key.Type == asymkey_model.KeyTypeDeploy {
  211. ctx.JSON(http.StatusNotFound, private.Response{
  212. UserMsg: fmt.Sprintf("Cannot find repository %s/%s", results.OwnerName, results.RepoName),
  213. })
  214. return
  215. }
  216. // Deploy Keys have ownerID set to 0 therefore we can't use the owner
  217. // So now we need to check if the key is a deploy key
  218. // We'll keep hold of the deploy key here for permissions checking
  219. var deployKey *asymkey_model.DeployKey
  220. var user *user_model.User
  221. if key.Type == asymkey_model.KeyTypeDeploy {
  222. var err error
  223. deployKey, err = asymkey_model.GetDeployKeyByRepo(ctx, key.ID, repo.ID)
  224. if err != nil {
  225. if asymkey_model.IsErrDeployKeyNotExist(err) {
  226. ctx.JSON(http.StatusNotFound, private.Response{
  227. UserMsg: fmt.Sprintf("Public (Deploy) Key: %d:%s is not authorized to %s %s/%s.", key.ID, key.Name, modeString, results.OwnerName, results.RepoName),
  228. })
  229. return
  230. }
  231. log.Error("Unable to get deploy for public (deploy) key: %d in %-v Error: %v", key.ID, repo, err)
  232. ctx.JSON(http.StatusInternalServerError, private.Response{
  233. Err: fmt.Sprintf("Unable to get Deploy Key for Public Key: %d:%s in %s/%s.", key.ID, key.Name, results.OwnerName, results.RepoName),
  234. })
  235. return
  236. }
  237. results.DeployKeyID = deployKey.ID
  238. results.KeyName = deployKey.Name
  239. // FIXME: Deploy keys aren't really the owner of the repo pushing changes
  240. // however we don't have good way of representing deploy keys in hook.go
  241. // so for now use the owner of the repository
  242. results.UserName = results.OwnerName
  243. results.UserID = repo.OwnerID
  244. if !repo.Owner.KeepEmailPrivate {
  245. results.UserEmail = repo.Owner.Email
  246. }
  247. } else {
  248. // Get the user represented by the Key
  249. var err error
  250. user, err = user_model.GetUserByID(ctx, key.OwnerID)
  251. if err != nil {
  252. if user_model.IsErrUserNotExist(err) {
  253. ctx.JSON(http.StatusUnauthorized, private.Response{
  254. UserMsg: fmt.Sprintf("Public Key: %d:%s owner %d does not exist.", key.ID, key.Name, key.OwnerID),
  255. })
  256. return
  257. }
  258. log.Error("Unable to get owner: %d for public key: %d:%s Error: %v", key.OwnerID, key.ID, key.Name, err)
  259. ctx.JSON(http.StatusInternalServerError, private.Response{
  260. Err: fmt.Sprintf("Unable to get Owner: %d for Deploy Key: %d:%s in %s/%s.", key.OwnerID, key.ID, key.Name, ownerName, repoName),
  261. })
  262. return
  263. }
  264. if !user.IsActive || user.ProhibitLogin {
  265. ctx.JSON(http.StatusForbidden, private.Response{
  266. UserMsg: "Your account is disabled.",
  267. })
  268. return
  269. }
  270. results.UserName = user.Name
  271. if !user.KeepEmailPrivate {
  272. results.UserEmail = user.Email
  273. }
  274. }
  275. // Don't allow pushing if the repo is archived
  276. if repoExist && mode > perm.AccessModeRead && repo.IsArchived {
  277. ctx.JSON(http.StatusUnauthorized, private.Response{
  278. UserMsg: fmt.Sprintf("Repo: %s/%s is archived.", results.OwnerName, results.RepoName),
  279. })
  280. return
  281. }
  282. // Permissions checking:
  283. if repoExist &&
  284. (mode > perm.AccessModeRead ||
  285. repo.IsPrivate ||
  286. owner.Visibility.IsPrivate() ||
  287. (user != nil && user.IsRestricted) || // user will be nil if the key is a deploykey
  288. setting.Service.RequireSignInViewStrict) {
  289. if key.Type == asymkey_model.KeyTypeDeploy {
  290. if deployKey.Mode < mode {
  291. ctx.JSON(http.StatusUnauthorized, private.Response{
  292. UserMsg: fmt.Sprintf("Deploy Key: %d:%s is not authorized to %s %s/%s.", key.ID, key.Name, modeString, results.OwnerName, results.RepoName),
  293. })
  294. return
  295. }
  296. } else {
  297. // Because of the special ref "refs/for" (AGit) we will need to delay write permission check,
  298. // AGit flow needs to write its own ref when the doer has "reader" permission (allowing to create PR).
  299. // The real permission check is done in HookPreReceive (routers/private/hook_pre_receive.go).
  300. // Here it should relax the permission check for "git push (git-receive-pack)", but not for others like LFS operations.
  301. if git.DefaultFeatures().SupportProcReceive && unitType == unit.TypeCode && verb == git.CmdVerbReceivePack {
  302. mode = perm.AccessModeRead
  303. }
  304. perm, err := access_model.GetUserRepoPermission(ctx, repo, user)
  305. if err != nil {
  306. log.Error("Unable to get permissions for %-v with key %d in %-v Error: %v", user, key.ID, repo, err)
  307. ctx.JSON(http.StatusInternalServerError, private.Response{
  308. Err: fmt.Sprintf("Unable to get permissions for user %d:%s with key %d in %s/%s Error: %v", user.ID, user.Name, key.ID, results.OwnerName, results.RepoName, err),
  309. })
  310. return
  311. }
  312. userMode := perm.UnitAccessMode(unitType)
  313. if userMode < mode {
  314. log.Warn("Failed authentication attempt for %s with key %s (not authorized to %s %s/%s) from %s", user.Name, key.Name, modeString, ownerName, repoName, ctx.RemoteAddr())
  315. ctx.JSON(http.StatusUnauthorized, private.Response{
  316. UserMsg: fmt.Sprintf("User: %d:%s with Key: %d:%s is not authorized to %s %s/%s.", user.ID, user.Name, key.ID, key.Name, modeString, ownerName, repoName),
  317. })
  318. return
  319. }
  320. }
  321. }
  322. // We already know we aren't using a deploy key
  323. if !repoExist {
  324. owner, err := user_model.GetUserByName(ctx, ownerName)
  325. if err != nil {
  326. ctx.JSON(http.StatusInternalServerError, private.Response{
  327. Err: fmt.Sprintf("Unable to get owner: %s %v", results.OwnerName, err),
  328. })
  329. return
  330. }
  331. if owner.IsOrganization() && !setting.Repository.EnablePushCreateOrg {
  332. ctx.JSON(http.StatusForbidden, private.Response{
  333. UserMsg: "Push to create is not enabled for organizations.",
  334. })
  335. return
  336. }
  337. if !owner.IsOrganization() && !setting.Repository.EnablePushCreateUser {
  338. ctx.JSON(http.StatusForbidden, private.Response{
  339. UserMsg: "Push to create is not enabled for users.",
  340. })
  341. return
  342. }
  343. repo, err = repo_service.PushCreateRepo(ctx, user, owner, results.RepoName)
  344. if err != nil {
  345. log.Error("pushCreateRepo: %v", err)
  346. ctx.JSON(http.StatusNotFound, private.Response{
  347. UserMsg: fmt.Sprintf("Cannot find repository: %s/%s", results.OwnerName, results.RepoName),
  348. })
  349. return
  350. }
  351. results.RepoID = repo.ID
  352. }
  353. if results.IsWiki {
  354. // Ensure the wiki is enabled before we allow access to it
  355. if _, err := repo.GetUnit(ctx, unit.TypeWiki); err != nil {
  356. if repo_model.IsErrUnitTypeNotExist(err) {
  357. ctx.JSON(http.StatusForbidden, private.Response{
  358. UserMsg: "repository wiki is disabled",
  359. })
  360. return
  361. }
  362. log.Error("Failed to get the wiki unit in %-v Error: %v", repo, err)
  363. ctx.JSON(http.StatusInternalServerError, private.Response{
  364. Err: fmt.Sprintf("Failed to get the wiki unit in %s/%s Error: %v", ownerName, repoName, err),
  365. })
  366. return
  367. }
  368. // Finally if we're trying to touch the wiki we should init it
  369. if err = wiki_service.InitWiki(ctx, repo); err != nil {
  370. log.Error("Failed to initialize the wiki in %-v Error: %v", repo, err)
  371. ctx.JSON(http.StatusInternalServerError, private.Response{
  372. Err: fmt.Sprintf("Failed to initialize the wiki in %s/%s Error: %v", ownerName, repoName, err),
  373. })
  374. return
  375. }
  376. }
  377. log.Debug("Serv Results:\nIsWiki: %t\nDeployKeyID: %d\nKeyID: %d\tKeyName: %s\nUserName: %s\nUserID: %d\nOwnerName: %s\nRepoName: %s\nRepoID: %d",
  378. results.IsWiki,
  379. results.DeployKeyID,
  380. results.KeyID,
  381. results.KeyName,
  382. results.UserName,
  383. results.UserID,
  384. results.OwnerName,
  385. results.RepoName,
  386. results.RepoID)
  387. ctx.JSON(http.StatusOK, results)
  388. // We will update the keys in a different call.
  389. }