228 lines
7.7 KiB
Go
228 lines
7.7 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"io"
|
|
"mime/multipart"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"reflect"
|
|
"sort"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
// Upload-filename parity fix: the streaming multipart route used to run names
|
|
// through sanitizeName, which strips leading dots and non-ASCII, so .env
|
|
// arrived as env and café.txt as caf.txt while the base64 routes preserved
|
|
// both. sanitizeUploadFilename is now the single gate for every upload route:
|
|
// dotfiles and valid UTF-8 names survive, separators/NUL/control characters
|
|
// cannot, and unusable names yield "" so handlers answer 400 instead of
|
|
// silently renaming the upload to a fallback name.
|
|
func TestSanitizeUploadFilename(t *testing.T) {
|
|
cases := []struct {
|
|
name string
|
|
in string
|
|
want string
|
|
}{
|
|
{"dotfile preserved", ".env", ".env"},
|
|
{"path component basenamed keeps dotfile", "config/.env", ".env"},
|
|
{"dotdot-prefixed name kept", "..env", "..env"},
|
|
{"non-ascii preserved", "café.txt", "café.txt"},
|
|
{"cjk preserved", "服务器.cfg", "服务器.cfg"},
|
|
{"plain name unchanged", "v1.2-rc_3.tar.gz", "v1.2-rc_3.tar.gz"},
|
|
{"interior spaces kept", "my server.txt", "my server.txt"},
|
|
{"edge whitespace trimmed", " .env\t", ".env"},
|
|
{"path separator basenamed", "a/b.txt", "b.txt"},
|
|
{"backslash replaced", "back\\slash.txt", "back_slash.txt"},
|
|
{"nul replaced", "nul\x00name", "nul_name"},
|
|
{"crlf replaced", "a\rb\nc.txt", "a_b_c.txt"},
|
|
{"control chars replaced", "a\x1b[31mb.txt", "a_[31mb.txt"},
|
|
{"invalid utf8 deterministic", "caf\xe9.txt", "caf_.txt"},
|
|
{"dot rejected", ".", ""},
|
|
{"dotdot rejected", "..", ""},
|
|
{"parent traversal rejected", "a/..", ""},
|
|
{"self traversal rejected", "a/.", ""},
|
|
{"root rejected", "/", ""},
|
|
{"empty rejected", "", ""},
|
|
{"whitespace only rejected", " ", ""},
|
|
{"control only becomes underscore", "\x01\x7f", "__"},
|
|
{"long ascii capped at 200 bytes", strings.Repeat("a", 300), strings.Repeat("a", 200)},
|
|
{"long utf8 capped on rune boundary", strings.Repeat("é", 150) + ".txt", strings.Repeat("é", 100)},
|
|
}
|
|
for _, tc := range cases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
got := sanitizeUploadFilename(tc.in)
|
|
if got != tc.want {
|
|
t.Fatalf("sanitizeUploadFilename(%q) = %q, want %q", tc.in, got, tc.want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func newUploadFilenameTestAgent(t *testing.T) (*Agent, string) {
|
|
t.Helper()
|
|
tmp := t.TempDir()
|
|
vol := filepath.Join(tmp, "servers")
|
|
if err := os.MkdirAll(vol, 0o750); err != nil {
|
|
t.Fatalf("mkdir volumes: %v", err)
|
|
}
|
|
return &Agent{volumesDir: vol, uploadLimit: 1 << 20}, vol
|
|
}
|
|
|
|
const fixtureUploadDaemonToken = "fixture-upload-daemon-token"
|
|
|
|
func streamUploadFilenameRequest(t *testing.T, a *Agent, server, dir, filename, content string) *httptest.ResponseRecorder {
|
|
t.Helper()
|
|
return streamUploadFilenameRequestWithMethod(t, http.HandlerFunc(a.handleFSUploadStream), http.MethodPost, server, dir, filename, content)
|
|
}
|
|
|
|
func streamUploadFilenameRequestWithMethod(t *testing.T, handler http.Handler, method, server, dir, filename, content string) *httptest.ResponseRecorder {
|
|
t.Helper()
|
|
var buf bytes.Buffer
|
|
mw := multipart.NewWriter(&buf)
|
|
if err := mw.WriteField("server", server); err != nil {
|
|
t.Fatalf("write server field: %v", err)
|
|
}
|
|
if err := mw.WriteField("dir", dir); err != nil {
|
|
t.Fatalf("write dir field: %v", err)
|
|
}
|
|
fw, err := mw.CreateFormFile("file", filename)
|
|
if err != nil {
|
|
t.Fatalf("create form file: %v", err)
|
|
}
|
|
if _, err := io.WriteString(fw, content); err != nil {
|
|
t.Fatalf("write file content: %v", err)
|
|
}
|
|
if err := mw.Close(); err != nil {
|
|
t.Fatalf("close multipart writer: %v", err)
|
|
}
|
|
req := httptest.NewRequest(method, "/v1/fs/upload", &buf)
|
|
req.Header.Set("Content-Type", mw.FormDataContentType())
|
|
req.Header.Set("X-Node-Token", fixtureUploadDaemonToken)
|
|
rec := httptest.NewRecorder()
|
|
handler.ServeHTTP(rec, req)
|
|
return rec
|
|
}
|
|
|
|
func rawUploadFilenameRequest(t *testing.T, a *Agent, server, dir, filename, content string) *httptest.ResponseRecorder {
|
|
t.Helper()
|
|
payload, err := json.Marshal(map[string]string{
|
|
"dir": dir,
|
|
"server": server,
|
|
"filename": filename,
|
|
"data_b64": base64.StdEncoding.EncodeToString([]byte(content)),
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("marshal upload payload: %v", err)
|
|
}
|
|
req := httptest.NewRequest(http.MethodPost, "/v1/fs/uploadRaw", bytes.NewReader(payload))
|
|
rec := httptest.NewRecorder()
|
|
a.handleFSUploadRaw(rec, req)
|
|
return rec
|
|
}
|
|
|
|
func uploadFilenameListing(t *testing.T, root string) []string {
|
|
t.Helper()
|
|
var names []string
|
|
err := filepath.Walk(root, func(p string, info os.FileInfo, err error) error {
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if p == root {
|
|
return nil
|
|
}
|
|
rel, relErr := filepath.Rel(root, p)
|
|
if relErr != nil {
|
|
return relErr
|
|
}
|
|
names = append(names, rel)
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("walk %s: %v", root, err)
|
|
}
|
|
sort.Strings(names)
|
|
return names
|
|
}
|
|
|
|
// The regression pair: the SAME filenames through BOTH upload routes must be
|
|
// stored under the SAME names, dotfiles and non-ASCII included.
|
|
func TestUploadRoutesStoreTheSameFilename(t *testing.T) {
|
|
a, vol := newUploadFilenameTestAgent(t)
|
|
streamRoot := filepath.Join(vol, "alpha")
|
|
rawRoot := filepath.Join(vol, "beta")
|
|
for _, dir := range []string{streamRoot, rawRoot} {
|
|
if err := os.MkdirAll(dir, 0o750); err != nil {
|
|
t.Fatalf("mkdir server dir: %v", err)
|
|
}
|
|
}
|
|
|
|
names := []string{".env", "café.txt", "mod-config.cfg", "a/b.txt", `notes "draft".txt`, "notes %22draft%22.txt", "notes _draft_.txt"}
|
|
for _, name := range names {
|
|
rec := streamUploadFilenameRequest(t, a, "alpha", streamRoot, name, "stream-content")
|
|
if rec.Code != 200 {
|
|
t.Fatalf("stream upload %q: status %d body %s", name, rec.Code, rec.Body.String())
|
|
}
|
|
rec = rawUploadFilenameRequest(t, a, "beta", rawRoot, name, "raw-content")
|
|
if rec.Code != 200 {
|
|
t.Fatalf("raw upload %q: status %d body %s", name, rec.Code, rec.Body.String())
|
|
}
|
|
}
|
|
|
|
gotStream := uploadFilenameListing(t, streamRoot)
|
|
gotRaw := uploadFilenameListing(t, rawRoot)
|
|
if !reflect.DeepEqual(gotStream, gotRaw) {
|
|
t.Fatalf("routes disagree on stored names:\nstream: %q\nraw: %q", gotStream, gotRaw)
|
|
}
|
|
want := []string{".env", "b.txt", "café.txt", "mod-config.cfg", `notes "draft".txt`, "notes %22draft%22.txt", "notes _draft_.txt"}
|
|
if !reflect.DeepEqual(gotStream, want) {
|
|
t.Fatalf("stored names = %q, want %q", gotStream, want)
|
|
}
|
|
|
|
// The dotfile really landed as .env with its content intact.
|
|
data, err := os.ReadFile(filepath.Join(streamRoot, ".env"))
|
|
if err != nil {
|
|
t.Fatalf("read uploaded dotfile: %v", err)
|
|
}
|
|
if string(data) != "stream-content" {
|
|
t.Fatalf("dotfile content = %q, want %q", data, "stream-content")
|
|
}
|
|
data, err = os.ReadFile(filepath.Join(rawRoot, ".env"))
|
|
if err != nil {
|
|
t.Fatalf("read uploaded dotfile: %v", err)
|
|
}
|
|
if string(data) != "raw-content" {
|
|
t.Fatalf("dotfile content = %q, want %q", data, "raw-content")
|
|
}
|
|
}
|
|
|
|
// Unusable names are refused by both routes with the base64 routes' existing
|
|
// 400 "invalid filename" shape instead of being silently renamed.
|
|
func TestUploadRoutesRejectUnusableFilenames(t *testing.T) {
|
|
a, vol := newUploadFilenameTestAgent(t)
|
|
serverRoot := filepath.Join(vol, "alpha")
|
|
if err := os.MkdirAll(serverRoot, 0o750); err != nil {
|
|
t.Fatalf("mkdir server dir: %v", err)
|
|
}
|
|
|
|
for _, name := range []string{".", ".."} {
|
|
rec := streamUploadFilenameRequest(t, a, "alpha", serverRoot, name, "x")
|
|
if rec.Code != 400 {
|
|
t.Fatalf("stream upload %q: status %d, want 400", name, rec.Code)
|
|
}
|
|
rec = rawUploadFilenameRequest(t, a, "alpha", serverRoot, name, "x")
|
|
if rec.Code != 400 {
|
|
t.Fatalf("raw upload %q: status %d, want 400", name, rec.Code)
|
|
}
|
|
}
|
|
// Nothing was written for the rejected names.
|
|
if got := uploadFilenameListing(t, serverRoot); len(got) != 0 {
|
|
t.Fatalf("rejected uploads left files behind: %q", got)
|
|
}
|
|
}
|