Files
Kelx/download_test.go
2026-11-30 16:32:37 +00:00

222 lines
7.4 KiB
Go

package main
// Tests for the download commit path (Downloader.writeDownloadToFile, the
// write+rename half of downloadToFile — finding 6's daemon side).
//
// downloadToFile cannot be driven end-to-end in a unit test: its SSRF gate
// (safeURL + the guarded dialer) refuses the loopback address any httptest
// server binds to, by design. The corruption mechanism under test lived
// entirely in the commit half, which is exactly what the extracted method
// isolates: with the old deterministic destPath+".tmp" name, two concurrent
// commits to the same destination shared one temp file — writes interleaved
// into one inode and the first rename-by-name moved the other writer's
// still-open fd into destPath, both flows reported success, and the
// destination was left truncated or interleaved. With unique O_EXCL temp
// names, the destination must always be exactly ONE complete payload, and no
// temp file may survive.
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
)
// blockPattern builds a payload whose integrity is trivially checkable: the
// filler byte alternates by 64 KiB block, so an interleaved write of two
// payloads is detectable block-by-block and a truncated one by length.
func blockPattern(size int, fill byte) []byte {
b := make([]byte, size)
for i := range b {
b[i] = fill
if (i+1)%(64*1024) == 0 {
fill += 7
}
}
return b
}
func strayTempFiles(t *testing.T, dir, destBase string) []string {
t.Helper()
entries, err := os.ReadDir(dir)
if err != nil {
t.Fatalf("read dir: %v", err)
}
var strays []string
for _, e := range entries {
if name := e.Name(); strings.HasPrefix(name, "."+destBase+".tmp-") {
strays = append(strays, name)
}
}
return strays
}
func waitForStrayTempCount(t *testing.T, dir, destBase string, want int) {
t.Helper()
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
if len(strayTempFiles(t, dir, destBase)) >= want {
return
}
time.Sleep(2 * time.Millisecond)
}
t.Fatalf("expected %d in-flight temp file(s) next to %s, saw %d", want, destBase, len(strayTempFiles(t, dir, destBase)))
}
func TestWriteDownloadToFileSingleCommit(t *testing.T) {
dir := t.TempDir()
dest := filepath.Join(dir, "server.jar")
payload := blockPattern(1<<20, 0x41)
if err := (Downloader{}).writeDownloadToFile(bytes.NewReader(payload), dest); err != nil {
t.Fatalf("single download: %v", err)
}
got, err := os.ReadFile(dest)
if err != nil {
t.Fatalf("read dest: %v", err)
}
if !bytes.Equal(got, payload) {
t.Fatalf("dest content mismatch: got %d bytes, want %d", len(got), len(payload))
}
if strays := strayTempFiles(t, dir, "server.jar"); len(strays) != 0 {
t.Fatalf("temp files survived a successful commit: %v", strays)
}
}
// TestWriteDownloadToFileConcurrentCommitsNeverInterleave replays the
// double-submitted install: two writers commit to the same destination at the
// same time, chunk-by-chunk, with both temp files provably in flight before
// any byte is written. The final destination must be exactly one complete
// payload — never a mix, never a truncation — and both commits must succeed.
func TestWriteDownloadToFileConcurrentCommitsNeverInterleave(t *testing.T) {
dir := t.TempDir()
dest := filepath.Join(dir, "server.jar")
payloadA := blockPattern(1<<20, 0x41) // block pattern from 0x41
payloadB := blockPattern(1<<20, 0x80) // disjoint pattern
prA, pwA := io.Pipe()
prB, pwB := io.Pipe()
defer pwA.Close()
defer pwB.Close()
doneA := make(chan error, 1)
doneB := make(chan error, 1)
go func() { doneA <- (Downloader{}).writeDownloadToFile(prA, dest) }()
go func() { doneB <- (Downloader{}).writeDownloadToFile(prB, dest) }()
// Both writers have created their (now unique) temp files and are parked
// reading their bodies: the interleaving below is deterministic.
waitForStrayTempCount(t, dir, "server.jar", 2)
chunk := 64 * 1024
for offset := 0; offset < len(payloadA); offset += chunk {
if _, err := pwA.Write(payloadA[offset : offset+chunk]); err != nil {
t.Fatalf("writer A pipe: %v", err)
}
if _, err := pwB.Write(payloadB[offset : offset+chunk]); err != nil {
t.Fatalf("writer B pipe: %v", err)
}
}
if err := pwA.Close(); err != nil && !errors.Is(err, io.ErrClosedPipe) {
t.Fatalf("close A: %v", err)
}
if err := pwB.Close(); err != nil && !errors.Is(err, io.ErrClosedPipe) {
t.Fatalf("close B: %v", err)
}
if err := <-doneA; err != nil {
t.Fatalf("concurrent commit A failed: %v", err)
}
if err := <-doneB; err != nil {
t.Fatalf("concurrent commit B failed: %v", err)
}
got, err := os.ReadFile(dest)
if err != nil {
t.Fatalf("read dest: %v", err)
}
if !bytes.Equal(got, payloadA) && !bytes.Equal(got, payloadB) {
t.Fatalf("dest must be exactly one complete payload, got a mixed/truncated file (%d bytes, first block byte 0x%02x)",
len(got), got[0])
}
if strays := strayTempFiles(t, dir, "server.jar"); len(strays) != 0 {
t.Fatalf("temp files survived concurrent commits: %v", strays)
}
}
func TestWriteDownloadToFileFailedCommitLeavesDestUntouched(t *testing.T) {
dir := t.TempDir()
dest := filepath.Join(dir, "server.jar")
original := []byte("original jar contents")
if err := os.WriteFile(dest, original, 0o644); err != nil {
t.Fatalf("seed dest: %v", err)
}
// A body that fails mid-copy: the temp file must be removed and the
// destination must keep the old contents (the destructive wipe happened
// before the download, so a partial commit here is the corruption).
if err := (Downloader{}).writeDownloadToFile(errReader{err: errors.New("connection reset mid-download")}, dest); err == nil {
t.Fatal("expected the failing body to fail the commit")
}
got, err := os.ReadFile(dest)
if err != nil {
t.Fatalf("read dest: %v", err)
}
if !bytes.Equal(got, original) {
t.Fatalf("failed commit must leave dest untouched, got %q", got)
}
if strays := strayTempFiles(t, dir, "server.jar"); len(strays) != 0 {
t.Fatalf("temp files survived a failed commit: %v", strays)
}
}
type errReader struct{ err error }
func (e errReader) Read(p []byte) (int, error) { return 0, e.err }
func TestWriteDownloadToFileConcurrentDistinctDestinations(t *testing.T) {
// The old deterministic name also collided across DIFFERENT destinations
// that happened to share a basename (two servers' server.jar under one
// parent dir is not the layout, but plugins/uploads share basenames
// within one server). Distinct destinations must never observe each
// other's commit: run many concurrent commits with the maxBytes limiter
// active and require every one to land complete.
dir := t.TempDir()
const n = 24
payload := blockPattern(16*1024, 0x21)
var wg sync.WaitGroup
errs := make([]error, n)
for i := 0; i < n; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
dest := filepath.Join(dir, fmt.Sprintf("artifact-%02d.jar", i))
errs[i] = (Downloader{maxBytes: 1 << 20}).writeDownloadToFile(bytes.NewReader(payload), dest)
}(i)
}
wg.Wait()
for i, err := range errs {
if err != nil {
t.Fatalf("commit %d failed: %v", i, err)
}
}
for i := 0; i < n; i++ {
got, err := os.ReadFile(filepath.Join(dir, fmt.Sprintf("artifact-%02d.jar", i)))
if err != nil {
t.Fatalf("read artifact %d: %v", i, err)
}
if !bytes.Equal(got, payload) {
t.Fatalf("artifact %d content mismatch", i)
}
}
if strays := strayTempFiles(t, dir, "artifact-"); len(strays) != 0 {
t.Fatalf("temp files survived: %v", strays)
}
}