git » gofer » next » tree

[next] / server / write_test.go

package server

import (
	"errors"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"testing/iotest"

	"blitiri.com.ar/go/gofer/config"
	"blitiri.com.ar/go/gofer/trace"
)

// put issues a PUT through handlePut and returns the response. ius, if not
// empty, is sent as the If-Unmodified-Since header.
func put(fs *FileSystem, path, body, ius string) *http.Response {
	req := httptest.NewRequest("PUT", "http://unused"+path,
		strings.NewReader(body))
	if ius != "" {
		req.Header.Set("If-Unmodified-Since", ius)
	}
	tr := trace.New("test", path)
	req = req.WithContext(trace.NewContext(req.Context(), tr))
	w := httptest.NewRecorder()
	handlePut(fs, w, req)
	return w.Result()
}

// del issues a DELETE through handleDelete and returns the response.
func del(fs *FileSystem, path string) *http.Response {
	req := httptest.NewRequest("DELETE", "http://unused"+path, nil)
	tr := trace.New("test", path)
	req = req.WithContext(trace.NewContext(req.Context(), tr))
	w := httptest.NewRecorder()
	handleDelete(fs, w, req)
	return w.Result()
}

// TestPutLastModified checks that PUT returns a Last-Modified header, and that
// feeding it straight back as If-Unmodified-Since satisfies the precondition
// (rather than failing it). This is what lets a client chain writes without an
// extra round trip to learn the new validator.
func TestPutLastModified(t *testing.T) {
	root := t.TempDir()
	fs := NewFS(root, http.Dir(root), config.DirOpts{
		Put: map[string]bool{"/": true},
	})

	// Create the file; the response carries its Last-Modified.
	resp := put(fs, "/f.txt", "one", "")
	if resp.StatusCode != http.StatusCreated {
		t.Fatalf("create: status = %d, want 201", resp.StatusCode)
	}
	lm := resp.Header.Get("Last-Modified")
	if lm == "" {
		t.Fatal("create: no Last-Modified header")
	}

	// Replacing it with that exact validator must pass the precondition.
	resp = put(fs, "/f.txt", "two", lm)
	if resp.StatusCode != http.StatusNoContent {
		t.Fatalf("replace: status = %d, want 204 (validator did not "+
			"round-trip)", resp.StatusCode)
	}
}

// TestWriteSiblingPrefix checks that enabling PUT and DELETE on a prefix does
// not enable them on sibling paths that merely share its leading characters.
func TestWriteSiblingPrefix(t *testing.T) {
	root := t.TempDir()
	if err := os.Mkdir(filepath.Join(root, "public"), 0o755); err != nil {
		t.Fatal(err)
	}
	secret := filepath.Join(root, "public", "secret.txt")
	if err := os.WriteFile(secret, []byte("secret"), 0o644); err != nil {
		t.Fatal(err)
	}

	fs := NewFS(root, http.Dir(root), config.DirOpts{
		Put:    map[string]bool{"/pub/": true},
		Delete: map[string]bool{"/pub/": true},
	})

	// Siblings are rejected, and the existing file is left untouched.
	resp := put(fs, "/public/secret.txt", "overwritten", "")
	if resp.StatusCode != http.StatusMethodNotAllowed {
		t.Errorf("PUT sibling: status = %d, want 405", resp.StatusCode)
	}
	resp = put(fs, "/pubfoo", "new", "")
	if resp.StatusCode != http.StatusMethodNotAllowed {
		t.Errorf("PUT sibling file: status = %d, want 405", resp.StatusCode)
	}
	resp = del(fs, "/public/secret.txt")
	if resp.StatusCode != http.StatusMethodNotAllowed {
		t.Errorf("DELETE sibling: status = %d, want 405", resp.StatusCode)
	}
	if got, err := os.ReadFile(secret); err != nil || string(got) != "secret" {
		t.Errorf("sibling file changed: %q, %v", got, err)
	}
	if _, err := os.Stat(filepath.Join(root, "pubfoo")); err == nil {
		t.Errorf("PUT sibling created /pubfoo")
	}

	// The prefix itself still works.
	resp = put(fs, "/pub/f.txt", "one", "")
	if resp.StatusCode != http.StatusCreated {
		t.Errorf("PUT in prefix: status = %d, want 201", resp.StatusCode)
	}
	resp = del(fs, "/pub/f.txt")
	if resp.StatusCode != http.StatusNoContent {
		t.Errorf("DELETE in prefix: status = %d, want 204", resp.StatusCode)
	}
}

