本站源代码
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

604 lines
15KB

  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. bodyReader := ctx.Req.Body().ReadCloser()
  268. defer bodyReader.Close()
  269. if err := contentStore.Put(meta, bodyReader); err != nil {
  270. ctx.Resp.WriteHeader(500)
  271. fmt.Fprintf(ctx.Resp, `{"message":"%s"}`, err)
  272. if _, err = repository.RemoveLFSMetaObjectByOid(rv.Oid); err != nil {
  273. log.Error("RemoveLFSMetaObjectByOid: %v", err)
  274. }
  275. return
  276. }
  277. logRequest(ctx.Req, 200)
  278. }
  279. // VerifyHandler verify oid and its size from the content store
  280. func VerifyHandler(ctx *context.Context) {
  281. if !setting.LFS.StartServer {
  282. writeStatus(ctx, 404)
  283. return
  284. }
  285. if !MetaMatcher(ctx.Req) {
  286. writeStatus(ctx, 400)
  287. return
  288. }
  289. rv := unpack(ctx)
  290. meta, _ := getAuthenticatedRepoAndMeta(ctx, rv, true)
  291. if meta == nil {
  292. return
  293. }
  294. contentStore := &ContentStore{BasePath: setting.LFS.ContentPath}
  295. ok, err := contentStore.Verify(meta)
  296. if err != nil {
  297. ctx.Resp.WriteHeader(500)
  298. fmt.Fprintf(ctx.Resp, `{"message":"%s"}`, err)
  299. return
  300. }
  301. if !ok {
  302. writeStatus(ctx, 422)
  303. return
  304. }
  305. logRequest(ctx.Req, 200)
  306. }
  307. // Represent takes a RequestVars and Meta and turns it into a Representation suitable
  308. // for json encoding
  309. func Represent(rv *RequestVars, meta *models.LFSMetaObject, download, upload bool) *Representation {
  310. rep := &Representation{
  311. Oid: meta.Oid,
  312. Size: meta.Size,
  313. Actions: make(map[string]*link),
  314. }
  315. header := make(map[string]string)
  316. if rv.Authorization == "" {
  317. //https://github.com/github/git-lfs/issues/1088
  318. header["Authorization"] = "Authorization: Basic dummy"
  319. } else {
  320. header["Authorization"] = rv.Authorization
  321. }
  322. if download {
  323. rep.Actions["download"] = &link{Href: rv.ObjectLink(), Header: header}
  324. }
  325. if upload {
  326. rep.Actions["upload"] = &link{Href: rv.ObjectLink(), Header: header}
  327. }
  328. if upload && !download {
  329. // Force client side verify action while gitea lacks proper server side verification
  330. verifyHeader := make(map[string]string)
  331. for k, v := range header {
  332. verifyHeader[k] = v
  333. }
  334. // This is only needed to workaround https://github.com/git-lfs/git-lfs/issues/3662
  335. verifyHeader["Accept"] = metaMediaType
  336. rep.Actions["verify"] = &link{Href: rv.VerifyLink(), Header: verifyHeader}
  337. }
  338. return rep
  339. }
  340. // MetaMatcher provides a mux.MatcherFunc that only allows requests that contain
  341. // an Accept header with the metaMediaType
  342. func MetaMatcher(r macaron.Request) bool {
  343. mediaParts := strings.Split(r.Header.Get("Accept"), ";")
  344. mt := mediaParts[0]
  345. return mt == metaMediaType
  346. }
  347. func unpack(ctx *context.Context) *RequestVars {
  348. r := ctx.Req
  349. rv := &RequestVars{
  350. User: ctx.Params("username"),
  351. Repo: strings.TrimSuffix(ctx.Params("reponame"), ".git"),
  352. Oid: ctx.Params("oid"),
  353. Authorization: r.Header.Get("Authorization"),
  354. }
  355. if r.Method == "POST" { // Maybe also check if +json
  356. var p RequestVars
  357. bodyReader := r.Body().ReadCloser()
  358. defer bodyReader.Close()
  359. dec := json.NewDecoder(bodyReader)
  360. err := dec.Decode(&p)
  361. if err != nil {
  362. return rv
  363. }
  364. rv.Oid = p.Oid
  365. rv.Size = p.Size
  366. }
  367. return rv
  368. }
  369. // TODO cheap hack, unify with unpack
  370. func unpackbatch(ctx *context.Context) *BatchVars {
  371. r := ctx.Req
  372. var bv BatchVars
  373. bodyReader := r.Body().ReadCloser()
  374. defer bodyReader.Close()
  375. dec := json.NewDecoder(bodyReader)
  376. err := dec.Decode(&bv)
  377. if err != nil {
  378. return &bv
  379. }
  380. for i := 0; i < len(bv.Objects); i++ {
  381. bv.Objects[i].User = ctx.Params("username")
  382. bv.Objects[i].Repo = strings.TrimSuffix(ctx.Params("reponame"), ".git")
  383. bv.Objects[i].Authorization = r.Header.Get("Authorization")
  384. }
  385. return &bv
  386. }
  387. func writeStatus(ctx *context.Context, status int) {
  388. message := http.StatusText(status)
  389. mediaParts := strings.Split(ctx.Req.Header.Get("Accept"), ";")
  390. mt := mediaParts[0]
  391. if strings.HasSuffix(mt, "+json") {
  392. message = `{"message":"` + message + `"}`
  393. }
  394. ctx.Resp.WriteHeader(status)
  395. fmt.Fprint(ctx.Resp, message)
  396. logRequest(ctx.Req, status)
  397. }
  398. func logRequest(r macaron.Request, status int) {
  399. log.Debug("LFS request - Method: %s, URL: %s, Status %d", r.Method, r.URL, status)
  400. }
  401. // authenticate uses the authorization string to determine whether
  402. // or not to proceed. This server assumes an HTTP Basic auth format.
  403. func authenticate(ctx *context.Context, repository *models.Repository, authorization string, requireWrite bool) bool {
  404. accessMode := models.AccessModeRead
  405. if requireWrite {
  406. accessMode = models.AccessModeWrite
  407. }
  408. // ctx.IsSigned is unnecessary here, this will be checked in perm.CanAccess
  409. perm, err := models.GetUserRepoPermission(repository, ctx.User)
  410. if err != nil {
  411. return false
  412. }
  413. canRead := perm.CanAccess(accessMode, models.UnitTypeCode)
  414. if canRead {
  415. return true
  416. }
  417. user, repo, opStr, err := parseToken(authorization)
  418. if err != nil {
  419. return false
  420. }
  421. ctx.User = user
  422. if opStr == "basic" {
  423. perm, err = models.GetUserRepoPermission(repository, ctx.User)
  424. if err != nil {
  425. return false
  426. }
  427. return perm.CanAccess(accessMode, models.UnitTypeCode)
  428. }
  429. if repository.ID == repo.ID {
  430. if requireWrite && opStr != "upload" {
  431. return false
  432. }
  433. return true
  434. }
  435. return false
  436. }
  437. func parseToken(authorization string) (*models.User, *models.Repository, string, error) {
  438. if authorization == "" {
  439. return nil, nil, "unknown", fmt.Errorf("No token")
  440. }
  441. if strings.HasPrefix(authorization, "Bearer ") {
  442. token, err := jwt.Parse(authorization[7:], func(t *jwt.Token) (interface{}, error) {
  443. if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
  444. return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
  445. }
  446. return setting.LFS.JWTSecretBytes, nil
  447. })
  448. if err != nil {
  449. return nil, nil, "unknown", err
  450. }
  451. claims, claimsOk := token.Claims.(jwt.MapClaims)
  452. if !token.Valid || !claimsOk {
  453. return nil, nil, "unknown", fmt.Errorf("Token claim invalid")
  454. }
  455. opStr, ok := claims["op"].(string)
  456. if !ok {
  457. return nil, nil, "unknown", fmt.Errorf("Token operation invalid")
  458. }
  459. repoID, ok := claims["repo"].(float64)
  460. if !ok {
  461. return nil, nil, opStr, fmt.Errorf("Token repository id invalid")
  462. }
  463. r, err := models.GetRepositoryByID(int64(repoID))
  464. if err != nil {
  465. return nil, nil, opStr, err
  466. }
  467. userID, ok := claims["user"].(float64)
  468. if !ok {
  469. return nil, r, opStr, fmt.Errorf("Token user id invalid")
  470. }
  471. u, err := models.GetUserByID(int64(userID))
  472. if err != nil {
  473. return nil, r, opStr, err
  474. }
  475. return u, r, opStr, nil
  476. }
  477. if strings.HasPrefix(authorization, "Basic ") {
  478. c, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(authorization, "Basic "))
  479. if err != nil {
  480. return nil, nil, "basic", err
  481. }
  482. cs := string(c)
  483. i := strings.IndexByte(cs, ':')
  484. if i < 0 {
  485. return nil, nil, "basic", fmt.Errorf("Basic auth invalid")
  486. }
  487. user, password := cs[:i], cs[i+1:]
  488. u, err := models.GetUserByName(user)
  489. if err != nil {
  490. return nil, nil, "basic", err
  491. }
  492. if !u.IsPasswordSet() || !u.ValidatePassword(password) {
  493. return nil, nil, "basic", fmt.Errorf("Basic auth failed")
  494. }
  495. return u, nil, "basic", nil
  496. }
  497. return nil, nil, "unknown", fmt.Errorf("Token not found")
  498. }
  499. func requireAuth(ctx *context.Context) {
  500. ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs")
  501. writeStatus(ctx, 401)
  502. }
上海开阖软件有限公司 沪ICP备12045867号-1