debian-mirror-gitlab/workhorse/internal/upload/uploads_test.go

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

547 lines
16 KiB
Go
Raw Normal View History

2021-02-22 17:27:13 +05:30
package upload
import (
2022-04-04 11:22:00 +05:30
"bufio"
2021-02-22 17:27:13 +05:30
"bytes"
"context"
"fmt"
2022-04-04 11:22:00 +05:30
"io"
2021-02-22 17:27:13 +05:30
"mime/multipart"
"net/http"
"net/http/httptest"
2022-04-04 11:22:00 +05:30
"net/textproto"
2021-02-22 17:27:13 +05:30
"os"
2022-07-23 23:45:48 +05:30
"path"
2021-02-22 17:27:13 +05:30
"regexp"
"strconv"
"strings"
"testing"
"time"
"github.com/stretchr/testify/require"
2021-10-27 15:23:28 +05:30
"gitlab.com/gitlab-org/gitlab/workhorse/internal/api"
"gitlab.com/gitlab-org/gitlab/workhorse/internal/helper"
"gitlab.com/gitlab-org/gitlab/workhorse/internal/proxy"
"gitlab.com/gitlab-org/gitlab/workhorse/internal/testhelper"
2022-08-13 15:12:31 +05:30
"gitlab.com/gitlab-org/gitlab/workhorse/internal/upload/destination"
2022-05-07 20:08:51 +05:30
"gitlab.com/gitlab-org/gitlab/workhorse/internal/upload/destination/objectstore/test"
2021-10-27 15:23:28 +05:30
"gitlab.com/gitlab-org/gitlab/workhorse/internal/upstream/roundtripper"
2021-02-22 17:27:13 +05:30
)
var nilHandler = http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})
2021-10-29 20:43:33 +05:30
type testFormProcessor struct{ SavedFileTracker }
2021-02-22 17:27:13 +05:30
func (a *testFormProcessor) ProcessField(ctx context.Context, formName string, writer *multipart.Writer) error {
if formName != "token" && !strings.HasPrefix(formName, "file.") && !strings.HasPrefix(formName, "other.") {
return fmt.Errorf("illegal field: %v", formName)
}
return nil
}
func (a *testFormProcessor) Finalize(ctx context.Context) error {
return nil
}
func TestUploadTempPathRequirement(t *testing.T) {
apiResponse := &api.Response{}
preparer := &DefaultPreparer{}
2022-07-16 23:28:13 +05:30
_, err := preparer.Prepare(apiResponse)
2021-02-22 17:27:13 +05:30
require.Error(t, err)
}
func TestUploadHandlerForwardingRawData(t *testing.T) {
ts := testhelper.TestServerWithHandler(regexp.MustCompile(`/url/path\z`), func(w http.ResponseWriter, r *http.Request) {
require.Equal(t, "PATCH", r.Method, "method")
2022-07-23 23:45:48 +05:30
body, err := io.ReadAll(r.Body)
2021-02-22 17:27:13 +05:30
require.NoError(t, err)
require.Equal(t, "REQUEST", string(body), "request body")
w.WriteHeader(202)
fmt.Fprint(w, "RESPONSE")
})
defer ts.Close()
httpRequest, err := http.NewRequest("PATCH", ts.URL+"/url/path", bytes.NewBufferString("REQUEST"))
require.NoError(t, err)
2022-07-23 23:45:48 +05:30
tempPath := t.TempDir()
2021-02-22 17:27:13 +05:30
response := httptest.NewRecorder()
handler := newProxy(ts.URL)
2022-07-23 23:45:48 +05:30
fa := &eagerAuthorizer{&api.Response{TempPath: tempPath}}
2021-02-22 17:27:13 +05:30
preparer := &DefaultPreparer{}
2022-07-23 23:45:48 +05:30
interceptMultipartFiles(response, httpRequest, handler, nil, fa, preparer)
2021-02-22 17:27:13 +05:30
require.Equal(t, 202, response.Code)
require.Equal(t, "RESPONSE", response.Body.String(), "response body")
}
func TestUploadHandlerRewritingMultiPartData(t *testing.T) {
var filePath string
2022-07-23 23:45:48 +05:30
tempPath := t.TempDir()
2021-02-22 17:27:13 +05:30
ts := testhelper.TestServerWithHandler(regexp.MustCompile(`/url/path\z`), func(w http.ResponseWriter, r *http.Request) {
require.Equal(t, "PUT", r.Method, "method")
require.NoError(t, r.ParseMultipartForm(100000))
require.Empty(t, r.MultipartForm.File, "Expected to not receive any files")
require.Equal(t, "test", r.FormValue("token"), "Expected to receive token")
require.Equal(t, "my.file", r.FormValue("file.name"), "Expected to receive a filename")
filePath = r.FormValue("file.path")
require.True(t, strings.HasPrefix(filePath, tempPath), "Expected to the file to be in tempPath")
require.Empty(t, r.FormValue("file.remote_url"), "Expected to receive empty remote_url")
require.Empty(t, r.FormValue("file.remote_id"), "Expected to receive empty remote_id")
require.Equal(t, "4", r.FormValue("file.size"), "Expected to receive the file size")
hashes := map[string]string{
"sha1": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3",
"sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
"sha512": "ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff",
}
for algo, hash := range hashes {
require.Equal(t, hash, r.FormValue("file."+algo), "file hash %s", algo)
}
2022-08-13 15:12:31 +05:30
expectedLen := 12
if destination.FIPSEnabled() {
expectedLen--
require.Empty(t, r.FormValue("file.md5"), "file hash md5")
} else {
require.Equal(t, "098f6bcd4621d373cade4e832627b4f6", r.FormValue("file.md5"), "file hash md5")
}
require.Len(t, r.MultipartForm.Value, expectedLen, "multipart form values")
2021-02-22 17:27:13 +05:30
w.WriteHeader(202)
fmt.Fprint(w, "RESPONSE")
})
var buffer bytes.Buffer
writer := multipart.NewWriter(&buffer)
writer.WriteField("token", "test")
file, err := writer.CreateFormFile("file", "my.file")
require.NoError(t, err)
fmt.Fprint(file, "test")
writer.Close()
httpRequest, err := http.NewRequest("PUT", ts.URL+"/url/path", nil)
require.NoError(t, err)
ctx, cancel := context.WithCancel(context.Background())
httpRequest = httpRequest.WithContext(ctx)
2022-07-23 23:45:48 +05:30
httpRequest.Body = io.NopCloser(&buffer)
2021-02-22 17:27:13 +05:30
httpRequest.ContentLength = int64(buffer.Len())
httpRequest.Header.Set("Content-Type", writer.FormDataContentType())
response := httptest.NewRecorder()
handler := newProxy(ts.URL)
2022-07-23 23:45:48 +05:30
fa := &eagerAuthorizer{&api.Response{TempPath: tempPath}}
2021-02-22 17:27:13 +05:30
preparer := &DefaultPreparer{}
2022-07-23 23:45:48 +05:30
interceptMultipartFiles(response, httpRequest, handler, &testFormProcessor{}, fa, preparer)
2021-02-22 17:27:13 +05:30
require.Equal(t, 202, response.Code)
cancel() // this will trigger an async cleanup
waitUntilDeleted(t, filePath)
}
func TestUploadHandlerDetectingInjectedMultiPartData(t *testing.T) {
var filePath string
tests := []struct {
name string
field string
response int
}{
{
name: "injected file.path",
field: "file.path",
response: 400,
},
{
name: "injected file.remote_id",
field: "file.remote_id",
response: 400,
},
{
name: "field with other prefix",
field: "other.path",
response: 202,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
ts := testhelper.TestServerWithHandler(regexp.MustCompile(`/url/path\z`), func(w http.ResponseWriter, r *http.Request) {
require.Equal(t, "PUT", r.Method, "method")
w.WriteHeader(202)
fmt.Fprint(w, "RESPONSE")
})
var buffer bytes.Buffer
writer := multipart.NewWriter(&buffer)
file, err := writer.CreateFormFile("file", "my.file")
require.NoError(t, err)
fmt.Fprint(file, "test")
writer.WriteField(test.field, "value")
writer.Close()
httpRequest, err := http.NewRequest("PUT", ts.URL+"/url/path", &buffer)
require.NoError(t, err)
ctx, cancel := context.WithCancel(context.Background())
httpRequest = httpRequest.WithContext(ctx)
httpRequest.Header.Set("Content-Type", writer.FormDataContentType())
response := httptest.NewRecorder()
handler := newProxy(ts.URL)
2022-07-23 23:45:48 +05:30
testInterceptMultipartFiles(t, response, httpRequest, handler, &testFormProcessor{})
2021-02-22 17:27:13 +05:30
require.Equal(t, test.response, response.Code)
cancel() // this will trigger an async cleanup
waitUntilDeleted(t, filePath)
})
}
}
func TestUploadProcessingField(t *testing.T) {
var buffer bytes.Buffer
writer := multipart.NewWriter(&buffer)
writer.WriteField("token2", "test")
writer.Close()
httpRequest, err := http.NewRequest("PUT", "/url/path", &buffer)
require.NoError(t, err)
httpRequest.Header.Set("Content-Type", writer.FormDataContentType())
response := httptest.NewRecorder()
2022-07-23 23:45:48 +05:30
testInterceptMultipartFiles(t, response, httpRequest, nilHandler, &testFormProcessor{})
2021-02-22 17:27:13 +05:30
require.Equal(t, 500, response.Code)
}
2021-10-29 20:43:33 +05:30
func TestUploadingMultipleFiles(t *testing.T) {
testhelper.ConfigureSecret()
var buffer bytes.Buffer
writer := multipart.NewWriter(&buffer)
2022-01-26 12:08:38 +05:30
for i := 0; i < 11; i++ {
2022-07-23 23:45:48 +05:30
_, err := writer.CreateFormFile(fmt.Sprintf("file %v", i), "my.file")
2022-01-26 12:08:38 +05:30
require.NoError(t, err)
}
2021-10-29 20:43:33 +05:30
require.NoError(t, writer.Close())
httpRequest, err := http.NewRequest("PUT", "/url/path", &buffer)
require.NoError(t, err)
httpRequest.Header.Set("Content-Type", writer.FormDataContentType())
response := httptest.NewRecorder()
2022-07-23 23:45:48 +05:30
testInterceptMultipartFiles(t, response, httpRequest, nilHandler, &testFormProcessor{})
2021-10-29 20:43:33 +05:30
require.Equal(t, 400, response.Code)
2022-01-26 12:08:38 +05:30
require.Equal(t, "upload request contains more than 10 files\n", response.Body.String())
2021-10-29 20:43:33 +05:30
}
2021-02-22 17:27:13 +05:30
func TestUploadProcessingFile(t *testing.T) {
2022-07-23 23:45:48 +05:30
testhelper.ConfigureSecret()
tempPath := t.TempDir()
2021-02-22 17:27:13 +05:30
2022-07-23 23:45:48 +05:30
objectStore, testServer := test.StartObjectStore()
2021-02-22 17:27:13 +05:30
defer testServer.Close()
storeUrl := testServer.URL + test.ObjectPath
tests := []struct {
name string
2021-11-18 22:05:49 +05:30
preauth *api.Response
2022-07-23 23:45:48 +05:30
content func(t *testing.T) []byte
2021-02-22 17:27:13 +05:30
}{
{
name: "FileStore Upload",
2021-11-18 22:05:49 +05:30
preauth: &api.Response{TempPath: tempPath},
2022-07-23 23:45:48 +05:30
content: func(t *testing.T) []byte {
entries, err := os.ReadDir(tempPath)
require.NoError(t, err)
require.Len(t, entries, 1)
content, err := os.ReadFile(path.Join(tempPath, entries[0].Name()))
require.NoError(t, err)
return content
},
2021-02-22 17:27:13 +05:30
},
{
name: "ObjectStore Upload",
2022-07-23 23:45:48 +05:30
preauth: &api.Response{RemoteObject: api.RemoteObject{StoreURL: storeUrl, ID: "123"}},
content: func(*testing.T) []byte { return objectStore.GetObject(test.ObjectPath) },
2021-02-22 17:27:13 +05:30
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var buffer bytes.Buffer
writer := multipart.NewWriter(&buffer)
file, err := writer.CreateFormFile("file", "my.file")
require.NoError(t, err)
fmt.Fprint(file, "test")
writer.Close()
httpRequest, err := http.NewRequest("PUT", "/url/path", &buffer)
require.NoError(t, err)
httpRequest.Header.Set("Content-Type", writer.FormDataContentType())
response := httptest.NewRecorder()
2022-07-23 23:45:48 +05:30
fa := &eagerAuthorizer{test.preauth}
2021-02-22 17:27:13 +05:30
preparer := &DefaultPreparer{}
2022-07-23 23:45:48 +05:30
interceptMultipartFiles(response, httpRequest, nilHandler, &testFormProcessor{}, fa, preparer)
2021-02-22 17:27:13 +05:30
require.Equal(t, 200, response.Code)
2022-07-23 23:45:48 +05:30
require.Equal(t, "test", string(test.content(t)))
2021-02-22 17:27:13 +05:30
})
}
}
func TestInvalidFileNames(t *testing.T) {
testhelper.ConfigureSecret()
for _, testCase := range []struct {
2021-06-08 01:23:25 +05:30
filename string
code int
expectedPrefix string
2021-02-22 17:27:13 +05:30
}{
2021-06-08 01:23:25 +05:30
{"foobar", 200, "foobar"}, // sanity check for test setup below
{"foo/bar", 200, "bar"},
{"foo/bar/baz", 200, "baz"},
{"/../../foobar", 200, "foobar"},
{".", 500, ""},
{"..", 500, ""},
{"./", 500, ""},
2021-02-22 17:27:13 +05:30
} {
buffer := &bytes.Buffer{}
writer := multipart.NewWriter(buffer)
file, err := writer.CreateFormFile("file", testCase.filename)
require.NoError(t, err)
fmt.Fprint(file, "test")
writer.Close()
httpRequest, err := http.NewRequest("POST", "/example", buffer)
require.NoError(t, err)
httpRequest.Header.Set("Content-Type", writer.FormDataContentType())
response := httptest.NewRecorder()
2022-07-23 23:45:48 +05:30
testInterceptMultipartFiles(t, response, httpRequest, nilHandler, &SavedFileTracker{Request: httpRequest})
2021-02-22 17:27:13 +05:30
require.Equal(t, testCase.code, response.Code)
}
}
2022-04-04 11:22:00 +05:30
func TestContentDispositionRewrite(t *testing.T) {
testhelper.ConfigureSecret()
tests := []struct {
desc string
header string
code int
sanitizedHeader string
}{
{
desc: "with name",
header: `form-data; name="foo"`,
code: 200,
sanitizedHeader: `form-data; name=foo`,
},
{
desc: "with name and name*",
header: `form-data; name="foo"; name*=UTF-8''bar`,
code: 200,
sanitizedHeader: `form-data; name=bar`,
},
{
desc: "with name and invalid name*",
header: `form-data; name="foo"; name*=UTF-16''bar`,
code: 200,
sanitizedHeader: `form-data; name=foo`,
},
}
for _, testCase := range tests {
t.Run(testCase.desc, func(t *testing.T) {
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition", testCase.header)
h.Set("Content-Type", "application/octet-stream")
buffer := &bytes.Buffer{}
writer := multipart.NewWriter(buffer)
file, err := writer.CreatePart(h)
require.NoError(t, err)
fmt.Fprint(file, "test")
writer.Close()
httpRequest := httptest.NewRequest("POST", "/example", buffer)
httpRequest.Header.Set("Content-Type", writer.FormDataContentType())
var upstreamRequestBuffer bytes.Buffer
customHandler := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
r.Write(&upstreamRequestBuffer)
})
response := httptest.NewRecorder()
2022-07-23 23:45:48 +05:30
testInterceptMultipartFiles(t, response, httpRequest, customHandler, &SavedFileTracker{Request: httpRequest})
2022-04-04 11:22:00 +05:30
upstreamRequest, err := http.ReadRequest(bufio.NewReader(&upstreamRequestBuffer))
require.NoError(t, err)
reader, err := upstreamRequest.MultipartReader()
require.NoError(t, err)
for i := 0; ; i++ {
p, err := reader.NextPart()
if err == io.EOF {
require.Equal(t, i, 1)
break
}
require.NoError(t, err)
require.Equal(t, testCase.sanitizedHeader, p.Header.Get("Content-Disposition"))
}
require.Equal(t, testCase.code, response.Code)
})
}
}
2021-02-22 17:27:13 +05:30
func TestUploadHandlerRemovingExif(t *testing.T) {
2022-07-23 23:45:48 +05:30
content, err := os.ReadFile("exif/testdata/sample_exif.jpg")
2021-02-22 17:27:13 +05:30
require.NoError(t, err)
2021-04-15 22:33:27 +05:30
runUploadTest(t, content, "sample_exif.jpg", 200, func(w http.ResponseWriter, r *http.Request) {
err := r.ParseMultipartForm(100000)
require.NoError(t, err)
2021-02-22 17:27:13 +05:30
2021-04-15 22:33:27 +05:30
size, err := strconv.Atoi(r.FormValue("file.size"))
require.NoError(t, err)
require.True(t, size < len(content), "Expected the file to be smaller after removal of exif")
require.True(t, size > 0, "Expected to receive not empty file")
2021-02-22 17:27:13 +05:30
2021-04-15 22:33:27 +05:30
w.WriteHeader(200)
fmt.Fprint(w, "RESPONSE")
})
}
func TestUploadHandlerRemovingExifTiff(t *testing.T) {
2022-07-23 23:45:48 +05:30
content, err := os.ReadFile("exif/testdata/sample_exif.tiff")
2021-02-22 17:27:13 +05:30
require.NoError(t, err)
2021-04-15 22:33:27 +05:30
runUploadTest(t, content, "sample_exif.tiff", 200, func(w http.ResponseWriter, r *http.Request) {
2021-02-22 17:27:13 +05:30
err := r.ParseMultipartForm(100000)
require.NoError(t, err)
size, err := strconv.Atoi(r.FormValue("file.size"))
require.NoError(t, err)
require.True(t, size < len(content), "Expected the file to be smaller after removal of exif")
require.True(t, size > 0, "Expected to receive not empty file")
w.WriteHeader(200)
fmt.Fprint(w, "RESPONSE")
})
2021-04-15 22:33:27 +05:30
}
2021-02-22 17:27:13 +05:30
2021-04-15 22:33:27 +05:30
func TestUploadHandlerRemovingExifInvalidContentType(t *testing.T) {
2022-07-23 23:45:48 +05:30
content, err := os.ReadFile("exif/testdata/sample_exif_invalid.jpg")
2021-02-22 17:27:13 +05:30
require.NoError(t, err)
2021-04-15 22:33:27 +05:30
runUploadTest(t, content, "sample_exif_invalid.jpg", 200, func(w http.ResponseWriter, r *http.Request) {
err := r.ParseMultipartForm(100000)
require.NoError(t, err)
2021-02-22 17:27:13 +05:30
2022-07-23 23:45:48 +05:30
output, err := os.ReadFile(r.FormValue("file.path"))
2021-04-15 22:33:27 +05:30
require.NoError(t, err)
require.Equal(t, content, output, "Expected the file to be same as before")
2021-02-22 17:27:13 +05:30
2021-04-15 22:33:27 +05:30
w.WriteHeader(200)
fmt.Fprint(w, "RESPONSE")
})
}
func TestUploadHandlerRemovingExifCorruptedFile(t *testing.T) {
2022-07-23 23:45:48 +05:30
content, err := os.ReadFile("exif/testdata/sample_exif_corrupted.jpg")
2021-02-22 17:27:13 +05:30
require.NoError(t, err)
2021-04-15 22:33:27 +05:30
runUploadTest(t, content, "sample_exif_corrupted.jpg", 422, func(w http.ResponseWriter, r *http.Request) {
err := r.ParseMultipartForm(100000)
require.Error(t, err)
})
2021-02-22 17:27:13 +05:30
}
2021-04-15 22:33:27 +05:30
func runUploadTest(t *testing.T, image []byte, filename string, httpCode int, tsHandler func(http.ResponseWriter, *http.Request)) {
2021-02-22 17:27:13 +05:30
var buffer bytes.Buffer
writer := multipart.NewWriter(&buffer)
2021-04-15 22:33:27 +05:30
file, err := writer.CreateFormFile("file", filename)
require.NoError(t, err)
_, err = file.Write(image)
2021-02-22 17:27:13 +05:30
require.NoError(t, err)
err = writer.Close()
require.NoError(t, err)
2021-04-15 22:33:27 +05:30
ts := testhelper.TestServerWithHandler(regexp.MustCompile(`/url/path\z`), tsHandler)
2021-02-22 17:27:13 +05:30
defer ts.Close()
httpRequest, err := http.NewRequest("POST", ts.URL+"/url/path", &buffer)
require.NoError(t, err)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
httpRequest = httpRequest.WithContext(ctx)
httpRequest.ContentLength = int64(buffer.Len())
httpRequest.Header.Set("Content-Type", writer.FormDataContentType())
response := httptest.NewRecorder()
handler := newProxy(ts.URL)
2022-07-23 23:45:48 +05:30
testInterceptMultipartFiles(t, response, httpRequest, handler, &testFormProcessor{})
2021-04-15 22:33:27 +05:30
require.Equal(t, httpCode, response.Code)
2021-02-22 17:27:13 +05:30
}
func newProxy(url string) *proxy.Proxy {
parsedURL := helper.URLMustParse(url)
return proxy.NewProxy(parsedURL, "123", roundtripper.NewTestBackendRoundTripper(parsedURL))
}
func waitUntilDeleted(t *testing.T, path string) {
var err error
2022-04-04 11:22:00 +05:30
require.Eventually(t, func() bool {
2021-02-22 17:27:13 +05:30
_, err = os.Stat(path)
2022-04-04 11:22:00 +05:30
return err != nil
}, 10*time.Second, 10*time.Millisecond)
2021-02-22 17:27:13 +05:30
require.True(t, os.IsNotExist(err), "expected the file to be deleted")
}
2022-07-23 23:45:48 +05:30
func testInterceptMultipartFiles(t *testing.T, w http.ResponseWriter, r *http.Request, h http.Handler, filter MultipartFormProcessor) {
t.Helper()
fa := &eagerAuthorizer{&api.Response{TempPath: t.TempDir()}}
preparer := &DefaultPreparer{}
interceptMultipartFiles(w, r, h, filter, fa, preparer)
}