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 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. package lfs
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "path"
  9. "regexp"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "code.gitea.io/gitea/models"
  14. "code.gitea.io/gitea/modules/context"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/setting"
  17. "gitea.com/macaron/macaron"
  18. "github.com/dgrijalva/jwt-go"
  19. )
  20. const (
  21. metaMediaType = "application/vnd.git-lfs+json"
  22. )
  23. // RequestVars contain variables from the HTTP request. Variables from routing, json body decoding, and
  24. // some headers are stored.
  25. type RequestVars struct {
  26. Oid string
  27. Size int64
  28. User string
  29. Password string
  30. Repo string
  31. Authorization string
  32. }
  33. // BatchVars contains multiple RequestVars processed in one batch operation.
  34. // https://github.com/git-lfs/git-lfs/blob/master/docs/api/batch.md
  35. type BatchVars struct {
  36. Transfers []string `json:"transfers,omitempty"`
  37. Operation string `json:"operation"`
  38. Objects []*RequestVars `json:"objects"`
  39. }
  40. // BatchResponse contains multiple object metadata Representation structures
  41. // for use with the batch API.
  42. type BatchResponse struct {
  43. Transfer string `json:"transfer,omitempty"`
  44. Objects []*Representation `json:"objects"`
  45. }
  46. // Representation is object metadata as seen by clients of the lfs server.
  47. type Representation struct {
  48. Oid string `json:"oid"`
  49. Size int64 `json:"size"`
  50. Actions map[string]*link `json:"actions"`
  51. Error *ObjectError `json:"error,omitempty"`
  52. }
  53. // ObjectError defines the JSON structure returned to the client in case of an error
  54. type ObjectError struct {
  55. Code int `json:"code"`
  56. Message string `json:"message"`
  57. }
  58. // ObjectLink builds a URL linking to the object.
  59. func (v *RequestVars) ObjectLink() string {
  60. return setting.AppURL + path.Join(v.User, v.Repo+".git", "info/lfs/objects", v.Oid)
  61. }
  62. // VerifyLink builds a URL for verifying the object.
  63. func (v *RequestVars) VerifyLink() string {
  64. return setting.AppURL + path.Join(v.User, v.Repo+".git", "info/lfs/verify")
  65. }
  66. // link provides a structure used to build a hypermedia representation of an HTTP link.
  67. type link struct {
  68. Href string `json:"href"`
  69. Header map[string]string `json:"header,omitempty"`
  70. ExpiresAt time.Time `json:"expires_at,omitempty"`
  71. }
  72. var oidRegExp = regexp.MustCompile(`^[A-Fa-f0-9]+$`)
  73. func isOidValid(oid string) bool {
  74. return oidRegExp.MatchString(oid)
  75. }
  76. // ObjectOidHandler is the main request routing entry point into LFS server functions
  77. func ObjectOidHandler(ctx *context.Context) {
  78. if !setting.LFS.StartServer {
  79. writeStatus(ctx, 404)
  80. return
  81. }
  82. if ctx.Req.Method == "GET" || ctx.Req.Method == "HEAD" {
  83. if MetaMatcher(ctx.Req) {
  84. getMetaHandler(ctx)
  85. return
  86. }
  87. getContentHandler(ctx)
  88. return
  89. } else if ctx.Req.Method == "PUT" {
  90. PutHandler(ctx)
  91. return
  92. }
  93. }
  94. func getAuthenticatedRepoAndMeta(ctx *context.Context, rv *RequestVars, requireWrite bool) (*models.LFSMetaObject, *models.Repository) {
  95. if !isOidValid(rv.Oid) {
  96. writeStatus(ctx, 404)
  97. return nil, nil
  98. }
  99. repository, err := models.GetRepositoryByOwnerAndName(rv.User, rv.Repo)
  100. if err != nil {
  101. log.Debug("Could not find repository: %s/%s - %s", rv.User, rv.Repo, err)
  102. writeStatus(ctx, 404)
  103. return nil, nil
  104. }
  105. if !authenticate(ctx, repository, rv.Authorization, requireWrite) {
  106. requireAuth(ctx)
  107. return nil, nil
  108. }
  109. meta, err := repository.GetLFSMetaObjectByOid(rv.Oid)
  110. if err != nil {
  111. writeStatus(ctx, 404)
  112. return nil, nil
  113. }
  114. return meta, repository
  115. }
  116. // getContentHandler gets the content from the content store
  117. func getContentHandler(ctx *context.Context) {
  118. rv := unpack(ctx)
  119. meta, _ := getAuthenticatedRepoAndMeta(ctx, rv, false)
  120. if meta == nil {
  121. return
  122. }
  123. // Support resume download using Range header
  124. var fromByte int64
  125. statusCode := 200
  126. if rangeHdr := ctx.Req.Header.Get("Range"); rangeHdr != "" {
  127. regex := regexp.MustCompile(`bytes=(\d+)\-.*`)
  128. match := regex.FindStringSubmatch(rangeHdr)
  129. if len(match) > 1 {
  130. statusCode = 206
  131. fromByte, _ = strconv.ParseInt(match[1], 10, 32)
  132. ctx.Resp.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", fromByte, meta.Size-1, meta.Size-fromByte))
  133. }
  134. }
  135. contentStore := &ContentStore{BasePath: setting.LFS.ContentPath}
  136. content, err := contentStore.Get(meta, fromByte)
  137. if err != nil {
  138. writeStatus(ctx, 404)
  139. return
  140. }
  141. ctx.Resp.Header().Set("Content-Length", strconv.FormatInt(meta.Size-fromByte, 10))
  142. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  143. filename := ctx.Params("filename")
  144. if len(filename) > 0 {
  145. decodedFilename, err := base64.RawURLEncoding.DecodeString(filename)
  146. if err == nil {
  147. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename=\""+string(decodedFilename)+"\"")
  148. }
  149. }
  150. ctx.Resp.WriteHeader(statusCode)
  151. _, _ = io.Copy(ctx.Resp, content)
  152. _ = content.Close()
  153. logRequest(ctx.Req, statusCode)
  154. }
  155. // getMetaHandler retrieves metadata about the object
  156. func getMetaHandler(ctx *context.Context) {
  157. rv := unpack(ctx)
  158. meta, _ := getAuthenticatedRepoAndMeta(ctx, rv, false)
  159. if meta == nil {
  160. return
  161. }
  162. ctx.Resp.Header().Set("Content-Type", metaMediaType)
  163. if ctx.Req.Method == "GET" {
  164. enc := json.NewEncoder(ctx.Resp)
  165. _ = enc.Encode(Represent(rv, meta, true, false))
  166. }
  167. logRequest(ctx.Req, 200)
  168. }
  169. // PostHandler instructs the client how to upload data
  170. func PostHandler(ctx *context.Context) {
  171. if !setting.LFS.StartServer {
  172. writeStatus(ctx, 404)
  173. return
  174. }
  175. if !MetaMatcher(ctx.Req) {
  176. writeStatus(ctx, 400)
  177. return
  178. }
  179. rv := unpack(ctx)
  180. repository, err := models.GetRepositoryByOwnerAndName(rv.User, rv.Repo)
  181. if err != nil {
  182. log.Debug("Could not find repository: %s/%s - %s", rv.User, rv.Repo, err)
  183. writeStatus(ctx, 404)
  184. return
  185. }
  186. if !authenticate(ctx, repository, rv.Authorization, true) {
  187. requireAuth(ctx)
  188. return
  189. }
  190. if !isOidValid(rv.Oid) {
  191. writeStatus(ctx, 404)
  192. return
  193. }
  194. meta, err := models.NewLFSMetaObject(&models.LFSMetaObject{Oid: rv.Oid, Size: rv.Size, RepositoryID: repository.ID})
  195. if err != nil {
  196. writeStatus(ctx, 404)
  197. return
  198. }
  199. ctx.Resp.Header().Set("Content-Type", metaMediaType)
  200. sentStatus := 202
  201. contentStore := &ContentStore{BasePath: setting.LFS.ContentPath}
  202. if meta.Existing && contentStore.Exists(meta) {
  203. sentStatus = 200
  204. }
  205. ctx.Resp.WriteHeader(sentStatus)
  206. enc := json.NewEncoder(ctx.Resp)
  207. _ = enc.Encode(Represent(rv, meta, meta.Existing, true))
  208. logRequest(ctx.Req, sentStatus)
  209. }
  210. // BatchHandler provides the batch api
  211. func BatchHandler(ctx *context.Context) {
  212. if !setting.LFS.StartServer {
  213. writeStatus(ctx, 404)
  214. return
  215. }
  216. if !MetaMatcher(ctx.Req) {
  217. writeStatus(ctx, 400)
  218. return
  219. }
  220. bv := unpackbatch(ctx)
  221. var responseObjects []*Representation
  222. // Create a response object
  223. for _, object := range bv.Objects {
  224. if !isOidValid(object.Oid) {
  225. continue
  226. }
  227. repository, err := models.GetRepositoryByOwnerAndName(object.User, object.Repo)
  228. if err != nil {
  229. log.Debug("Could not find repository: %s/%s - %s", object.User, object.Repo, err)
  230. writeStatus(ctx, 404)
  231. return
  232. }
  233. requireWrite := false
  234. if bv.Operation == "upload" {
  235. requireWrite = true
  236. }
  237. if !authenticate(ctx, repository, object.Authorization, requireWrite) {
  238. requireAuth(ctx)
  239. return
  240. }
  241. contentStore := &ContentStore{BasePath: setting.LFS.ContentPath}
  242. meta, err := repository.GetLFSMetaObjectByOid(object.Oid)
  243. if err == nil && contentStore.Exists(meta) { // Object is found and exists
  244. responseObjects = append(responseObjects, Represent(object, meta, true, false))
  245. continue
  246. }
  247. // Object is not found
  248. meta, err = models.NewLFSMetaObject(&models.LFSMetaObject{Oid: object.Oid, Size: object.Size, RepositoryID: repository.ID})
  249. if err == nil {
  250. responseObjects = append(responseObjects, Represent(object, meta, meta.Existing, !contentStore.Exists(meta)))
  251. }
  252. }
  253. ctx.Resp.Header().Set("Content-Type", metaMediaType)
  254. respobj := &BatchResponse{Objects: responseObjects}
  255. enc := json.NewEncoder(ctx.Resp)
  256. _ = enc.Encode(respobj)
  257. logRequest(ctx.Req, 200)
  258. }
  259. // PutHandler receives data from the client and puts it into the content store
  260. func PutHandler(ctx *context.Context) {
  261. rv := unpack(ctx)
  262. meta, repository := getAuthenticatedRepoAndMeta(ctx, rv, true)
  263. if meta == nil {
  264. return
  265. }
  266. contentStore := &ContentStore{BasePath: setting.LFS.ContentPath}
  267. if err := contentStore.Put(meta, ctx.Req.Body().ReadCloser()); err != nil {
  268. ctx.Resp.WriteHeader(500)
  269. fmt.Fprintf(ctx.Resp, `{"message":"%s"}`, err)
  270. if err = repository.RemoveLFSMetaObjectByOid(rv.Oid); err != nil {
  271. log.Error("RemoveLFSMetaObjectByOid: %v", err)
  272. }
  273. return
  274. }
  275. logRequest(ctx.Req, 200)
  276. }
  277. // VerifyHandler verify oid and its size from the content store
  278. func VerifyHandler(ctx *context.Context) {
  279. if !setting.LFS.StartServer {
  280. writeStatus(ctx, 404)
  281. return
  282. }
  283. if !MetaMatcher(ctx.Req) {
  284. writeStatus(ctx, 400)
  285. return
  286. }
  287. rv := unpack(ctx)
  288. meta, _ := getAuthenticatedRepoAndMeta(ctx, rv, true)
  289. if meta == nil {
  290. return
  291. }
  292. contentStore := &ContentStore{BasePath: setting.LFS.ContentPath}
  293. ok, err := contentStore.Verify(meta)
  294. if err != nil {
  295. ctx.Resp.WriteHeader(500)
  296. fmt.Fprintf(ctx.Resp, `{"message":"%s"}`, err)
  297. return
  298. }
  299. if !ok {
  300. writeStatus(ctx, 422)
  301. return
  302. }
  303. logRequest(ctx.Req, 200)
  304. }
  305. // Represent takes a RequestVars and Meta and turns it into a Representation suitable
  306. // for json encoding
  307. func Represent(rv *RequestVars, meta *models.LFSMetaObject, download, upload bool) *Representation {
  308. rep := &Representation{
  309. Oid: meta.Oid,
  310. Size: meta.Size,
  311. Actions: make(map[string]*link),
  312. }
  313. header := make(map[string]string)
  314. if rv.Authorization == "" {
  315. //https://github.com/github/git-lfs/issues/1088
  316. header["Authorization"] = "Authorization: Basic dummy"
  317. } else {
  318. header["Authorization"] = rv.Authorization
  319. }
  320. if download {
  321. rep.Actions["download"] = &link{Href: rv.ObjectLink(), Header: header}
  322. }
  323. if upload {
  324. rep.Actions["upload"] = &link{Href: rv.ObjectLink(), Header: header}
  325. }
  326. if upload && !download {
  327. // Force client side verify action while gitea lacks proper server side verification
  328. verifyHeader := make(map[string]string)
  329. for k, v := range header {
  330. verifyHeader[k] = v
  331. }
  332. // This is only needed to workaround https://github.com/git-lfs/git-lfs/issues/3662
  333. verifyHeader["Accept"] = metaMediaType
  334. rep.Actions["verify"] = &link{Href: rv.VerifyLink(), Header: verifyHeader}
  335. }
  336. return rep
  337. }
  338. // MetaMatcher provides a mux.MatcherFunc that only allows requests that contain
  339. // an Accept header with the metaMediaType
  340. func MetaMatcher(r macaron.Request) bool {
  341. mediaParts := strings.Split(r.Header.Get("Accept"), ";")
  342. mt := mediaParts[0]
  343. return mt == metaMediaType
  344. }
  345. func unpack(ctx *context.Context) *RequestVars {
  346. r := ctx.Req
  347. rv := &RequestVars{
  348. User: ctx.Params("username"),
  349. Repo: strings.TrimSuffix(ctx.Params("reponame"), ".git"),
  350. Oid: ctx.Params("oid"),
  351. Authorization: r.Header.Get("Authorization"),
  352. }
  353. if r.Method == "POST" { // Maybe also check if +json
  354. var p RequestVars
  355. dec := json.NewDecoder(r.Body().ReadCloser())
  356. err := dec.Decode(&p)
  357. if err != nil {
  358. return rv
  359. }
  360. rv.Oid = p.Oid
  361. rv.Size = p.Size
  362. }
  363. return rv
  364. }
  365. // TODO cheap hack, unify with unpack
  366. func unpackbatch(ctx *context.Context) *BatchVars {
  367. r := ctx.Req
  368. var bv BatchVars
  369. dec := json.NewDecoder(r.Body().ReadCloser())
  370. err := dec.Decode(&bv)
  371. if err != nil {
  372. return &bv
  373. }
  374. for i := 0; i < len(bv.Objects); i++ {
  375. bv.Objects[i].User = ctx.Params("username")
  376. bv.Objects[i].Repo = strings.TrimSuffix(ctx.Params("reponame"), ".git")
  377. bv.Objects[i].Authorization = r.Header.Get("Authorization")
  378. }
  379. return &bv
  380. }
  381. func writeStatus(ctx *context.Context, status int) {
  382. message := http.StatusText(status)
  383. mediaParts := strings.Split(ctx.Req.Header.Get("Accept"), ";")
  384. mt := mediaParts[0]
  385. if strings.HasSuffix(mt, "+json") {
  386. message = `{"message":"` + message + `"}`
  387. }
  388. ctx.Resp.WriteHeader(status)
  389. fmt.Fprint(ctx.Resp, message)
  390. logRequest(ctx.Req, status)
  391. }
  392. func logRequest(r macaron.Request, status int) {
  393. log.Debug("LFS request - Method: %s, URL: %s, Status %d", r.Method, r.URL, status)
  394. }
  395. // authenticate uses the authorization string to determine whether
  396. // or not to proceed. This server assumes an HTTP Basic auth format.
  397. func authenticate(ctx *context.Context, repository *models.Repository, authorization string, requireWrite bool) bool {
  398. accessMode := models.AccessModeRead
  399. if requireWrite {
  400. accessMode = models.AccessModeWrite
  401. }
  402. // ctx.IsSigned is unnecessary here, this will be checked in perm.CanAccess
  403. perm, err := models.GetUserRepoPermission(repository, ctx.User)
  404. if err != nil {
  405. return false
  406. }
  407. canRead := perm.CanAccess(accessMode, models.UnitTypeCode)
  408. if canRead {
  409. return true
  410. }
  411. user, repo, opStr, err := parseToken(authorization)
  412. if err != nil {
  413. return false
  414. }
  415. ctx.User = user
  416. if opStr == "basic" {
  417. perm, err = models.GetUserRepoPermission(repository, ctx.User)
  418. if err != nil {
  419. return false
  420. }
  421. return perm.CanAccess(accessMode, models.UnitTypeCode)
  422. }
  423. if repository.ID == repo.ID {
  424. if requireWrite && opStr != "upload" {
  425. return false
  426. }
  427. return true
  428. }
  429. return false
  430. }
  431. func parseToken(authorization string) (*models.User, *models.Repository, string, error) {
  432. if authorization == "" {
  433. return nil, nil, "unknown", fmt.Errorf("No token")
  434. }
  435. if strings.HasPrefix(authorization, "Bearer ") {
  436. token, err := jwt.Parse(authorization[7:], 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, "unknown", err
  444. }
  445. claims, claimsOk := token.Claims.(jwt.MapClaims)
  446. if !token.Valid || !claimsOk {
  447. return nil, nil, "unknown", fmt.Errorf("Token claim invalid")
  448. }
  449. opStr, ok := claims["op"].(string)
  450. if !ok {
  451. return nil, nil, "unknown", fmt.Errorf("Token operation invalid")
  452. }
  453. repoID, ok := claims["repo"].(float64)
  454. if !ok {
  455. return nil, nil, opStr, fmt.Errorf("Token repository id invalid")
  456. }
  457. r, err := models.GetRepositoryByID(int64(repoID))
  458. if err != nil {
  459. return nil, nil, opStr, err
  460. }
  461. userID, ok := claims["user"].(float64)
  462. if !ok {
  463. return nil, r, opStr, fmt.Errorf("Token user id invalid")
  464. }
  465. u, err := models.GetUserByID(int64(userID))
  466. if err != nil {
  467. return nil, r, opStr, err
  468. }
  469. return u, r, opStr, nil
  470. }
  471. if strings.HasPrefix(authorization, "Basic ") {
  472. c, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(authorization, "Basic "))
  473. if err != nil {
  474. return nil, nil, "basic", err
  475. }
  476. cs := string(c)
  477. i := strings.IndexByte(cs, ':')
  478. if i < 0 {
  479. return nil, nil, "basic", fmt.Errorf("Basic auth invalid")
  480. }
  481. user, password := cs[:i], cs[i+1:]
  482. u, err := models.GetUserByName(user)
  483. if err != nil {
  484. return nil, nil, "basic", err
  485. }
  486. if !u.IsPasswordSet() || !u.ValidatePassword(password) {
  487. return nil, nil, "basic", fmt.Errorf("Basic auth failed")
  488. }
  489. return u, nil, "basic", nil
  490. }
  491. return nil, nil, "unknown", fmt.Errorf("Token not found")
  492. }
  493. func requireAuth(ctx *context.Context) {
  494. ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs")
  495. writeStatus(ctx, 401)
  496. }