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

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