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.
667 lines
20 KiB
667 lines
20 KiB
5 years ago
|
// Copyright 2020 The Gitea Authors. All rights reserved.
|
||
|
// Use of this source code is governed by a MIT-style
|
||
|
// license that can be found in the LICENSE file.
|
||
|
|
||
8 years ago
|
package lfs
|
||
|
|
||
|
import (
|
||
|
"encoding/base64"
|
||
|
"fmt"
|
||
|
"io"
|
||
|
"net/http"
|
||
7 years ago
|
"path"
|
||
8 years ago
|
"regexp"
|
||
|
"strconv"
|
||
|
"strings"
|
||
|
|
||
|
"code.gitea.io/gitea/models"
|
||
|
"code.gitea.io/gitea/modules/context"
|
||
4 years ago
|
lfs_module "code.gitea.io/gitea/modules/lfs"
|
||
8 years ago
|
"code.gitea.io/gitea/modules/log"
|
||
|
"code.gitea.io/gitea/modules/setting"
|
||
7 years ago
|
|
||
8 years ago
|
"github.com/dgrijalva/jwt-go"
|
||
4 years ago
|
jsoniter "github.com/json-iterator/go"
|
||
8 years ago
|
)
|
||
|
|
||
4 years ago
|
// requestContext contain variables from the HTTP request.
|
||
|
type requestContext struct {
|
||
8 years ago
|
User string
|
||
|
Repo string
|
||
|
Authorization string
|
||
|
}
|
||
|
|
||
5 years ago
|
// Claims is a JWT Token Claims
|
||
|
type Claims struct {
|
||
|
RepoID int64
|
||
|
Op string
|
||
|
UserID int64
|
||
|
jwt.StandardClaims
|
||
|
}
|
||
|
|
||
8 years ago
|
// ObjectLink builds a URL linking to the object.
|
||
4 years ago
|
func (rc *requestContext) ObjectLink(oid string) string {
|
||
|
return setting.AppURL + path.Join(rc.User, rc.Repo+".git", "info/lfs/objects", oid)
|
||
7 years ago
|
}
|
||
|
|
||
|
// VerifyLink builds a URL for verifying the object.
|
||
4 years ago
|
func (rc *requestContext) VerifyLink() string {
|
||
|
return setting.AppURL + path.Join(rc.User, rc.Repo+".git", "info/lfs/verify")
|
||
8 years ago
|
}
|
||
|
|
||
7 years ago
|
var oidRegExp = regexp.MustCompile(`^[A-Fa-f0-9]+$`)
|
||
|
|
||
7 years ago
|
func isOidValid(oid string) bool {
|
||
|
return oidRegExp.MatchString(oid)
|
||
|
}
|
||
|
|
||
8 years ago
|
// ObjectOidHandler is the main request routing entry point into LFS server functions
|
||
|
func ObjectOidHandler(ctx *context.Context) {
|
||
|
if !setting.LFS.StartServer {
|
||
5 years ago
|
log.Debug("Attempt to access LFS server but LFS server is disabled")
|
||
8 years ago
|
writeStatus(ctx, 404)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
if ctx.Req.Method == "GET" || ctx.Req.Method == "HEAD" {
|
||
|
if MetaMatcher(ctx.Req) {
|
||
7 years ago
|
getMetaHandler(ctx)
|
||
8 years ago
|
return
|
||
|
}
|
||
6 years ago
|
|
||
|
getContentHandler(ctx)
|
||
|
return
|
||
|
} else if ctx.Req.Method == "PUT" {
|
||
8 years ago
|
PutHandler(ctx)
|
||
|
return
|
||
|
}
|
||
|
|
||
5 years ago
|
log.Warn("Unhandled LFS method: %s for %s/%s OID[%s]", ctx.Req.Method, ctx.Params("username"), ctx.Params("reponame"), ctx.Params("oid"))
|
||
|
writeStatus(ctx, 404)
|
||
8 years ago
|
}
|
||
|
|
||
4 years ago
|
func getAuthenticatedRepoAndMeta(ctx *context.Context, rc *requestContext, p lfs_module.Pointer, requireWrite bool) (*models.LFSMetaObject, *models.Repository) {
|
||
|
if !isOidValid(p.Oid) {
|
||
|
log.Info("Attempt to access invalid LFS OID[%s] in %s/%s", p.Oid, rc.User, rc.Repo)
|
||
7 years ago
|
writeStatus(ctx, 404)
|
||
|
return nil, nil
|
||
|
}
|
||
|
|
||
4 years ago
|
repository, err := models.GetRepositoryByOwnerAndName(rc.User, rc.Repo)
|
||
8 years ago
|
if err != nil {
|
||
4 years ago
|
log.Error("Unable to get repository: %s/%s Error: %v", rc.User, rc.Repo, err)
|
||
8 years ago
|
writeStatus(ctx, 404)
|
||
7 years ago
|
return nil, nil
|
||
8 years ago
|
}
|
||
|
|
||
4 years ago
|
if !authenticate(ctx, repository, rc.Authorization, requireWrite) {
|
||
7 years ago
|
requireAuth(ctx)
|
||
|
return nil, nil
|
||
|
}
|
||
8 years ago
|
|
||
4 years ago
|
meta, err := repository.GetLFSMetaObjectByOid(p.Oid)
|
||
8 years ago
|
if err != nil {
|
||
4 years ago
|
log.Error("Unable to get LFS OID[%s] Error: %v", p.Oid, err)
|
||
8 years ago
|
writeStatus(ctx, 404)
|
||
7 years ago
|
return nil, nil
|
||
8 years ago
|
}
|
||
|
|
||
7 years ago
|
return meta, repository
|
||
|
}
|
||
|
|
||
|
// getContentHandler gets the content from the content store
|
||
|
func getContentHandler(ctx *context.Context) {
|
||
4 years ago
|
rc, p := unpack(ctx)
|
||
7 years ago
|
|
||
4 years ago
|
meta, _ := getAuthenticatedRepoAndMeta(ctx, rc, p, false)
|
||
7 years ago
|
if meta == nil {
|
||
5 years ago
|
// Status already written in getAuthenticatedRepoAndMeta
|
||
8 years ago
|
return
|
||
|
}
|
||
|
|
||
|
// Support resume download using Range header
|
||
5 years ago
|
var fromByte, toByte int64
|
||
|
toByte = meta.Size - 1
|
||
8 years ago
|
statusCode := 200
|
||
|
if rangeHdr := ctx.Req.Header.Get("Range"); rangeHdr != "" {
|
||
5 years ago
|
regex := regexp.MustCompile(`bytes=(\d+)\-(\d*).*`)
|
||
8 years ago
|
match := regex.FindStringSubmatch(rangeHdr)
|
||
6 years ago
|
if len(match) > 1 {
|
||
8 years ago
|
statusCode = 206
|
||
|
fromByte, _ = strconv.ParseInt(match[1], 10, 32)
|
||
5 years ago
|
|
||
4 years ago
|
if fromByte >= meta.Size {
|
||
|
writeStatus(ctx, http.StatusRequestedRangeNotSatisfiable)
|
||
|
return
|
||
|
}
|
||
|
|
||
5 years ago
|
if match[2] != "" {
|
||
|
_toByte, _ := strconv.ParseInt(match[2], 10, 32)
|
||
|
if _toByte >= fromByte && _toByte < toByte {
|
||
|
toByte = _toByte
|
||
|
}
|
||
|
}
|
||
|
|
||
|
ctx.Resp.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", fromByte, toByte, meta.Size-fromByte))
|
||
4 years ago
|
ctx.Resp.Header().Set("Access-Control-Expose-Headers", "Content-Range")
|
||
8 years ago
|
}
|
||
|
}
|
||
|
|
||
4 years ago
|
contentStore := lfs_module.NewContentStore()
|
||
|
content, err := contentStore.Get(meta.Pointer)
|
||
8 years ago
|
if err != nil {
|
||
4 years ago
|
// Errors are logged in contentStore.Get
|
||
|
writeStatus(ctx, http.StatusNotFound)
|
||
8 years ago
|
return
|
||
|
}
|
||
5 years ago
|
defer content.Close()
|
||
8 years ago
|
|
||
4 years ago
|
if fromByte > 0 {
|
||
|
_, err = content.Seek(fromByte, io.SeekStart)
|
||
|
if err != nil {
|
||
|
log.Error("Whilst trying to read LFS OID[%s]: Unable to seek to %d Error: %v", meta.Oid, fromByte, err)
|
||
|
|
||
|
writeStatus(ctx, http.StatusInternalServerError)
|
||
|
return
|
||
|
}
|
||
|
}
|
||
|
|
||
5 years ago
|
contentLength := toByte + 1 - fromByte
|
||
|
ctx.Resp.Header().Set("Content-Length", strconv.FormatInt(contentLength, 10))
|
||
8 years ago
|
ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
|
||
|
|
||
|
filename := ctx.Params("filename")
|
||
|
if len(filename) > 0 {
|
||
|
decodedFilename, err := base64.RawURLEncoding.DecodeString(filename)
|
||
|
if err == nil {
|
||
|
ctx.Resp.Header().Set("Content-Disposition", "attachment; filename=\""+string(decodedFilename)+"\"")
|
||
4 years ago
|
ctx.Resp.Header().Set("Access-Control-Expose-Headers", "Content-Disposition")
|
||
8 years ago
|
}
|
||
|
}
|
||
|
|
||
|
ctx.Resp.WriteHeader(statusCode)
|
||
5 years ago
|
if written, err := io.CopyN(ctx.Resp, content, contentLength); err != nil {
|
||
5 years ago
|
log.Error("Error whilst copying LFS OID[%s] to the response after %d bytes. Error: %v", meta.Oid, written, err)
|
||
|
}
|
||
8 years ago
|
logRequest(ctx.Req, statusCode)
|
||
|
}
|
||
|
|
||
7 years ago
|
// getMetaHandler retrieves metadata about the object
|
||
|
func getMetaHandler(ctx *context.Context) {
|
||
4 years ago
|
rc, p := unpack(ctx)
|
||
8 years ago
|
|
||
4 years ago
|
meta, _ := getAuthenticatedRepoAndMeta(ctx, rc, p, false)
|
||
7 years ago
|
if meta == nil {
|
||
5 years ago
|
// Status already written in getAuthenticatedRepoAndMeta
|
||
8 years ago
|
return
|
||
|
}
|
||
|
|
||
4 years ago
|
ctx.Resp.Header().Set("Content-Type", lfs_module.MediaType)
|
||
8 years ago
|
|
||
|
if ctx.Req.Method == "GET" {
|
||
4 years ago
|
json := jsoniter.ConfigCompatibleWithStandardLibrary
|
||
8 years ago
|
enc := json.NewEncoder(ctx.Resp)
|
||
4 years ago
|
if err := enc.Encode(represent(rc, meta.Pointer, true, false)); err != nil {
|
||
5 years ago
|
log.Error("Failed to encode representation as json. Error: %v", err)
|
||
|
}
|
||
8 years ago
|
}
|
||
|
|
||
|
logRequest(ctx.Req, 200)
|
||
|
}
|
||
|
|
||
|
// PostHandler instructs the client how to upload data
|
||
|
func PostHandler(ctx *context.Context) {
|
||
|
if !setting.LFS.StartServer {
|
||
5 years ago
|
log.Debug("Attempt to access LFS server but LFS server is disabled")
|
||
8 years ago
|
writeStatus(ctx, 404)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
if !MetaMatcher(ctx.Req) {
|
||
4 years ago
|
log.Info("Attempt to POST without accepting the correct media type: %s", lfs_module.MediaType)
|
||
8 years ago
|
writeStatus(ctx, 400)
|
||
|
return
|
||
|
}
|
||
|
|
||
4 years ago
|
rc, p := unpack(ctx)
|
||
8 years ago
|
|
||
4 years ago
|
repository, err := models.GetRepositoryByOwnerAndName(rc.User, rc.Repo)
|
||
8 years ago
|
if err != nil {
|
||
4 years ago
|
log.Error("Unable to get repository: %s/%s Error: %v", rc.User, rc.Repo, err)
|
||
8 years ago
|
writeStatus(ctx, 404)
|
||
|
return
|
||
|
}
|
||
|
|
||
4 years ago
|
if !authenticate(ctx, repository, rc.Authorization, true) {
|
||
8 years ago
|
requireAuth(ctx)
|
||
7 years ago
|
return
|
||
|
}
|
||
|
|
||
4 years ago
|
if !isOidValid(p.Oid) {
|
||
|
log.Info("Invalid LFS OID[%s] attempt to POST in %s/%s", p.Oid, rc.User, rc.Repo)
|
||
7 years ago
|
writeStatus(ctx, 404)
|
||
|
return
|
||
8 years ago
|
}
|
||
|
|
||
4 years ago
|
if setting.LFS.MaxFileSize > 0 && p.Size > setting.LFS.MaxFileSize {
|
||
|
log.Info("Denied LFS OID[%s] upload of size %d to %s/%s because of LFS_MAX_FILE_SIZE=%d", p.Oid, p.Size, rc.User, rc.Repo, setting.LFS.MaxFileSize)
|
||
5 years ago
|
writeStatus(ctx, 413)
|
||
|
return
|
||
|
}
|
||
|
|
||
4 years ago
|
meta, err := models.NewLFSMetaObject(&models.LFSMetaObject{Pointer: p, RepositoryID: repository.ID})
|
||
8 years ago
|
if err != nil {
|
||
4 years ago
|
log.Error("Unable to write LFS OID[%s] size %d meta object in %v/%v to database. Error: %v", p.Oid, p.Size, rc.User, rc.Repo, err)
|
||
8 years ago
|
writeStatus(ctx, 404)
|
||
|
return
|
||
|
}
|
||
|
|
||
4 years ago
|
ctx.Resp.Header().Set("Content-Type", lfs_module.MediaType)
|
||
8 years ago
|
|
||
|
sentStatus := 202
|
||
4 years ago
|
contentStore := lfs_module.NewContentStore()
|
||
|
exist, err := contentStore.Exists(p)
|
||
4 years ago
|
if err != nil {
|
||
4 years ago
|
log.Error("Unable to check if LFS OID[%s] exist on %s / %s. Error: %v", p.Oid, rc.User, rc.Repo, err)
|
||
4 years ago
|
writeStatus(ctx, 500)
|
||
|
return
|
||
|
}
|
||
|
if meta.Existing && exist {
|
||
8 years ago
|
sentStatus = 200
|
||
|
}
|
||
|
ctx.Resp.WriteHeader(sentStatus)
|
||
|
|
||
4 years ago
|
json := jsoniter.ConfigCompatibleWithStandardLibrary
|
||
8 years ago
|
enc := json.NewEncoder(ctx.Resp)
|
||
4 years ago
|
if err := enc.Encode(represent(rc, meta.Pointer, meta.Existing, true)); err != nil {
|
||
5 years ago
|
log.Error("Failed to encode representation as json. Error: %v", err)
|
||
|
}
|
||
8 years ago
|
logRequest(ctx.Req, sentStatus)
|
||
|
}
|
||
|
|
||
|
// BatchHandler provides the batch api
|
||
|
func BatchHandler(ctx *context.Context) {
|
||
|
if !setting.LFS.StartServer {
|
||
5 years ago
|
log.Debug("Attempt to access LFS server but LFS server is disabled")
|
||
8 years ago
|
writeStatus(ctx, 404)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
if !MetaMatcher(ctx.Req) {
|
||
4 years ago
|
log.Info("Attempt to BATCH without accepting the correct media type: %s", lfs_module.MediaType)
|
||
8 years ago
|
writeStatus(ctx, 400)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
bv := unpackbatch(ctx)
|
||
|
|
||
4 years ago
|
reqCtx := &requestContext{
|
||
|
User: ctx.Params("username"),
|
||
|
Repo: strings.TrimSuffix(ctx.Params("reponame"), ".git"),
|
||
|
Authorization: ctx.Req.Header.Get("Authorization"),
|
||
|
}
|
||
|
|
||
|
var responseObjects []*lfs_module.ObjectResponse
|
||
8 years ago
|
|
||
|
// Create a response object
|
||
|
for _, object := range bv.Objects {
|
||
7 years ago
|
if !isOidValid(object.Oid) {
|
||
4 years ago
|
log.Info("Invalid LFS OID[%s] attempt to BATCH in %s/%s", object.Oid, reqCtx.User, reqCtx.Repo)
|
||
7 years ago
|
continue
|
||
|
}
|
||
|
|
||
4 years ago
|
repository, err := models.GetRepositoryByOwnerAndName(reqCtx.User, reqCtx.Repo)
|
||
8 years ago
|
if err != nil {
|
||
4 years ago
|
log.Error("Unable to get repository: %s/%s Error: %v", reqCtx.User, reqCtx.Repo, err)
|
||
8 years ago
|
writeStatus(ctx, 404)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
requireWrite := false
|
||
|
if bv.Operation == "upload" {
|
||
|
requireWrite = true
|
||
|
}
|
||
|
|
||
4 years ago
|
if !authenticate(ctx, repository, reqCtx.Authorization, requireWrite) {
|
||
8 years ago
|
requireAuth(ctx)
|
||
|
return
|
||
|
}
|
||
|
|
||
4 years ago
|
contentStore := lfs_module.NewContentStore()
|
||
7 years ago
|
|
||
|
meta, err := repository.GetLFSMetaObjectByOid(object.Oid)
|
||
4 years ago
|
if err == nil { // Object is found and exists
|
||
4 years ago
|
exist, err := contentStore.Exists(meta.Pointer)
|
||
4 years ago
|
if err != nil {
|
||
4 years ago
|
log.Error("Unable to check if LFS OID[%s] exist on %s / %s. Error: %v", object.Oid, reqCtx.User, reqCtx.Repo, err)
|
||
4 years ago
|
writeStatus(ctx, 500)
|
||
|
return
|
||
|
}
|
||
|
if exist {
|
||
4 years ago
|
responseObjects = append(responseObjects, represent(reqCtx, meta.Pointer, true, false))
|
||
4 years ago
|
continue
|
||
|
}
|
||
8 years ago
|
}
|
||
|
|
||
5 years ago
|
if requireWrite && setting.LFS.MaxFileSize > 0 && object.Size > setting.LFS.MaxFileSize {
|
||
4 years ago
|
log.Info("Denied LFS OID[%s] upload of size %d to %s/%s because of LFS_MAX_FILE_SIZE=%d", object.Oid, object.Size, reqCtx.User, reqCtx.Repo, setting.LFS.MaxFileSize)
|
||
5 years ago
|
writeStatus(ctx, 413)
|
||
|
return
|
||
|
}
|
||
|
|
||
7 years ago
|
// Object is not found
|
||
4 years ago
|
meta, err = models.NewLFSMetaObject(&models.LFSMetaObject{Pointer: object, RepositoryID: repository.ID})
|
||
7 years ago
|
if err == nil {
|
||
4 years ago
|
exist, err := contentStore.Exists(meta.Pointer)
|
||
4 years ago
|
if err != nil {
|
||
4 years ago
|
log.Error("Unable to check if LFS OID[%s] exist on %s / %s. Error: %v", object.Oid, reqCtx.User, reqCtx.Repo, err)
|
||
4 years ago
|
writeStatus(ctx, 500)
|
||
|
return
|
||
|
}
|
||
4 years ago
|
responseObjects = append(responseObjects, represent(reqCtx, meta.Pointer, meta.Existing, !exist))
|
||
5 years ago
|
} else {
|
||
4 years ago
|
log.Error("Unable to write LFS OID[%s] size %d meta object in %v/%v to database. Error: %v", object.Oid, object.Size, reqCtx.User, reqCtx.Repo, err)
|
||
8 years ago
|
}
|
||
|
}
|
||
|
|
||
4 years ago
|
ctx.Resp.Header().Set("Content-Type", lfs_module.MediaType)
|
||
8 years ago
|
|
||
4 years ago
|
respobj := &lfs_module.BatchResponse{Objects: responseObjects}
|
||
8 years ago
|
|
||
4 years ago
|
json := jsoniter.ConfigCompatibleWithStandardLibrary
|
||
8 years ago
|
enc := json.NewEncoder(ctx.Resp)
|
||
5 years ago
|
if err := enc.Encode(respobj); err != nil {
|
||
|
log.Error("Failed to encode representation as json. Error: %v", err)
|
||
|
}
|
||
8 years ago
|
logRequest(ctx.Req, 200)
|
||
|
}
|
||
|
|
||
|
// PutHandler receives data from the client and puts it into the content store
|
||
|
func PutHandler(ctx *context.Context) {
|
||
4 years ago
|
rc, p := unpack(ctx)
|
||
8 years ago
|
|
||
4 years ago
|
meta, repository := getAuthenticatedRepoAndMeta(ctx, rc, p, true)
|
||
7 years ago
|
if meta == nil {
|
||
5 years ago
|
// Status already written in getAuthenticatedRepoAndMeta
|
||
8 years ago
|
return
|
||
|
}
|
||
|
|
||
4 years ago
|
contentStore := lfs_module.NewContentStore()
|
||
4 years ago
|
defer ctx.Req.Body.Close()
|
||
4 years ago
|
if err := contentStore.Put(meta.Pointer, ctx.Req.Body); err != nil {
|
||
5 years ago
|
// Put will log the error itself
|
||
8 years ago
|
ctx.Resp.WriteHeader(500)
|
||
4 years ago
|
if err == lfs_module.ErrSizeMismatch || err == lfs_module.ErrHashMismatch {
|
||
5 years ago
|
fmt.Fprintf(ctx.Resp, `{"message":"%s"}`, err)
|
||
|
} else {
|
||
|
fmt.Fprintf(ctx.Resp, `{"message":"Internal Server Error"}`)
|
||
|
}
|
||
4 years ago
|
if _, err = repository.RemoveLFSMetaObjectByOid(p.Oid); err != nil {
|
||
|
log.Error("Whilst removing metaobject for LFS OID[%s] due to preceding error there was another Error: %v", p.Oid, err)
|
||
7 years ago
|
}
|
||
8 years ago
|
return
|
||
|
}
|
||
|
|
||
|
logRequest(ctx.Req, 200)
|
||
|
}
|
||
|
|
||
7 years ago
|
// VerifyHandler verify oid and its size from the content store
|
||
|
func VerifyHandler(ctx *context.Context) {
|
||
|
if !setting.LFS.StartServer {
|
||
5 years ago
|
log.Debug("Attempt to access LFS server but LFS server is disabled")
|
||
7 years ago
|
writeStatus(ctx, 404)
|
||
|
return
|
||
|
}
|
||
|
|
||
6 years ago
|
if !MetaMatcher(ctx.Req) {
|
||
4 years ago
|
log.Info("Attempt to VERIFY without accepting the correct media type: %s", lfs_module.MediaType)
|
||
7 years ago
|
writeStatus(ctx, 400)
|
||
|
return
|
||
|
}
|
||
|
|
||
4 years ago
|
rc, p := unpack(ctx)
|
||
7 years ago
|
|
||
4 years ago
|
meta, _ := getAuthenticatedRepoAndMeta(ctx, rc, p, true)
|
||
7 years ago
|
if meta == nil {
|
||
5 years ago
|
// Status already written in getAuthenticatedRepoAndMeta
|
||
7 years ago
|
return
|
||
|
}
|
||
|
|
||
4 years ago
|
contentStore := lfs_module.NewContentStore()
|
||
|
ok, err := contentStore.Verify(meta.Pointer)
|
||
7 years ago
|
if err != nil {
|
||
5 years ago
|
// Error will be logged in Verify
|
||
7 years ago
|
ctx.Resp.WriteHeader(500)
|
||
5 years ago
|
fmt.Fprintf(ctx.Resp, `{"message":"Internal Server Error"}`)
|
||
7 years ago
|
return
|
||
|
}
|
||
|
if !ok {
|
||
|
writeStatus(ctx, 422)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
logRequest(ctx.Req, 200)
|
||
|
}
|
||
|
|
||
4 years ago
|
// represent takes a requestContext and Meta and turns it into a ObjectResponse suitable
|
||
8 years ago
|
// for json encoding
|
||
4 years ago
|
func represent(rc *requestContext, pointer lfs_module.Pointer, download, upload bool) *lfs_module.ObjectResponse {
|
||
|
rep := &lfs_module.ObjectResponse{
|
||
|
Pointer: pointer,
|
||
|
Actions: make(map[string]*lfs_module.Link),
|
||
8 years ago
|
}
|
||
|
|
||
|
header := make(map[string]string)
|
||
|
|
||
4 years ago
|
if rc.Authorization == "" {
|
||
8 years ago
|
//https://github.com/github/git-lfs/issues/1088
|
||
|
header["Authorization"] = "Authorization: Basic dummy"
|
||
|
} else {
|
||
4 years ago
|
header["Authorization"] = rc.Authorization
|
||
8 years ago
|
}
|
||
|
|
||
|
if download {
|
||
4 years ago
|
rep.Actions["download"] = &lfs_module.Link{Href: rc.ObjectLink(pointer.Oid), Header: header}
|
||
8 years ago
|
}
|
||
|
|
||
|
if upload {
|
||
4 years ago
|
rep.Actions["upload"] = &lfs_module.Link{Href: rc.ObjectLink(pointer.Oid), Header: header}
|
||
8 years ago
|
}
|
||
|
|
||
7 years ago
|
if upload && !download {
|
||
|
// Force client side verify action while gitea lacks proper server side verification
|
||
6 years ago
|
verifyHeader := make(map[string]string)
|
||
|
for k, v := range header {
|
||
|
verifyHeader[k] = v
|
||
|
}
|
||
|
|
||
|
// This is only needed to workaround https://github.com/git-lfs/git-lfs/issues/3662
|
||
4 years ago
|
verifyHeader["Accept"] = lfs_module.MediaType
|
||
6 years ago
|
|
||
4 years ago
|
rep.Actions["verify"] = &lfs_module.Link{Href: rc.VerifyLink(), Header: verifyHeader}
|
||
7 years ago
|
}
|
||
|
|
||
8 years ago
|
return rep
|
||
|
}
|
||
|
|
||
|
// MetaMatcher provides a mux.MatcherFunc that only allows requests that contain
|
||
4 years ago
|
// an Accept header with the lfs_module.MediaType
|
||
4 years ago
|
func MetaMatcher(r *http.Request) bool {
|
||
8 years ago
|
mediaParts := strings.Split(r.Header.Get("Accept"), ";")
|
||
|
mt := mediaParts[0]
|
||
4 years ago
|
return mt == lfs_module.MediaType
|
||
8 years ago
|
}
|
||
|
|
||
4 years ago
|
func unpack(ctx *context.Context) (*requestContext, lfs_module.Pointer) {
|
||
8 years ago
|
r := ctx.Req
|
||
4 years ago
|
rc := &requestContext{
|
||
8 years ago
|
User: ctx.Params("username"),
|
||
|
Repo: strings.TrimSuffix(ctx.Params("reponame"), ".git"),
|
||
|
Authorization: r.Header.Get("Authorization"),
|
||
|
}
|
||
4 years ago
|
p := lfs_module.Pointer{Oid: ctx.Params("oid")}
|
||
8 years ago
|
|
||
|
if r.Method == "POST" { // Maybe also check if +json
|
||
4 years ago
|
var p2 lfs_module.Pointer
|
||
4 years ago
|
bodyReader := r.Body
|
||
5 years ago
|
defer bodyReader.Close()
|
||
4 years ago
|
json := jsoniter.ConfigCompatibleWithStandardLibrary
|
||
5 years ago
|
dec := json.NewDecoder(bodyReader)
|
||
4 years ago
|
err := dec.Decode(&p2)
|
||
8 years ago
|
if err != nil {
|
||
5 years ago
|
// The error is logged as a WARN here because this may represent misbehaviour rather than a true error
|
||
4 years ago
|
log.Warn("Unable to decode POST request vars for LFS OID[%s] in %s/%s: Error: %v", p.Oid, rc.User, rc.Repo, err)
|
||
|
return rc, p
|
||
8 years ago
|
}
|
||
|
|
||
4 years ago
|
p.Oid = p2.Oid
|
||
|
p.Size = p2.Size
|
||
8 years ago
|
}
|
||
|
|
||
4 years ago
|
return rc, p
|
||
8 years ago
|
}
|
||
|
|
||
|
// TODO cheap hack, unify with unpack
|
||
4 years ago
|
func unpackbatch(ctx *context.Context) *lfs_module.BatchRequest {
|
||
8 years ago
|
|
||
|
r := ctx.Req
|
||
4 years ago
|
var bv lfs_module.BatchRequest
|
||
8 years ago
|
|
||
4 years ago
|
bodyReader := r.Body
|
||
5 years ago
|
defer bodyReader.Close()
|
||
4 years ago
|
json := jsoniter.ConfigCompatibleWithStandardLibrary
|
||
5 years ago
|
dec := json.NewDecoder(bodyReader)
|
||
8 years ago
|
err := dec.Decode(&bv)
|
||
|
if err != nil {
|
||
5 years ago
|
// The error is logged as a WARN here because this may represent misbehaviour rather than a true error
|
||
|
log.Warn("Unable to decode BATCH request vars in %s/%s: Error: %v", ctx.Params("username"), strings.TrimSuffix(ctx.Params("reponame"), ".git"), err)
|
||
8 years ago
|
return &bv
|
||
|
}
|
||
|
|
||
|
return &bv
|
||
|
}
|
||
|
|
||
|
func writeStatus(ctx *context.Context, status int) {
|
||
|
message := http.StatusText(status)
|
||
|
|
||
|
mediaParts := strings.Split(ctx.Req.Header.Get("Accept"), ";")
|
||
|
mt := mediaParts[0]
|
||
|
if strings.HasSuffix(mt, "+json") {
|
||
|
message = `{"message":"` + message + `"}`
|
||
|
}
|
||
|
|
||
|
ctx.Resp.WriteHeader(status)
|
||
|
fmt.Fprint(ctx.Resp, message)
|
||
|
logRequest(ctx.Req, status)
|
||
|
}
|
||
|
|
||
4 years ago
|
func logRequest(r *http.Request, status int) {
|
||
8 years ago
|
log.Debug("LFS request - Method: %s, URL: %s, Status %d", r.Method, r.URL, status)
|
||
|
}
|
||
|
|
||
|
// authenticate uses the authorization string to determine whether
|
||
|
// or not to proceed. This server assumes an HTTP Basic auth format.
|
||
|
func authenticate(ctx *context.Context, repository *models.Repository, authorization string, requireWrite bool) bool {
|
||
|
accessMode := models.AccessModeRead
|
||
|
if requireWrite {
|
||
|
accessMode = models.AccessModeWrite
|
||
|
}
|
||
|
|
||
6 years ago
|
// ctx.IsSigned is unnecessary here, this will be checked in perm.CanAccess
|
||
6 years ago
|
perm, err := models.GetUserRepoPermission(repository, ctx.User)
|
||
|
if err != nil {
|
||
5 years ago
|
log.Error("Unable to GetUserRepoPermission for user %-v in repo %-v Error: %v", ctx.User, repository)
|
||
6 years ago
|
return false
|
||
8 years ago
|
}
|
||
6 years ago
|
|
||
|
canRead := perm.CanAccess(accessMode, models.UnitTypeCode)
|
||
|
if canRead {
|
||
|
return true
|
||
8 years ago
|
}
|
||
|
|
||
7 years ago
|
user, repo, opStr, err := parseToken(authorization)
|
||
8 years ago
|
if err != nil {
|
||
5 years ago
|
// Most of these are Warn level - the true internal server errors are logged in parseToken already
|
||
|
log.Warn("Authentication failure for provided token with Error: %v", err)
|
||
8 years ago
|
return false
|
||
|
}
|
||
7 years ago
|
ctx.User = user
|
||
|
if opStr == "basic" {
|
||
6 years ago
|
perm, err = models.GetUserRepoPermission(repository, ctx.User)
|
||
|
if err != nil {
|
||
5 years ago
|
log.Error("Unable to GetUserRepoPermission for user %-v in repo %-v Error: %v", ctx.User, repository)
|
||
6 years ago
|
return false
|
||
|
}
|
||
|
return perm.CanAccess(accessMode, models.UnitTypeCode)
|
||
8 years ago
|
}
|
||
7 years ago
|
if repository.ID == repo.ID {
|
||
|
if requireWrite && opStr != "upload" {
|
||
|
return false
|
||
|
}
|
||
|
return true
|
||
8 years ago
|
}
|
||
7 years ago
|
return false
|
||
8 years ago
|
}
|
||
|
|
||
7 years ago
|
func parseToken(authorization string) (*models.User, *models.Repository, string, error) {
|
||
|
if authorization == "" {
|
||
|
return nil, nil, "unknown", fmt.Errorf("No token")
|
||
|
}
|
||
|
if strings.HasPrefix(authorization, "Bearer ") {
|
||
5 years ago
|
token, err := jwt.ParseWithClaims(authorization[7:], &Claims{}, func(t *jwt.Token) (interface{}, error) {
|
||
7 years ago
|
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||
|
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
|
||
|
}
|
||
|
return setting.LFS.JWTSecretBytes, nil
|
||
|
})
|
||
|
if err != nil {
|
||
5 years ago
|
// The error here is WARN level because it is caused by bad authorization rather than an internal server error
|
||
7 years ago
|
return nil, nil, "unknown", err
|
||
8 years ago
|
}
|
||
5 years ago
|
claims, claimsOk := token.Claims.(*Claims)
|
||
7 years ago
|
if !token.Valid || !claimsOk {
|
||
|
return nil, nil, "unknown", fmt.Errorf("Token claim invalid")
|
||
|
}
|
||
5 years ago
|
r, err := models.GetRepositoryByID(claims.RepoID)
|
||
7 years ago
|
if err != nil {
|
||
5 years ago
|
log.Error("Unable to GetRepositoryById[%d]: Error: %v", claims.RepoID, err)
|
||
|
return nil, nil, claims.Op, err
|
||
7 years ago
|
}
|
||
5 years ago
|
u, err := models.GetUserByID(claims.UserID)
|
||
7 years ago
|
if err != nil {
|
||
5 years ago
|
log.Error("Unable to GetUserById[%d]: Error: %v", claims.UserID, err)
|
||
|
return nil, r, claims.Op, err
|
||
7 years ago
|
}
|
||
5 years ago
|
return u, r, claims.Op, nil
|
||
8 years ago
|
}
|
||
|
|
||
7 years ago
|
if strings.HasPrefix(authorization, "Basic ") {
|
||
|
c, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(authorization, "Basic "))
|
||
|
if err != nil {
|
||
|
return nil, nil, "basic", err
|
||
|
}
|
||
|
cs := string(c)
|
||
|
i := strings.IndexByte(cs, ':')
|
||
|
if i < 0 {
|
||
|
return nil, nil, "basic", fmt.Errorf("Basic auth invalid")
|
||
|
}
|
||
|
user, password := cs[:i], cs[i+1:]
|
||
|
u, err := models.GetUserByName(user)
|
||
|
if err != nil {
|
||
5 years ago
|
log.Error("Unable to GetUserByName[%d]: Error: %v", user, err)
|
||
7 years ago
|
return nil, nil, "basic", err
|
||
|
}
|
||
6 years ago
|
if !u.IsPasswordSet() || !u.ValidatePassword(password) {
|
||
7 years ago
|
return nil, nil, "basic", fmt.Errorf("Basic auth failed")
|
||
|
}
|
||
|
return u, nil, "basic", nil
|
||
8 years ago
|
}
|
||
|
|
||
7 years ago
|
return nil, nil, "unknown", fmt.Errorf("Token not found")
|
||
8 years ago
|
}
|
||
|
|
||
|
func requireAuth(ctx *context.Context) {
|
||
|
ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs")
|
||
|
writeStatus(ctx, 401)
|
||
|
}
|