Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+626
View File
@@ -0,0 +1,626 @@
package main
import (
"bytes"
"crypto/sha256"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
)
// The staging invariant for every failure mode of the stream upload route:
// the pre-existing destination survives byte-identical and no temp file is
// left behind in the destination directory. Before the temp+rename staging
// an interrupted overwrite destroyed the file it was replacing.
func uploadAtomicityServerDir(t *testing.T, a *Agent) string {
t.Helper()
dir := filepath.Join(a.volumesDir, "alpha")
if err := os.MkdirAll(dir, 0o750); err != nil {
t.Fatalf("mkdir server dir: %v", err)
}
return dir
}
// An upload whose transfer fails mid-part (here: the body crosses the
// MaxBytesReader limit) must leave the replaced file untouched.
func TestStreamUploadFailedOverwritePreservesExistingFile(t *testing.T) {
a, _ := newUploadFilenameTestAgent(t)
dir := uploadAtomicityServerDir(t, a)
dest := filepath.Join(dir, "keep.txt")
if err := os.WriteFile(dest, []byte("old-content"), 0o644); err != nil {
t.Fatalf("seed destination: %v", err)
}
rec := streamUploadFilenameRequest(t, a, "alpha", dir, "keep.txt", strings.Repeat("A", 2<<20))
// The MaxBytesReader abort (it counts multipart framing too, so it fires
// for parts just over the limit) must surface the same 413 shape as the
// payload-limit branch, not a generic 500.
if rec.Code != 413 {
t.Fatalf("oversized upload: status %d body %s, want 413", rec.Code, rec.Body.String())
}
data, err := os.ReadFile(dest)
if err != nil {
t.Fatalf("read destination: %v", err)
}
if string(data) != "old-content" {
t.Fatalf("failed overwrite destroyed the previous file: content = %q", data)
}
if got := uploadFilenameListing(t, dir); len(got) != 1 || got[0] != "keep.txt" {
t.Fatalf("destination directory = %q, want [keep.txt] (temp leftover?)", got)
}
}
// A hard read error mid-file (the client disconnects mid-upload) must fail
// the request without touching the pre-existing destination.
func TestStreamUploadMidBodyErrorPreservesExistingFile(t *testing.T) {
a, _ := newUploadFilenameTestAgent(t)
dir := uploadAtomicityServerDir(t, a)
dest := filepath.Join(dir, "keep.txt")
if err := os.WriteFile(dest, []byte("old-content"), 0o644); err != nil {
t.Fatalf("seed destination: %v", err)
}
const boundary = "adpanelatomicityboundary"
preamble := "--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=\"server\"\r\n\r\nalpha\r\n" +
"--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=\"dir\"\r\n\r\n" + dir + "\r\n" +
"--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=\"file\"; filename=\"keep.txt\"\r\n" +
"Content-Type: application/octet-stream\r\n\r\n"
pr, pw := io.Pipe()
go func() {
if _, err := pw.Write([]byte(preamble + "partial")); err != nil {
pw.CloseWithError(err)
return
}
pw.CloseWithError(errors.New("client disconnected mid-upload"))
}()
req := httptest.NewRequest(http.MethodPost, "/v1/fs/upload", pr)
req.Header.Set("Content-Type", "multipart/form-data; boundary="+boundary)
rec := httptest.NewRecorder()
a.handleFSUploadStream(rec, req)
if rec.Code != 500 {
t.Fatalf("mid-body read error: status %d body %s, want 500", rec.Code, rec.Body.String())
}
data, err := os.ReadFile(dest)
if err != nil {
t.Fatalf("read destination: %v", err)
}
if string(data) != "old-content" {
t.Fatalf("failed overwrite destroyed the previous file: content = %q", data)
}
if got := uploadFilenameListing(t, dir); len(got) != 1 || got[0] != "keep.txt" {
t.Fatalf("destination directory = %q, want [keep.txt] (temp leftover?)", got)
}
}
func TestStreamUploadSuccessfulOverwriteReplacesContent(t *testing.T) {
a, _ := newUploadFilenameTestAgent(t)
dir := uploadAtomicityServerDir(t, a)
dest := filepath.Join(dir, "keep.txt")
if err := os.WriteFile(dest, []byte("old-content"), 0o644); err != nil {
t.Fatalf("seed destination: %v", err)
}
rec := streamUploadFilenameRequest(t, a, "alpha", dir, "keep.txt", "new-content")
if rec.Code != 200 {
t.Fatalf("overwrite upload: status %d body %s, want 200", rec.Code, rec.Body.String())
}
data, err := os.ReadFile(dest)
if err != nil {
t.Fatalf("read destination: %v", err)
}
if string(data) != "new-content" {
t.Fatalf("overwrite content = %q, want %q", data, "new-content")
}
if got := uploadFilenameListing(t, dir); len(got) != 1 || got[0] != "keep.txt" {
t.Fatalf("destination directory = %q, want [keep.txt] (temp leftover?)", got)
}
}
func TestStreamUploadQuotaCountsFileBytesAndReplacement(t *testing.T) {
agent, _ := newUploadFilenameTestAgent(t)
agent.uploadLimit = 2 << 20
dir := uploadAtomicityServerDir(t, agent)
dest := filepath.Join(dir, "keep.txt")
if err := os.WriteFile(dest, []byte("old"), 0o644); err != nil {
t.Fatal(err)
}
if err := agent.saveMeta(dir, map[string]any{"resources": map[string]any{"storageMb": 1}}); err != nil {
t.Fatal(err)
}
remaining := (1 << 20) - agent.getServerTotalUsage(dir)
if remaining <= 0 {
t.Fatalf("fixture must leave room for a replacement: %d", remaining)
}
content := strings.Repeat("X", int(remaining)+len("old"))
accepted := streamUploadFilenameRequest(t, agent, "alpha", dir, "keep.txt", content)
if accepted.Code != http.StatusOK {
t.Fatalf("exact-fit replacement: %d %s", accepted.Code, accepted.Body)
}
refused := streamUploadFilenameRequest(t, agent, "alpha", dir, "keep.txt", content+"X")
if refused.Code != http.StatusInsufficientStorage || !strings.Contains(refused.Body.String(), `"disk_limit_exceeded"`) {
t.Fatalf("over-quota replacement: %d %s", refused.Code, refused.Body)
}
if data, err := os.ReadFile(dest); err != nil || string(data) != content {
t.Fatalf("failed upload changed the existing file: len=%d err=%v", len(data), err)
}
}
func TestStreamUploadCreateOnlyPreservesExistingFile(t *testing.T) {
if runtime.GOOS != "linux" {
t.Skip("strict atomic no-replace is Linux-only")
}
agent, _ := newUploadFilenameTestAgent(t)
agent.token = fixtureUploadDaemonToken
dir := uploadAtomicityServerDir(t, agent)
first := streamUploadFilenameRequestWithMethod(t, agent, http.MethodPut, "alpha", dir, "keep.txt", "original")
if first.Code != http.StatusOK {
t.Fatalf("create-only upload: %d %s", first.Code, first.Body)
}
second := streamUploadFilenameRequestWithMethod(t, agent, http.MethodPut, "alpha", dir, "keep.txt", "replacement")
if second.Code != http.StatusConflict || !strings.Contains(second.Body.String(), `"destination_exists"`) {
t.Fatalf("create-only collision: %d %s", second.Code, second.Body)
}
data, err := os.ReadFile(filepath.Join(dir, "keep.txt"))
if err != nil || string(data) != "original" {
t.Fatalf("existing file changed: %q, %v", data, err)
}
if got := uploadFilenameListing(t, dir); len(got) != 1 || got[0] != "keep.txt" {
t.Fatalf("unexpected files after conflict: %q", got)
}
}
func TestStagedUploadCreateOnlyPreservesLateDestination(t *testing.T) {
if runtime.GOOS != "linux" {
t.Skip("strict atomic no-replace is Linux-only")
}
dir := t.TempDir()
root, err := safeOpenRoot(dir)
if err != nil {
t.Fatal(err)
}
defer root.Close()
const stage = "staged.txt"
const destination = "keep.txt"
if err := os.WriteFile(filepath.Join(dir, stage), []byte("staged content"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, destination), []byte("created in-flight"), 0o644); err != nil {
t.Fatal(err)
}
if err := commitStagedUpload(root, stage, destination, true); !errors.Is(err, errSafeDestExists) {
t.Fatalf("late destination was not refused: %v", err)
}
data, err := os.ReadFile(filepath.Join(dir, destination))
if err != nil || string(data) != "created in-flight" {
t.Fatalf("late destination changed: %q, %v", data, err)
}
}
// uploadIdleBody: the deadline is armed once at wrap and re-armed on the
// first successful read; an immediate second read sits inside the re-arm
// throttle and must not churn another SetReadDeadline.
type idleDeadlineRecorder struct {
*httptest.ResponseRecorder
deadlines []time.Time
}
func (d *idleDeadlineRecorder) SetReadDeadline(t time.Time) error {
d.deadlines = append(d.deadlines, t)
return nil
}
func TestUploadIdleBodyArmsAndReArmsDeadline(t *testing.T) {
oldWindow := uploadBodyIdleTimeout
uploadBodyIdleTimeout = time.Hour
defer func() { uploadBodyIdleTimeout = oldWindow }()
rec := &idleDeadlineRecorder{}
b := newUploadIdleBody(rec, io.NopCloser(strings.NewReader("hello world")))
if len(rec.deadlines) != 1 {
t.Fatalf("wrap armed %d deadlines, want 1", len(rec.deadlines))
}
buf := make([]byte, 4)
if _, err := b.Read(buf); err != nil {
t.Fatalf("first read: %v", err)
}
if len(rec.deadlines) != 2 {
t.Fatalf("first successful read armed %d deadlines total, want 2", len(rec.deadlines))
}
if !rec.deadlines[1].After(rec.deadlines[0]) {
t.Fatalf("re-armed deadline %v is not after the initial one %v", rec.deadlines[1], rec.deadlines[0])
}
if _, err := b.Read(buf); err != nil {
t.Fatalf("second read: %v", err)
}
if len(rec.deadlines) != 2 {
t.Fatalf("throttled second read armed %d deadlines total, want 2", len(rec.deadlines))
}
}
// A client that stalls mid-body must be aborted by the idle read deadline
// (not by an absolute cap) and the pre-existing destination must survive.
// Driven over a real connection because httptest.ResponseRecorder has no
// deadline support.
func TestUploadStalledClientAbortedAndDestinationPreserved(t *testing.T) {
oldWindow := uploadBodyIdleTimeout
uploadBodyIdleTimeout = 250 * time.Millisecond
defer func() { uploadBodyIdleTimeout = oldWindow }()
a, _ := newUploadFilenameTestAgent(t)
dir := uploadAtomicityServerDir(t, a)
dest := filepath.Join(dir, "keep.txt")
if err := os.WriteFile(dest, []byte("old-content"), 0o644); err != nil {
t.Fatalf("seed destination: %v", err)
}
srv := httptest.NewServer(http.HandlerFunc(a.handleFSUploadStream))
defer srv.Close()
const boundary = "adpanelatomicityboundary"
pr, pw := io.Pipe()
resCh := make(chan int, 1)
go func() {
req, err := http.NewRequest(http.MethodPost, srv.URL, pr)
if err != nil {
resCh <- -1
return
}
req.Header.Set("Content-Type", "multipart/form-data; boundary="+boundary)
resp, err := http.DefaultClient.Do(req)
if err != nil {
resCh <- -1
return
}
defer resp.Body.Close()
io.Copy(io.Discard, resp.Body)
resCh <- resp.StatusCode
}()
write := func(s string) {
if _, err := pw.Write([]byte(s)); err != nil {
t.Fatalf("write request body: %v", err)
}
}
write("--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=\"server\"\r\n\r\nalpha\r\n" +
"--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=\"dir\"\r\n\r\n" + dir + "\r\n" +
"--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=\"file\"; filename=\"keep.txt\"\r\n" +
"Content-Type: application/octet-stream\r\n\r\n")
write("partial")
// Stalled: nothing more is written and the pipe stays open. The idle
// window must fire and abort the handler with a 500.
if code := <-resCh; code != 500 {
t.Fatalf("stalled upload: status %d, want 500", code)
}
_ = pw.CloseWithError(errors.New("test finished"))
data, err := os.ReadFile(dest)
if err != nil {
t.Fatalf("read destination: %v", err)
}
if string(data) != "old-content" {
t.Fatalf("aborted stall destroyed the previous file: content = %q", data)
}
if got := uploadFilenameListing(t, dir); len(got) != 1 || got[0] != "keep.txt" {
t.Fatalf("destination directory = %q, want [keep.txt] (temp leftover?)", got)
}
}
// The inverse guarantee: a slow transfer whose gaps stay inside the idle
// window completes no matter how long the total takes — the window slides
// with progress instead of being armed once. The total here (~720ms, 8 gaps
// of 90ms) exceeds the window (400ms) by 1.8x, so a non-sliding deadline
// would abort it, while every gap keeps 310ms of slack inside the window so
// a CI runner briefly descheduling the test process cannot spuriously fire
// the deadline.
func TestUploadSlowTrickleCompletes(t *testing.T) {
oldWindow := uploadBodyIdleTimeout
uploadBodyIdleTimeout = 400 * time.Millisecond
defer func() { uploadBodyIdleTimeout = oldWindow }()
a, _ := newUploadFilenameTestAgent(t)
dir := uploadAtomicityServerDir(t, a)
dest := filepath.Join(dir, "trickled.bin")
srv := httptest.NewServer(http.HandlerFunc(a.handleFSUploadStream))
defer srv.Close()
const boundary = "adpanelatomicityboundary"
chunk := bytes.Repeat([]byte("A"), 32<<10)
pr, pw := io.Pipe()
resCh := make(chan int, 1)
go func() {
req, err := http.NewRequest(http.MethodPost, srv.URL, pr)
if err != nil {
resCh <- -1
return
}
req.Header.Set("Content-Type", "multipart/form-data; boundary="+boundary)
resp, err := http.DefaultClient.Do(req)
if err != nil {
resCh <- -1
return
}
defer resp.Body.Close()
io.Copy(io.Discard, resp.Body)
resCh <- resp.StatusCode
}()
write := func(s string) {
if _, err := pw.Write([]byte(s)); err != nil {
t.Fatalf("write request body: %v", err)
}
}
write("--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=\"server\"\r\n\r\nalpha\r\n" +
"--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=\"dir\"\r\n\r\n" + dir + "\r\n" +
"--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=\"file\"; filename=\"trickled.bin\"\r\n" +
"Content-Type: application/octet-stream\r\n\r\n")
for i := 0; i < 8; i++ {
if _, err := pw.Write(chunk); err != nil {
t.Fatalf("write chunk: %v", err)
}
time.Sleep(90 * time.Millisecond)
}
write("\r\n--" + boundary + "--\r\n")
_ = pw.Close()
if code := <-resCh; code != 200 {
t.Fatalf("trickled upload: status %d, want 200", code)
}
data, err := os.ReadFile(dest)
if err != nil {
t.Fatalf("read destination: %v", err)
}
if !bytes.Equal(data, bytes.Repeat(chunk, 8)) {
t.Fatalf("trickled upload content mismatch: %d bytes", len(data))
}
if got := uploadFilenameListing(t, dir); len(got) != 1 || got[0] != "trickled.bin" {
t.Fatalf("destination directory = %q, want [trickled.bin] (temp leftover?)", got)
}
}
// The staged commit swaps in the temp's inode, so an overwrite must carry the
// replaced file's mode on the temp first: the old in-place O_TRUNC write kept
// the inode and thus its mode, and without the inheritance an executable
// overwritten through the panel silently lost +x.
func TestStreamUploadOverwritePreservesMode(t *testing.T) {
a, _ := newUploadFilenameTestAgent(t)
dir := uploadAtomicityServerDir(t, a)
dest := filepath.Join(dir, "start.sh")
if err := os.WriteFile(dest, []byte("#!/bin/sh\n"), 0o644); err != nil {
t.Fatalf("seed destination: %v", err)
}
// Explicit chmod so the umask cannot skew the assertion.
if err := os.Chmod(dest, 0o755); err != nil {
t.Fatalf("chmod destination: %v", err)
}
rec := streamUploadFilenameRequest(t, a, "alpha", dir, "start.sh", "#!/bin/sh\necho updated\n")
if rec.Code != 200 {
t.Fatalf("overwrite upload: status %d body %s, want 200", rec.Code, rec.Body.String())
}
info, err := os.Stat(dest)
if err != nil {
t.Fatalf("stat destination: %v", err)
}
if info.Mode().Perm() != 0o755 {
t.Fatalf("overwrite dropped the exec bit: mode = %v, want 0755", info.Mode().Perm())
}
if got := uploadFilenameListing(t, dir); len(got) != 1 || got[0] != "start.sh" {
t.Fatalf("destination directory = %q, want [start.sh] (temp leftover?)", got)
}
}
// A brand-new upload has no replaced file to inherit a mode from and keeps
// the temp's default 0644&~umask; only the umask-independent invariant is
// asserted (regular file with owner read/write set).
func TestStreamUploadNewFileLandsWithUsablePerms(t *testing.T) {
a, _ := newUploadFilenameTestAgent(t)
dir := uploadAtomicityServerDir(t, a)
dest := filepath.Join(dir, "fresh.txt")
rec := streamUploadFilenameRequest(t, a, "alpha", dir, "fresh.txt", "fresh-content")
if rec.Code != 200 {
t.Fatalf("fresh upload: status %d body %s, want 200", rec.Code, rec.Body.String())
}
info, err := os.Stat(dest)
if err != nil {
t.Fatalf("stat destination: %v", err)
}
if !info.Mode().IsRegular() {
t.Fatalf("fresh upload is not a regular file: mode = %v", info.Mode())
}
if info.Mode().Perm()&0o600 != 0o600 {
t.Fatalf("fresh upload lacks owner read/write: mode = %v", info.Mode().Perm())
}
if got := uploadFilenameListing(t, dir); len(got) != 1 || got[0] != "fresh.txt" {
t.Fatalf("destination directory = %q, want [fresh.txt] (temp leftover?)", got)
}
}
// The editor save route stages update/legacy saves like the upload routes: a
// successful save replaces the content and leaves no temp behind, and the
// mode contracts keep their status codes (update on missing -> 404, create
// on existing -> 409).
func TestFSWriteEditorSaveStagesOverwrite(t *testing.T) {
a, _ := newUploadFilenameTestAgent(t)
dir := uploadAtomicityServerDir(t, a)
dest := filepath.Join(dir, "editor.cfg")
if err := os.WriteFile(dest, []byte("old-editor-content"), 0o644); err != nil {
t.Fatalf("seed destination: %v", err)
}
rr := fsPost(t, a.handleFSWrite, "/v1/fs/write", map[string]any{
"path": dest, "server": "alpha", "content": "new-editor-content", "mode": "update",
})
if rr.Code != 200 {
t.Fatalf("editor save: status %d body %s, want 200", rr.Code, rr.Body.String())
}
data, err := os.ReadFile(dest)
if err != nil {
t.Fatalf("read destination: %v", err)
}
if string(data) != "new-editor-content" {
t.Fatalf("editor save content = %q, want %q", data, "new-editor-content")
}
if got := uploadFilenameListing(t, dir); len(got) != 1 || got[0] != "editor.cfg" {
t.Fatalf("destination directory = %q, want [editor.cfg] (temp leftover?)", got)
}
rr = fsPost(t, a.handleFSWrite, "/v1/fs/write", map[string]any{
"path": filepath.Join(dir, "missing.txt"), "server": "alpha", "content": "x", "mode": "update",
})
if rr.Code != 404 {
t.Fatalf("update on missing file: status %d, want 404", rr.Code)
}
rr = fsPost(t, a.handleFSWrite, "/v1/fs/write", map[string]any{
"path": dest, "server": "alpha", "content": "x", "mode": "create",
})
if rr.Code != 409 {
t.Fatalf("create on existing file: status %d, want 409", rr.Code)
}
legacy := filepath.Join(dir, "legacy.txt")
rr = fsPost(t, a.handleFSWrite, "/v1/fs/write", map[string]any{
"path": legacy, "server": "alpha", "content": "v1",
})
if rr.Code != 200 {
t.Fatalf("legacy create save: status %d body %s, want 200", rr.Code, rr.Body.String())
}
rr = fsPost(t, a.handleFSWrite, "/v1/fs/write", map[string]any{
"path": legacy, "server": "alpha", "content": "v2",
})
if rr.Code != 200 {
t.Fatalf("legacy overwrite save: status %d body %s, want 200", rr.Code, rr.Body.String())
}
data, err = os.ReadFile(legacy)
if err != nil {
t.Fatalf("read legacy destination: %v", err)
}
if string(data) != "v2" {
t.Fatalf("legacy overwrite content = %q, want %q", data, "v2")
}
if got := uploadFilenameListing(t, dir); len(got) != 2 || got[0] != "editor.cfg" || got[1] != "legacy.txt" {
t.Fatalf("destination directory = %q, want [editor.cfg legacy.txt] (temp leftover?)", got)
}
}
func TestFSReviewedTextMutationRequiresCurrentBytes(t *testing.T) {
a, _ := newUploadFilenameTestAgent(t)
file := filepath.Join(uploadAtomicityServerDir(t, a), "review.txt")
const content = "old"
const digest = "cba06b5736faf67e54b07b561eae94395e774c517a7d910a54369e1263ccfbd4"
if err := os.WriteFile(file, []byte("changed"), 0o600); err != nil {
t.Fatal(err)
}
write := map[string]any{"path": file, "server": "alpha", "mode": "update", "content": "new", "expectedSha256": digest}
remove := map[string]any{"path": file, "server": "alpha", "expectedSha256": digest}
for _, rr := range []*httptest.ResponseRecorder{
fsPost(t, a.handleFSWrite, "/v1/fs/write", write),
fsPost(t, a.handleFSDelete, "/v1/fs/delete", remove),
} {
if rr.Code != 409 || decodeJSONBody(t, rr)["code"] != "file_changed_on_disk" {
t.Fatalf("expected rejected stale review, got %d: %s", rr.Code, rr.Body.String())
}
}
if data, err := os.ReadFile(file); err != nil || string(data) != "changed" {
t.Fatalf("stale review changed the file: %q, %v", data, err)
}
for _, action := range []string{"write", "delete"} {
if err := os.WriteFile(file, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
handler, body := a.handleFSWrite, write
if action == "delete" {
handler, body = a.handleFSDelete, remove
}
if rr := fsPost(t, handler, "/v1/fs/"+action, body); rr.Code != 200 {
t.Fatalf("matching reviewed %s refused: %d %s", action, rr.Code, rr.Body.String())
}
}
if _, err := os.Stat(file); !os.IsNotExist(err) {
t.Fatalf("reviewed file was not deleted: %v", err)
}
}
func TestFSWriteEditorGuardPreservesNewerBytes(t *testing.T) {
agent, _ := newUploadFilenameTestAgent(t)
file := filepath.Join(uploadAtomicityServerDir(t, agent), "editor.cfg")
original := []byte(strings.Repeat("editor-content\n", 2000))
if err := os.WriteFile(file, original, 0o600); err != nil {
t.Fatal(err)
}
baseHash := fmt.Sprintf("%x", sha256.Sum256(original))
for _, attempt := range []struct {
value string
status int
}{
{"first edit", http.StatusOK},
{"stale edit", http.StatusConflict},
} {
body := map[string]any{"path": file, "server": "alpha", "content": attempt.value, "editorBaseSha256": baseHash}
rec := fsPost(t, agent.handleFSWrite, "/v1/fs/write", body)
if rec.Code != attempt.status || (rec.Code == http.StatusConflict && decodeJSONBody(t, rec)["code"] != "file_changed_on_disk") {
t.Fatalf("write %q: got %d %s, want %d", attempt.value, rec.Code, rec.Body, attempt.status)
}
}
if kept, err := os.ReadFile(file); err != nil || string(kept) != "first edit" {
t.Fatalf("newer content changed: %q (%v)", kept, err)
}
}
// The editor save route must preserve the replaced file's mode the same way
// the upload routes do (the staged commit swaps in the temp's inode, the old
// in-place O_TRUNC write kept it) — an executable script saved from the
// panel editor silently losing +x was the user-visible regression.
func TestFSWriteEditorSavePreservesMode(t *testing.T) {
a, _ := newUploadFilenameTestAgent(t)
dir := uploadAtomicityServerDir(t, a)
dest := filepath.Join(dir, "start.sh")
if err := os.WriteFile(dest, []byte("old-editor-content"), 0o644); err != nil {
t.Fatalf("seed destination: %v", err)
}
// Explicit chmod so the umask cannot skew the assertion.
if err := os.Chmod(dest, 0o755); err != nil {
t.Fatalf("chmod destination: %v", err)
}
rr := fsPost(t, a.handleFSWrite, "/v1/fs/write", map[string]any{
"path": dest, "server": "alpha", "content": "new-editor-content", "mode": "update",
})
if rr.Code != 200 {
t.Fatalf("editor save: status %d body %s, want 200", rr.Code, rr.Body.String())
}
info, err := os.Stat(dest)
if err != nil {
t.Fatalf("stat destination: %v", err)
}
if info.Mode().Perm() != 0o755 {
t.Fatalf("editor save dropped the exec bit: mode = %v, want 0755", info.Mode().Perm())
}
if got := uploadFilenameListing(t, dir); len(got) != 1 || got[0] != "start.sh" {
t.Fatalf("destination directory = %q, want [start.sh] (temp leftover?)", got)
}
}