package assets import ( "archive/zip" "bytes" "context" "errors" "io/fs" "os" "path/filepath" "runtime" "strings" "testing" "testing/fstest" ) func TestValidatePath(t *testing.T) { ok := []string{"a", "images/logo.png", "a/b/c.wasm", "%2e%2e/x", "dir.with.dots/f"} bad := []string{"", "/abs", "../x", "a/../b", "./a", "a//b", "a/", `a\b`, "C:/x", "c:x", "a\x00b", "assets:x", ".."} for _, p := range ok { if err := ValidatePath(p); err != nil { t.Errorf("ValidatePath(%q) = %v, want ok", p, err) } } for _, p := range bad { if err := ValidatePath(p); !errors.Is(err, ErrInvalidPath) { t.Errorf("ValidatePath(%q) = %v, want ErrInvalidPath", p, err) } } } func TestFromRefBothForms(t *testing.T) { for _, ref := range []string{"/assets/images/a.png", "assets:images/a.png", "/assets/images/a.png?v=1#x", "assets:images/a.png#frag"} { got, err := FromRef(ref) if err != nil || got != "images/a.png" { t.Errorf("FromRef(%q) = %q, %v", ref, got, err) } } for _, ref := range []string{"/other/x", "assets:../x", "/assets/", "/assets//etc/passwd"} { if _, err := FromRef(ref); err == nil { t.Errorf("FromRef(%q) accepted", ref) } } } func TestJoinRelativeInsideRoot(t *testing.T) { cases := map[[2]string]string{ {"css/app.css", "../images/bg.png"}: "images/bg.png", {"css/app.css", "fonts.css"}: "css/fonts.css", {"css/a/b.css", "../../x.png"}: "x.png", } for in, want := range cases { if got, err := Join(in[0], in[1]); err != nil || got != want { t.Errorf("Join(%q,%q) = %q, %v; want %q", in[0], in[1], got, err, want) } } for _, ref := range []string{"../../x.png", "../../../etc/passwd", `..\x`} { if _, err := Join("css/app.css", ref); err == nil { t.Errorf("Join escaped root with %q", ref) } } } func TestMIME(t *testing.T) { want := map[string]string{ "a.css": "text/css", "a.js": "text/javascript", "a.svg": "image/svg+xml", "a.png": "image/png", "a.ttf": "font/ttf", "a.woff2": "font/woff2", "a.json": "application/json", "a.ico": "image/x-icon", } for name, m := range want { got, err := DetectMIME(name, []byte("x")) if err != nil || BaseMIME(got) != m { t.Errorf("%s: %q %v, want %s", name, got, err, m) } } if m, err := DetectMIME("a.wasm", []byte("\x00asm\x01\x00\x00\x00")); err != nil || m != "application/wasm" { t.Errorf("wasm: %q %v", m, err) } if _, err := DetectMIME("a.wasm", []byte("not wasm")); err == nil { t.Error("fake .wasm accepted") } if m, _ := DetectMIME("noext", []byte("\x89PNG\r\n\x1a\n")); m != "image/png" { t.Errorf("sniff fallback: %q", m) } } func zipBytes(t *testing.T, files map[string]string) []byte { t.Helper() var buf bytes.Buffer zw := zip.NewWriter(&buf) for name, data := range files { w, err := zw.Create(name) if err != nil { t.Fatal(err) } w.Write([]byte(data)) } if err := zw.Close(); err != nil { t.Fatal(err) } return buf.Bytes() } func TestAllSourcesSameIdentity(t *testing.T) { files := map[string]string{"index.html": "

hi

", "wasm/a.wasm": "\x00asm\x01\x00\x00\x00", "css/app.css": "body{}"} mfs := fstest.MapFS{} dir := t.TempDir() for name, data := range files { mfs[name] = &fstest.MapFile{Data: []byte(data)} os.MkdirAll(filepath.Join(dir, filepath.Dir(name)), 0o755) os.WriteFile(filepath.Join(dir, name), []byte(data), 0o644) } zipPath := filepath.Join(t.TempDir(), "assets.zip") os.WriteFile(zipPath, zipBytes(t, files), 0o644) dirSrc, err := NewDirSource(dir) if err != nil { t.Fatal(err) } zipSrc, err := NewZipFileSource(zipPath, "") if err != nil { t.Fatal(err) } embZip, err := NewZipBytesSource("embedzip", zipBytes(t, files), "") if err != nil { t.Fatal(err) } for _, s := range []Source{NewFSSource("embed", mfs), dirSrc, zipSrc, embZip} { r, _ := NewResolver(s) for name, data := range files { res, err := r.Resolve(context.Background(), name) if err != nil || string(res.Bytes) != data || res.Source != s.Name() { t.Errorf("%s %s: %v", s.Name(), name, err) } } if err := r.Close(); err != nil { t.Errorf("close %s: %v", s.Name(), err) } } } func TestFallbackOnlyOnNotFound(t *testing.T) { first := fstest.MapFS{"a.txt": {Data: []byte("first")}} second := fstest.MapFS{"a.txt": {Data: []byte("second")}, "b.txt": {Data: []byte("b")}} r, _ := NewResolver(NewFSSource("one", first), NewFSSource("two", second)) if res, _ := r.Resolve(context.Background(), "a.txt"); string(res.Bytes) != "first" { t.Error("override order not respected") } if res, _ := r.Resolve(context.Background(), "b.txt"); res.Source != "two" { t.Error("no fallback on not-found") } if _, err := r.Resolve(context.Background(), "c.txt"); !errors.Is(err, fs.ErrNotExist) { t.Errorf("missing: %v", err) } // A real read error in the first source must not fall through. boom := &errSource{err: errors.New("permission denied")} r2, _ := NewResolver(boom, NewFSSource("two", second)) if _, err := r2.Resolve(context.Background(), "b.txt"); err == nil || !strings.Contains(err.Error(), "permission denied") { t.Errorf("read error swallowed: %v", err) } } type errSource struct{ err error } func (e *errSource) Name() string { return "err" } func (e *errSource) Close() error { return nil } func (e *errSource) ReadFile(string, int64) ([]byte, error) { return nil, e.err } func TestCorruptZipIsError(t *testing.T) { p := filepath.Join(t.TempDir(), "bad.zip") os.WriteFile(p, []byte("not a zip"), 0o644) if _, err := NewZipFileSource(p, ""); err == nil { t.Error("corrupt zip accepted") } } func TestZipUnsafeNamesAndBudget(t *testing.T) { data := zipBytes(t, map[string]string{"../evil.txt": "x", "/abs.txt": "x", `a\b.txt`: "x", "assets/ok.txt": "ok", "big.bin": strings.Repeat("x", 2048)}) s, err := NewZipBytesSource("z", data, "") if err != nil { t.Fatal(err) } for _, name := range []string{"evil.txt", "abs.txt"} { if _, err := s.ReadFile(name, 1<<20); !errors.Is(err, fs.ErrNotExist) { t.Errorf("%s reachable: %v", name, err) } } if _, err := s.ReadFile("big.bin", 1024); err == nil || !strings.Contains(err.Error(), "budget") { t.Errorf("budget not enforced: %v", err) } // Explicit zip root for archives that contain an assets/ folder. s2, _ := NewZipBytesSource("z", data, "assets") if b, err := s2.ReadFile("ok.txt", 1024); err != nil || string(b) != "ok" { t.Errorf("zip root: %q %v", b, err) } } func TestDirSymlinkEscape(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("symlink creation needs privileges on Windows") } outside := t.TempDir() os.WriteFile(filepath.Join(outside, "secret.txt"), []byte("secret"), 0o644) root := t.TempDir() if err := os.Symlink(filepath.Join(outside, "secret.txt"), filepath.Join(root, "link.txt")); err != nil { t.Fatal(err) } if err := os.Symlink(outside, filepath.Join(root, "linkdir")); err != nil { t.Fatal(err) } s, err := NewDirSource(root) if err != nil { t.Fatal(err) } defer s.Close() for _, name := range []string{"link.txt", "linkdir/secret.txt"} { if b, err := s.ReadFile(name, 1024); err == nil { t.Errorf("%s escaped root: %q", name, b) } } }