package server
import (
"io/fs"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
func TestDirListError(t *testing.T) {
// Use this file as a "directory" for dirList.
// We expect it to return a 500 error.
d := http.Dir(".")
f, _ := d.Open("fileserver_test.go")
req := httptest.NewRequest("GET", "http://unused/", nil)
w := httptest.NewRecorder()
dirList(w, req, f)
resp := w.Result()
if resp.StatusCode != http.StatusInternalServerError {
t.Errorf("expected internal server error, got %v", resp)
}
}
func TestToHTTPError(t *testing.T) {
cases := []struct {
err error
expStatus int
}{
{fs.ErrNotExist, http.StatusNotFound},
{fs.ErrPermission, http.StatusForbidden},
{fs.ErrInvalid, http.StatusInternalServerError},
}
for _, c := range cases {
w := httptest.NewRecorder()
toHTTPError(w, c.err)
resp := w.Result()
if resp.StatusCode != c.expStatus {
t.Errorf("for error %v: expected %v, got %v",
c.err, c.expStatus, resp.StatusCode)
}
}
}
func TestHumanizeInt(t *testing.T) {
cases := []struct {
i int64
e string
}{
{10, "10"},
{1025, "1K"},
{2 * 1024, "2K"},
{2 * 1024 * 1024, "2M"},
{2 * 1024 * 1024 * 1024, "2G"},
}
for _, c := range cases {
s := humanizeInt(c.i)
if s != c.e {
t.Errorf("%v: expected %q, got %q", c.i, c.e, s)
}
}
}
// TestDirListEscaping checks that the links in directory listings are properly
// escaped, including names that are special in URLs and in HTML.
func TestDirListEscaping(t *testing.T) {
cases := []struct {
name string
want string
}{
{"plain", `<a href="plain">plain</a>`},
{"ñaca", `<a href="%C3%B1aca">ñaca</a>`},
{"a b", `<a href="a%20b">a b</a>`},
{"%41", `<a href="%2541">%41</a>`},
// Special in URLs.
{"#anchor", `<a href="%23anchor">#anchor</a>`},
{"?query", `<a href="%3Fquery">?query</a>`},
// These could be mistaken for a URL scheme.
{"x:y", `<a href="./x:y">x:y</a>`},
{"javascript:alert(1)",
`<a href="./javascript:alert%281%29">javascript:alert(1)</a>`},
// Special in HTML.
{"<a>", `<a href="%3Ca%3E"><a></a>`},
{`a"b`, `<a href="a%22b">a"b</a>`},
{"a'b", `<a href="a%27b">a'b</a>`},
{"&", `<a href="&amp;">&amp;</a>`},
{"<img src=x onerror=alert(1)>",
`<a href="%3Cimg%20src=x%20onerror=alert%281%29%3E">` +
`<img src=x onerror=alert(1)></a>`},
}
root := t.TempDir()
for _, c := range cases {
err := os.WriteFile(filepath.Join(root, c.name), nil, 0o644)
if err != nil {
t.Fatal(err)
}
}
req := httptest.NewRequest("GET", "http://unused/", nil)
w := httptest.NewRecorder()
FileServer(http.Dir(root)).ServeHTTP(w, req)
body := w.Body.String()
for _, c := range cases {
if !strings.Contains(body, c.want) {
t.Errorf("%q: %q not found in the listing", c.name, c.want)
}
}
if strings.Contains(body, "ZgotmplZ") {
t.Errorf("html/template filtered out a value:\n%s", body)
}
}