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.

server.go 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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 lfs
  5. import (
  6. "crypto/sha256"
  7. "encoding/base64"
  8. "encoding/hex"
  9. "errors"
  10. "fmt"
  11. "io"
  12. "net/http"
  13. "net/url"
  14. "path"
  15. "regexp"
  16. "strconv"
  17. "strings"
  18. "code.gitea.io/gitea/models"
  19. "code.gitea.io/gitea/models/perm"
  20. repo_model "code.gitea.io/gitea/models/repo"
  21. "code.gitea.io/gitea/models/unit"
  22. user_model "code.gitea.io/gitea/models/user"
  23. "code.gitea.io/gitea/modules/context"
  24. "code.gitea.io/gitea/modules/json"
  25. lfs_module "code.gitea.io/gitea/modules/lfs"
  26. "code.gitea.io/gitea/modules/log"
  27. "code.gitea.io/gitea/modules/setting"
  28. "code.gitea.io/gitea/modules/storage"
  29. "github.com/golang-jwt/jwt"
  30. )
  31. // requestContext contain variables from the HTTP request.
  32. type requestContext struct {
  33. User string
  34. Repo string
  35. Authorization string
  36. }
  37. // Claims is a JWT Token Claims
  38. type Claims struct {
  39. RepoID int64
  40. Op string
  41. UserID int64
  42. jwt.StandardClaims
  43. }
  44. // DownloadLink builds a URL to download the object.
  45. func (rc *requestContext) DownloadLink(p lfs_module.Pointer) string {
  46. return setting.AppURL + path.Join(url.PathEscape(rc.User), url.PathEscape(rc.Repo+".git"), "info/lfs/objects", url.PathEscape(p.Oid))
  47. }
  48. // UploadLink builds a URL to upload the object.
  49. func (rc *requestContext) UploadLink(p lfs_module.Pointer) string {
  50. return setting.AppURL + path.Join(url.PathEscape(rc.User), url.PathEscape(rc.Repo+".git"), "info/lfs/objects", url.PathEscape(p.Oid), strconv.FormatInt(p.Size, 10))
  51. }
  52. // VerifyLink builds a URL for verifying the object.
  53. func (rc *requestContext) VerifyLink(p lfs_module.Pointer) string {
  54. return setting.AppURL + path.Join(url.PathEscape(rc.User), url.PathEscape(rc.Repo+".git"), "info/lfs/verify")
  55. }
  56. // CheckAcceptMediaType checks if the client accepts the LFS media type.
  57. func CheckAcceptMediaType(ctx *context.Context) {
  58. mediaParts := strings.Split(ctx.Req.Header.Get("Accept"), ";")
  59. if mediaParts[0] != lfs_module.MediaType {
  60. log.Trace("Calling a LFS method without accepting the correct media type: %s", lfs_module.MediaType)
  61. writeStatus(ctx, http.StatusUnsupportedMediaType)
  62. return
  63. }
  64. }
  65. // DownloadHandler gets the content from the content store
  66. func DownloadHandler(ctx *context.Context) {
  67. rc := getRequestContext(ctx)
  68. p := lfs_module.Pointer{Oid: ctx.Params("oid")}
  69. meta := getAuthenticatedMeta(ctx, rc, p, false)
  70. if meta == nil {
  71. return
  72. }
  73. // Support resume download using Range header
  74. var fromByte, toByte int64
  75. toByte = meta.Size - 1
  76. statusCode := http.StatusOK
  77. if rangeHdr := ctx.Req.Header.Get("Range"); rangeHdr != "" {
  78. regex := regexp.MustCompile(`bytes=(\d+)\-(\d*).*`)
  79. match := regex.FindStringSubmatch(rangeHdr)
  80. if len(match) > 1 {
  81. statusCode = http.StatusPartialContent
  82. fromByte, _ = strconv.ParseInt(match[1], 10, 32)
  83. if fromByte >= meta.Size {
  84. writeStatus(ctx, http.StatusRequestedRangeNotSatisfiable)
  85. return
  86. }
  87. if match[2] != "" {
  88. _toByte, _ := strconv.ParseInt(match[2], 10, 32)
  89. if _toByte >= fromByte && _toByte < toByte {
  90. toByte = _toByte
  91. }
  92. }
  93. ctx.Resp.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", fromByte, toByte, meta.Size-fromByte))
  94. ctx.Resp.Header().Set("Access-Control-Expose-Headers", "Content-Range")
  95. }
  96. }
  97. contentStore := lfs_module.NewContentStore()
  98. content, err := contentStore.Get(meta.Pointer)
  99. if err != nil {
  100. writeStatus(ctx, http.StatusNotFound)
  101. return
  102. }
  103. defer content.Close()
  104. if fromByte > 0 {
  105. _, err = content.Seek(fromByte, io.SeekStart)
  106. if err != nil {
  107. log.Error("Whilst trying to read LFS OID[%s]: Unable to seek to %d Error: %v", meta.Oid, fromByte, err)
  108. writeStatus(ctx, http.StatusInternalServerError)
  109. return
  110. }
  111. }
  112. contentLength := toByte + 1 - fromByte
  113. ctx.Resp.Header().Set("Content-Length", strconv.FormatInt(contentLength, 10))
  114. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  115. filename := ctx.Params("filename")
  116. if len(filename) > 0 {
  117. decodedFilename, err := base64.RawURLEncoding.DecodeString(filename)
  118. if err == nil {
  119. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename=\""+string(decodedFilename)+"\"")
  120. ctx.Resp.Header().Set("Access-Control-Expose-Headers", "Content-Disposition")
  121. }
  122. }
  123. ctx.Resp.WriteHeader(statusCode)
  124. if written, err := io.CopyN(ctx.Resp, content, contentLength); err != nil {
  125. log.Error("Error whilst copying LFS OID[%s] to the response after %d bytes. Error: %v", meta.Oid, written, err)
  126. }
  127. }
  128. // BatchHandler provides the batch api
  129. func BatchHandler(ctx *context.Context) {
  130. var br lfs_module.BatchRequest
  131. if err := decodeJSON(ctx.Req, &br); err != nil {
  132. log.Trace("Unable to decode BATCH request vars: Error: %v", err)
  133. writeStatus(ctx, http.StatusBadRequest)
  134. return
  135. }
  136. var isUpload bool
  137. if br.Operation == "upload" {
  138. isUpload = true
  139. } else if br.Operation == "download" {
  140. isUpload = false
  141. } else {
  142. log.Trace("Attempt to BATCH with invalid operation: %s", br.Operation)
  143. writeStatus(ctx, http.StatusBadRequest)
  144. return
  145. }
  146. rc := getRequestContext(ctx)
  147. repository := getAuthenticatedRepository(ctx, rc, isUpload)
  148. if repository == nil {
  149. return
  150. }
  151. contentStore := lfs_module.NewContentStore()
  152. var responseObjects []*lfs_module.ObjectResponse
  153. for _, p := range br.Objects {
  154. if !p.IsValid() {
  155. responseObjects = append(responseObjects, buildObjectResponse(rc, p, false, false, &lfs_module.ObjectError{
  156. Code: http.StatusUnprocessableEntity,
  157. Message: "Oid or size are invalid",
  158. }))
  159. continue
  160. }
  161. exists, err := contentStore.Exists(p)
  162. if err != nil {
  163. log.Error("Unable to check if LFS OID[%s] exist. Error: %v", p.Oid, rc.User, rc.Repo, err)
  164. writeStatus(ctx, http.StatusInternalServerError)
  165. return
  166. }
  167. meta, err := models.GetLFSMetaObjectByOid(repository.ID, p.Oid)
  168. if err != nil && err != models.ErrLFSObjectNotExist {
  169. log.Error("Unable to get LFS MetaObject [%s] for %s/%s. Error: %v", p.Oid, rc.User, rc.Repo, err)
  170. writeStatus(ctx, http.StatusInternalServerError)
  171. return
  172. }
  173. if meta != nil && p.Size != meta.Size {
  174. responseObjects = append(responseObjects, buildObjectResponse(rc, p, false, false, &lfs_module.ObjectError{
  175. Code: http.StatusUnprocessableEntity,
  176. Message: fmt.Sprintf("Object %s is not %d bytes", p.Oid, p.Size),
  177. }))
  178. continue
  179. }
  180. var responseObject *lfs_module.ObjectResponse
  181. if isUpload {
  182. var err *lfs_module.ObjectError
  183. if !exists && setting.LFS.MaxFileSize > 0 && p.Size > setting.LFS.MaxFileSize {
  184. err = &lfs_module.ObjectError{
  185. Code: http.StatusUnprocessableEntity,
  186. Message: fmt.Sprintf("Size must be less than or equal to %d", setting.LFS.MaxFileSize),
  187. }
  188. }
  189. if exists && meta == nil {
  190. accessible, err := models.LFSObjectAccessible(ctx.User, p.Oid)
  191. if err != nil {
  192. log.Error("Unable to check if LFS MetaObject [%s] is accessible. Error: %v", p.Oid, err)
  193. writeStatus(ctx, http.StatusInternalServerError)
  194. return
  195. }
  196. if accessible {
  197. _, err := models.NewLFSMetaObject(&models.LFSMetaObject{Pointer: p, RepositoryID: repository.ID})
  198. if err != nil {
  199. log.Error("Unable to create LFS MetaObject [%s] for %s/%s. Error: %v", p.Oid, rc.User, rc.Repo, err)
  200. writeStatus(ctx, http.StatusInternalServerError)
  201. return
  202. }
  203. } else {
  204. exists = false
  205. }
  206. }
  207. responseObject = buildObjectResponse(rc, p, false, !exists, err)
  208. } else {
  209. var err *lfs_module.ObjectError
  210. if !exists || meta == nil {
  211. err = &lfs_module.ObjectError{
  212. Code: http.StatusNotFound,
  213. Message: http.StatusText(http.StatusNotFound),
  214. }
  215. }
  216. responseObject = buildObjectResponse(rc, p, true, false, err)
  217. }
  218. responseObjects = append(responseObjects, responseObject)
  219. }
  220. respobj := &lfs_module.BatchResponse{Objects: responseObjects}
  221. ctx.Resp.Header().Set("Content-Type", lfs_module.MediaType)
  222. enc := json.NewEncoder(ctx.Resp)
  223. if err := enc.Encode(respobj); err != nil {
  224. log.Error("Failed to encode representation as json. Error: %v", err)
  225. }
  226. }
  227. // UploadHandler receives data from the client and puts it into the content store
  228. func UploadHandler(ctx *context.Context) {
  229. rc := getRequestContext(ctx)
  230. p := lfs_module.Pointer{Oid: ctx.Params("oid")}
  231. var err error
  232. if p.Size, err = strconv.ParseInt(ctx.Params("size"), 10, 64); err != nil {
  233. writeStatusMessage(ctx, http.StatusUnprocessableEntity, err.Error())
  234. }
  235. if !p.IsValid() {
  236. log.Trace("Attempt to access invalid LFS OID[%s] in %s/%s", p.Oid, rc.User, rc.Repo)
  237. writeStatus(ctx, http.StatusUnprocessableEntity)
  238. return
  239. }
  240. repository := getAuthenticatedRepository(ctx, rc, true)
  241. if repository == nil {
  242. return
  243. }
  244. contentStore := lfs_module.NewContentStore()
  245. exists, err := contentStore.Exists(p)
  246. if err != nil {
  247. log.Error("Unable to check if LFS OID[%s] exist. Error: %v", p.Oid, err)
  248. writeStatus(ctx, http.StatusInternalServerError)
  249. return
  250. }
  251. uploadOrVerify := func() error {
  252. if exists {
  253. accessible, err := models.LFSObjectAccessible(ctx.User, p.Oid)
  254. if err != nil {
  255. log.Error("Unable to check if LFS MetaObject [%s] is accessible. Error: %v", p.Oid, err)
  256. return err
  257. }
  258. if !accessible {
  259. // The file exists but the user has no access to it.
  260. // The upload gets verified by hashing and size comparison to prove access to it.
  261. hash := sha256.New()
  262. written, err := io.Copy(hash, ctx.Req.Body)
  263. if err != nil {
  264. log.Error("Error creating hash. Error: %v", err)
  265. return err
  266. }
  267. if written != p.Size {
  268. return lfs_module.ErrSizeMismatch
  269. }
  270. if hex.EncodeToString(hash.Sum(nil)) != p.Oid {
  271. return lfs_module.ErrHashMismatch
  272. }
  273. }
  274. } else if err := contentStore.Put(p, ctx.Req.Body); err != nil {
  275. log.Error("Error putting LFS MetaObject [%s] into content store. Error: %v", p.Oid, err)
  276. return err
  277. }
  278. _, err := models.NewLFSMetaObject(&models.LFSMetaObject{Pointer: p, RepositoryID: repository.ID})
  279. return err
  280. }
  281. defer ctx.Req.Body.Close()
  282. if err := uploadOrVerify(); err != nil {
  283. if errors.Is(err, lfs_module.ErrSizeMismatch) || errors.Is(err, lfs_module.ErrHashMismatch) {
  284. log.Error("Upload does not match LFS MetaObject [%s]. Error: %v", p.Oid, err)
  285. writeStatusMessage(ctx, http.StatusUnprocessableEntity, err.Error())
  286. } else {
  287. writeStatus(ctx, http.StatusInternalServerError)
  288. }
  289. if _, err = models.RemoveLFSMetaObjectByOid(repository.ID, p.Oid); err != nil {
  290. log.Error("Error whilst removing metaobject for LFS OID[%s]: %v", p.Oid, err)
  291. }
  292. return
  293. }
  294. writeStatus(ctx, http.StatusOK)
  295. }
  296. // VerifyHandler verify oid and its size from the content store
  297. func VerifyHandler(ctx *context.Context) {
  298. var p lfs_module.Pointer
  299. if err := decodeJSON(ctx.Req, &p); err != nil {
  300. writeStatus(ctx, http.StatusUnprocessableEntity)
  301. return
  302. }
  303. rc := getRequestContext(ctx)
  304. meta := getAuthenticatedMeta(ctx, rc, p, true)
  305. if meta == nil {
  306. return
  307. }
  308. contentStore := lfs_module.NewContentStore()
  309. ok, err := contentStore.Verify(meta.Pointer)
  310. status := http.StatusOK
  311. if err != nil {
  312. status = http.StatusInternalServerError
  313. } else if !ok {
  314. status = http.StatusNotFound
  315. }
  316. writeStatus(ctx, status)
  317. }
  318. func decodeJSON(req *http.Request, v interface{}) error {
  319. defer req.Body.Close()
  320. dec := json.NewDecoder(req.Body)
  321. return dec.Decode(v)
  322. }
  323. func getRequestContext(ctx *context.Context) *requestContext {
  324. return &requestContext{
  325. User: ctx.Params("username"),
  326. Repo: strings.TrimSuffix(ctx.Params("reponame"), ".git"),
  327. Authorization: ctx.Req.Header.Get("Authorization"),
  328. }
  329. }
  330. func getAuthenticatedMeta(ctx *context.Context, rc *requestContext, p lfs_module.Pointer, requireWrite bool) *models.LFSMetaObject {
  331. if !p.IsValid() {
  332. log.Info("Attempt to access invalid LFS OID[%s] in %s/%s", p.Oid, rc.User, rc.Repo)
  333. writeStatusMessage(ctx, http.StatusUnprocessableEntity, "Oid or size are invalid")
  334. return nil
  335. }
  336. repository := getAuthenticatedRepository(ctx, rc, requireWrite)
  337. if repository == nil {
  338. return nil
  339. }
  340. meta, err := models.GetLFSMetaObjectByOid(repository.ID, p.Oid)
  341. if err != nil {
  342. log.Error("Unable to get LFS OID[%s] Error: %v", p.Oid, err)
  343. writeStatus(ctx, http.StatusNotFound)
  344. return nil
  345. }
  346. return meta
  347. }
  348. func getAuthenticatedRepository(ctx *context.Context, rc *requestContext, requireWrite bool) *repo_model.Repository {
  349. repository, err := repo_model.GetRepositoryByOwnerAndName(rc.User, rc.Repo)
  350. if err != nil {
  351. log.Error("Unable to get repository: %s/%s Error: %v", rc.User, rc.Repo, err)
  352. writeStatus(ctx, http.StatusNotFound)
  353. return nil
  354. }
  355. if !authenticate(ctx, repository, rc.Authorization, false, requireWrite) {
  356. requireAuth(ctx)
  357. return nil
  358. }
  359. return repository
  360. }
  361. func buildObjectResponse(rc *requestContext, pointer lfs_module.Pointer, download, upload bool, err *lfs_module.ObjectError) *lfs_module.ObjectResponse {
  362. rep := &lfs_module.ObjectResponse{Pointer: pointer}
  363. if err != nil {
  364. rep.Error = err
  365. } else {
  366. rep.Actions = make(map[string]*lfs_module.Link)
  367. header := make(map[string]string)
  368. if len(rc.Authorization) > 0 {
  369. header["Authorization"] = rc.Authorization
  370. }
  371. if download {
  372. rep.Actions["download"] = &lfs_module.Link{Href: rc.DownloadLink(pointer), Header: header}
  373. if setting.LFS.ServeDirect {
  374. //If we have a signed url (S3, object storage), redirect to this directly.
  375. u, err := storage.LFS.URL(pointer.RelativePath(), pointer.Oid)
  376. if u != nil && err == nil {
  377. rep.Actions["download"] = &lfs_module.Link{Href: u.String(), Header: header}
  378. }
  379. }
  380. }
  381. if upload {
  382. rep.Actions["upload"] = &lfs_module.Link{Href: rc.UploadLink(pointer), Header: header}
  383. verifyHeader := make(map[string]string)
  384. for key, value := range header {
  385. verifyHeader[key] = value
  386. }
  387. // This is only needed to workaround https://github.com/git-lfs/git-lfs/issues/3662
  388. verifyHeader["Accept"] = lfs_module.MediaType
  389. rep.Actions["verify"] = &lfs_module.Link{Href: rc.VerifyLink(pointer), Header: verifyHeader}
  390. }
  391. }
  392. return rep
  393. }
  394. func writeStatus(ctx *context.Context, status int) {
  395. writeStatusMessage(ctx, status, http.StatusText(status))
  396. }
  397. func writeStatusMessage(ctx *context.Context, status int, message string) {
  398. ctx.Resp.Header().Set("Content-Type", lfs_module.MediaType)
  399. ctx.Resp.WriteHeader(status)
  400. er := lfs_module.ErrorResponse{Message: message}
  401. enc := json.NewEncoder(ctx.Resp)
  402. if err := enc.Encode(er); err != nil {
  403. log.Error("Failed to encode error response as json. Error: %v", err)
  404. }
  405. }
  406. // authenticate uses the authorization string to determine whether
  407. // or not to proceed. This server assumes an HTTP Basic auth format.
  408. func authenticate(ctx *context.Context, repository *repo_model.Repository, authorization string, requireSigned, requireWrite bool) bool {
  409. accessMode := perm.AccessModeRead
  410. if requireWrite {
  411. accessMode = perm.AccessModeWrite
  412. }
  413. // ctx.IsSigned is unnecessary here, this will be checked in perm.CanAccess
  414. perm, err := models.GetUserRepoPermission(repository, ctx.User)
  415. if err != nil {
  416. log.Error("Unable to GetUserRepoPermission for user %-v in repo %-v Error: %v", ctx.User, repository)
  417. return false
  418. }
  419. canRead := perm.CanAccess(accessMode, unit.TypeCode)
  420. if canRead && (!requireSigned || ctx.IsSigned) {
  421. return true
  422. }
  423. user, err := parseToken(authorization, repository, accessMode)
  424. if err != nil {
  425. // Most of these are Warn level - the true internal server errors are logged in parseToken already
  426. log.Warn("Authentication failure for provided token with Error: %v", err)
  427. return false
  428. }
  429. ctx.User = user
  430. return true
  431. }
  432. func handleLFSToken(tokenSHA string, target *repo_model.Repository, mode perm.AccessMode) (*user_model.User, error) {
  433. if !strings.Contains(tokenSHA, ".") {
  434. return nil, nil
  435. }
  436. token, err := jwt.ParseWithClaims(tokenSHA, &Claims{}, func(t *jwt.Token) (interface{}, error) {
  437. if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
  438. return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
  439. }
  440. return setting.LFS.JWTSecretBytes, nil
  441. })
  442. if err != nil {
  443. return nil, nil
  444. }
  445. claims, claimsOk := token.Claims.(*Claims)
  446. if !token.Valid || !claimsOk {
  447. return nil, fmt.Errorf("invalid token claim")
  448. }
  449. if claims.RepoID != target.ID {
  450. return nil, fmt.Errorf("invalid token claim")
  451. }
  452. if mode == perm.AccessModeWrite && claims.Op != "upload" {
  453. return nil, fmt.Errorf("invalid token claim")
  454. }
  455. u, err := user_model.GetUserByID(claims.UserID)
  456. if err != nil {
  457. log.Error("Unable to GetUserById[%d]: Error: %v", claims.UserID, err)
  458. return nil, err
  459. }
  460. return u, nil
  461. }
  462. func parseToken(authorization string, target *repo_model.Repository, mode perm.AccessMode) (*user_model.User, error) {
  463. if authorization == "" {
  464. return nil, fmt.Errorf("no token")
  465. }
  466. parts := strings.SplitN(authorization, " ", 2)
  467. if len(parts) != 2 {
  468. return nil, fmt.Errorf("no token")
  469. }
  470. tokenSHA := parts[1]
  471. switch strings.ToLower(parts[0]) {
  472. case "bearer":
  473. fallthrough
  474. case "token":
  475. return handleLFSToken(tokenSHA, target, mode)
  476. }
  477. return nil, fmt.Errorf("token not found")
  478. }
  479. func requireAuth(ctx *context.Context) {
  480. ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs")
  481. writeStatus(ctx, http.StatusUnauthorized)
  482. }