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

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