Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,220 @@
|
||||
package main
|
||||
|
||||
// G4 hardening: sanitizeExtractedTree used to chmod by name after a by-name
|
||||
// walk - a symlink swapped in between Lstat and Chmod could move the mode
|
||||
// change outside the extraction. Every chmod now runs through dirfds beneath
|
||||
// the pinned dest root.
|
||||
//
|
||||
// G5 hardening: handleFilesArchive had no output byte budget (checkDiskLimit
|
||||
// with 0 projected bytes passed even when archiving "." on a near-quota
|
||||
// server would approach ~2x usage). The tar/gzip stream is now wrapped in the
|
||||
// extraction budget (extractBudgetForDir) via limitedWriter; a capped stream
|
||||
// answers with the endpoint's 507 disk_limit_exceeded shape, leaves no temp
|
||||
// behind and never renames a final archive into place.
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSanitizeExtractedTree_SanitizesModesAndSkipsSpecials(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
outside := t.TempDir()
|
||||
|
||||
if err := os.MkdirAll(filepath.Join(dir, "sub"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Chmod(filepath.Join(dir, "sub"), 0o777); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wide := filepath.Join(dir, "sub", "wide.txt")
|
||||
if err := os.WriteFile(wide, []byte("x"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Chmod(wide, 0o777); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tight := filepath.Join(dir, "tight.txt")
|
||||
if err := os.WriteFile(tight, []byte("x"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outsideTarget := filepath.Join(outside, "target.txt")
|
||||
if err := os.WriteFile(outsideTarget, []byte("x"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Chmod(outsideTarget, 0o666); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(outsideTarget, filepath.Join(dir, "link.txt")); err != nil {
|
||||
t.Skipf("symlinks unsupported: %v", err)
|
||||
}
|
||||
mkfifoInRoot(t, filepath.Join(dir, "pipe"))
|
||||
|
||||
err := errSettleWithin(t, "sanitizeExtractedTree over planted FIFO", func() error {
|
||||
return sanitizeExtractedTree(dir)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("sanitizeExtractedTree: %v", err)
|
||||
}
|
||||
|
||||
if st, serr := os.Stat(filepath.Join(dir, "sub")); serr != nil || st.Mode().Perm() != 0o755 {
|
||||
t.Fatalf("dir mode = %v (%v), want 755", st.Mode().Perm(), serr)
|
||||
}
|
||||
if st, serr := os.Stat(wide); serr != nil || st.Mode().Perm() != 0o644 {
|
||||
t.Fatalf("wide file mode = %v (%v), want 644", st.Mode().Perm(), serr)
|
||||
}
|
||||
if st, serr := os.Stat(tight); serr != nil || st.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("tight file mode = %v (%v), want unchanged 600", st.Mode().Perm(), serr)
|
||||
}
|
||||
// The symlink was skipped: the outside target keeps its mode (a
|
||||
// through-symlink chmod would have knocked 666 down to 644).
|
||||
if st, serr := os.Stat(outsideTarget); serr != nil || st.Mode().Perm() != 0o666 {
|
||||
t.Fatalf("outside target mode = %v (%v), want unchanged 666", st.Mode().Perm(), serr)
|
||||
}
|
||||
if _, serr := os.Lstat(filepath.Join(dir, "pipe")); serr != nil {
|
||||
t.Fatalf("FIFO must be left alone: %v", serr)
|
||||
}
|
||||
}
|
||||
|
||||
func newArchiveBudgetTestAgent(t *testing.T) (*Agent, string, string) {
|
||||
t.Helper()
|
||||
tmp := t.TempDir()
|
||||
vol := filepath.Join(tmp, "servers")
|
||||
a := &Agent{volumesDir: vol, dataRoot: tmp, uploadLimit: 1 << 20}
|
||||
serverDir := a.serverDir("alpha")
|
||||
if err := os.MkdirAll(filepath.Join(serverDir, "world"), 0o750); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Incompressible payload so the archive size tracks the file size.
|
||||
rng := rand.New(rand.NewSource(42))
|
||||
payload := make([]byte, 700*1024)
|
||||
if _, err := rng.Read(payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(serverDir, "world", "level.dat"), payload, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return a, serverDir, string(payload)
|
||||
}
|
||||
|
||||
func archiveRequest(t *testing.T, a *Agent, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/servers/alpha/files/archive", bytes.NewReader([]byte(body)))
|
||||
rec := httptest.NewRecorder()
|
||||
a.handleFilesArchive(rec, req, "alpha")
|
||||
return rec
|
||||
}
|
||||
|
||||
// Without a quota the budget is only the global archive-bomb cap: the archive
|
||||
// completes (200) and the tar.gz round-trips to the original bytes.
|
||||
func TestFilesArchive_UnderBudgetRoundTrip(t *testing.T) {
|
||||
a, serverDir, payload := newArchiveBudgetTestAgent(t)
|
||||
rec := archiveRequest(t, a, `{"paths":["."],"destDir":"out"}`)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("archive status %d body %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var resp struct {
|
||||
Path string `json:"path"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
archivePath := filepath.Join(serverDir, resp.Path)
|
||||
f, err := os.Open(archivePath)
|
||||
if err != nil {
|
||||
t.Fatalf("open archive: %v", err)
|
||||
}
|
||||
defer f.Close()
|
||||
gz, err := gzip.NewReader(f)
|
||||
if err != nil {
|
||||
t.Fatalf("gzip header: %v", err)
|
||||
}
|
||||
defer gz.Close()
|
||||
tr := tar.NewReader(gz)
|
||||
found := false
|
||||
for {
|
||||
hdr, err := tr.Next()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("tar read: %v", err)
|
||||
}
|
||||
if filepath.ToSlash(hdr.Name) == "alpha/world/level.dat" {
|
||||
data, err := io.ReadAll(tr)
|
||||
if err != nil {
|
||||
t.Fatalf("tar payload: %v", err)
|
||||
}
|
||||
if !bytes.Equal(data, []byte(payload)) {
|
||||
t.Fatalf("archived payload differs (%d vs %d bytes)", len(data), len(payload))
|
||||
}
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("level.dat missing from archive")
|
||||
}
|
||||
}
|
||||
|
||||
// Budget forcing mid-archive exhaustion: the response is the endpoint's 507
|
||||
// disk_limit_exceeded shape, no temp file is left behind and no final archive
|
||||
// file is renamed into place.
|
||||
func TestFilesArchive_BudgetCapReturns507(t *testing.T) {
|
||||
a, serverDir, _ := newArchiveBudgetTestAgent(t)
|
||||
meta := map[string]any{"resources": map[string]any{"storageMb": float64(1)}}
|
||||
if err := a.saveMeta(serverDir, meta); err != nil {
|
||||
t.Fatalf("saveMeta: %v", err)
|
||||
}
|
||||
// Sanity: 700KB used of 1MB passes the up-front checkDiskLimit(root, 0)
|
||||
// but leaves only ~300KB of budget for the ~700KB archive stream.
|
||||
if diskErr := a.checkDiskLimit(serverDir, 0); diskErr != nil {
|
||||
t.Fatalf("preconditions: unexpected disk limit failure: %v", diskErr)
|
||||
}
|
||||
if got := a.extractBudgetForDir(serverDir); got >= 700*1024 {
|
||||
t.Fatalf("expected a sub-700KB budget, got %d", got)
|
||||
}
|
||||
|
||||
outDir := filepath.Join(serverDir, "out")
|
||||
rec := archiveRequest(t, a, `{"paths":["."],"destDir":"out"}`)
|
||||
if rec.Code != 507 {
|
||||
t.Fatalf("archive status %d body %s, want 507", rec.Code, rec.Body.String())
|
||||
}
|
||||
var resp map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if resp["error"] != "disk_limit_exceeded" {
|
||||
t.Fatalf("error = %v, want disk_limit_exceeded", resp["error"])
|
||||
}
|
||||
for _, key := range []string{"message", "usedBytes", "limitBytes", "usedMb", "limitMb"} {
|
||||
if _, ok := resp[key]; !ok {
|
||||
t.Fatalf("507 payload missing %q: %v", key, resp)
|
||||
}
|
||||
}
|
||||
|
||||
// No temp left behind, no final archive file.
|
||||
ents, err := os.ReadDir(outDir)
|
||||
if err != nil {
|
||||
t.Fatalf("readdir out: %v", err)
|
||||
}
|
||||
if len(ents) != 0 {
|
||||
names := make([]string, 0, len(ents))
|
||||
for _, e := range ents {
|
||||
names = append(names, e.Name())
|
||||
}
|
||||
t.Fatalf("cap must leave the destination empty, found: %v", names)
|
||||
}
|
||||
// The source data is untouched.
|
||||
if _, err := os.Stat(filepath.Join(serverDir, "world", "level.dat")); err != nil {
|
||||
t.Fatalf("source data must survive: %v", err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user