// TestWriteSymlinks checks that PUT and DELETE follow symlinks that stay within
// the root, and refuse to go through the ones that don't.
func TestWriteSymlinks(t *testing.T) {
	base := t.TempDir()
	root := filepath.Join(base, "root")
	outside := filepath.Join(base, "outside")
	target := filepath.Join(outside, "target")
	for _, d := range []string{filepath.Join(root, "sub"), outside} {
		if err := os.MkdirAll(d, 0o755); err != nil {
			t.Fatal(err)
		}
	}
	if err := os.WriteFile(target, []byte("outside"), 0o644); err != nil {
		t.Fatal(err)
	}
	links := map[string]string{
		"out-rel":  "../outside",
		"out-abs":  outside,
		"out-file": "../outside/target",
		"in-rel":   "sub",
		// Absolute symlinks are always refused, even if they stay within.
		"in-abs": filepath.Join(root, "sub"),
	}
	for name, dst := range links {
		if err := os.Symlink(dst, filepath.Join(root, name)); err != nil {
			t.Fatal(err)
		}
	}

	fs := NewFS(root, http.Dir(root), config.DirOpts{
		Put:    map[string]bool{"/": true},
		Delete: map[string]bool{"/": true},
	})

	// Going through the symlinks.
	cases := []struct {
		do   func(*FileSystem, string) *http.Response
		path string
		want int
	}{
		{putX, "/out-rel/new", http.StatusInternalServerError},
		{putX, "/out-abs/new", http.StatusInternalServerError},
		{putX, "/out-rel/target", http.StatusInternalServerError},
		{putX, "/out-rel/a/b", http.StatusInternalServerError},
		{putX, "/out-rel", http.StatusInternalServerError},
		{putX, "/out-file", http.StatusInternalServerError},
		{putX, "/in-abs/new", http.StatusInternalServerError},
		{del, "/out-rel/target", http.StatusInternalServerError},
		{del, "/out-abs/target", http.StatusInternalServerError},
		{del, "/in-abs/new", http.StatusInternalServerError},

		{putX, "/in-rel/new", http.StatusCreated},
		{putX, "/in-rel/new", http.StatusNoContent},
		{del, "/in-rel/new", http.StatusNoContent},
	}
	for _, c := range cases {
		if resp := c.do(fs, c.path); resp.StatusCode != c.want {
			t.Errorf("%q: status = %d, want %d",
				c.path, resp.StatusCode, c.want)
		}
	}
	for name, dst := range links {
		got, err := os.Readlink(filepath.Join(root, name))
		if err != nil || got != dst {
			t.Errorf("symlink %q changed: %q, %v", name, got, err)
		}
	}

	// DELETE on a symlink removes the link itself, wherever it points to.
	for name := range links {
		if resp := del(fs, "/"+name); resp.StatusCode != http.StatusNoContent {
			t.Errorf("DELETE %q: status = %d, want 204", name, resp.StatusCode)
		}
		if _, err := os.Lstat(filepath.Join(root, name)); err == nil {
			t.Errorf("symlink %q still exists", name)
		}
	}

	// Nothing outside the root has changed.
	if got, err := os.ReadFile(target); err != nil || string(got) != "outside" {
		t.Errorf("target file changed: %q, %v", got, err)
	}
	if des, err := os.ReadDir(outside); err != nil || len(des) != 1 {
		t.Errorf("unexpected entries outside the root: %v, %v", des, err)
	}
}

// putX is put for tables, with a fixed body and no preconditions.
func putX(fs *FileSystem, path string) *http.Response {
	return put(fs, path, "x", "")
}

// TestWriteRootSymlink checks that the root itself can be a symlink, even if
// it points to somewhere else. This also applies to per-user directories.
func TestWriteRootSymlink(t *testing.T) {
	base := t.TempDir()
	dst := filepath.Join(base, "dst")
	link := filepath.Join(base, "link")
	if err := os.Mkdir(dst, 0o755); err != nil {
		t.Fatal(err)
	}
	if err := os.Symlink(dst, link); err != nil {
		t.Fatal(err)
	}

	fs := NewFS(link, http.Dir(link), config.DirOpts{
		Put:    map[string]bool{"/": true},
		Delete: map[string]bool{"/": true},
	})

	if resp := putX(fs, "/f"); resp.StatusCode != http.StatusCreated {
		t.Errorf("PUT: status = %d, want 201", resp.StatusCode)
	}
	if _, err := os.Stat(filepath.Join(dst, "f")); err != nil {
		t.Errorf("file not in the symlink target: %v", err)
	}
	if resp := del(fs, "/f"); resp.StatusCode != http.StatusNoContent {
		t.Errorf("DELETE: status = %d, want 204", resp.StatusCode)
	}
}

// TestPutMissingRoot checks that the root is created by PUT if it doesn't
// exist, and that DELETE doesn't need it.
func TestPutMissingRoot(t *testing.T) {
	root := filepath.Join(t.TempDir(), "a", "b")
	fs := NewFS(root, http.Dir(root), config.DirOpts{
		Put:    map[string]bool{"/": true},
		Delete: map[string]bool{"/": true},
	})

	if resp := del(fs, "/f"); resp.StatusCode != http.StatusNotFound {
		t.Errorf("DELETE: status = %d, want 404", resp.StatusCode)
	}
	if _, err := os.Stat(root); err == nil {
		t.Errorf("DELETE created the root")
	}

	if resp := putX(fs, "/d/f"); resp.StatusCode != http.StatusCreated {
		t.Errorf("PUT: status = %d, want 201", resp.StatusCode)
	}
	if _, err := os.Stat(filepath.Join(root, "d", "f")); err != nil {
		t.Errorf("file not created: %v", err)
	}
}

// TestPutBodyError checks that if reading the body fails, the target file is
// left untouched and the temporary file is removed.
func TestPutBodyError(t *testing.T) {
	root := t.TempDir()
	if err := os.WriteFile(filepath.Join(root, "f"), []byte("old"), 0o644); err != nil {
		t.Fatal(err)
	}
	fs := NewFS(root, http.Dir(root), config.DirOpts{
		Put: map[string]bool{"/": true},
	})

	req := httptest.NewRequest("PUT", "http://unused/f",
		iotest.ErrReader(errors.New("test error")))
	req = req.WithContext(trace.NewContext(req.Context(), trace.New("test", "/f")))
	w := httptest.NewRecorder()
	handlePut(fs, w, req)
	if w.Code != http.StatusInternalServerError {
		t.Errorf("status = %d, want 500", w.Code)
	}

	if got, err := os.ReadFile(filepath.Join(root, "f")); err != nil || string(got) != "old" {
		t.Errorf("target file changed: %q, %v", got, err)
	}
	if des, err := os.ReadDir(root); err != nil || len(des) != 1 {
		t.Errorf("unexpected directory entries: %v, %v", des, err)
	}
}