Files
shared/backend/carriernodeclient/thumbnails_test.go
T

261 lines
9.3 KiB
Go
Raw Normal View History

package carriernodeclient
import (
"context"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"sync"
"testing"
)
const testThumbnailID = "3f1c2a9e-6b1d-4e8a-9f0e-2d7c5b4a1e00"
// recordingCarrierNode serves bodies at the paths it is given, accepts every write, and
// records each request so a test can see which CarrierNode paths were touched.
type recordingCarrierNode struct {
mu sync.Mutex
bodies map[string]string
requests []string
}
func (n *recordingCarrierNode) ServeHTTP(w http.ResponseWriter, r *http.Request) {
n.mu.Lock()
n.requests = append(n.requests, r.Method+" "+r.URL.Path)
body, found := n.bodies[r.URL.Path]
n.mu.Unlock()
if r.Method == http.MethodPost || r.Method == http.MethodDelete {
w.WriteHeader(http.StatusOK)
return
}
if !found {
w.WriteHeader(http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "image/jpeg")
w.WriteHeader(http.StatusOK)
if r.Method != http.MethodHead {
_, _ = io.WriteString(w, body)
}
}
func (n *recordingCarrierNode) seen() []string {
n.mu.Lock()
defer n.mu.Unlock()
return append([]string(nil), n.requests...)
}
func newThumbnailTestClient(t *testing.T, bodies map[string]string) (*Client, *recordingCarrierNode) {
t.Helper()
node := &recordingCarrierNode{bodies: bodies}
server := httptest.NewServer(node)
t.Cleanup(server.Close)
return New("", func(context.Context) string { return server.URL }), node
}
func thumbnailRequest() *http.Request {
return httptest.NewRequest(http.MethodGet, "/api/media/thumb", nil)
}
func TestStoreThumbnailWritesToProjectThumbnailsMount(t *testing.T) {
client, node := newThumbnailTestClient(t, nil)
local := filepath.Join(t.TempDir(), "thumb.jpg")
if err := os.WriteFile(local, []byte("jpeg bytes"), 0o600); err != nil {
t.Fatal(err)
}
size, err := client.StoreThumbnail(context.Background(), "ContentScanner", testThumbnailID, local)
if err != nil {
t.Fatalf("StoreThumbnail error: %v", err)
}
if size != int64(len("jpeg bytes")) {
t.Fatalf("StoreThumbnail size = %d, want %d", size, len("jpeg bytes"))
}
want := []string{"POST /api/mount/ContentScanner/thumbnails/" + testThumbnailID + ".jpg"}
if got := node.seen(); !slices.Equal(got, want) {
t.Fatalf("requests = %v, want %v", got, want)
}
}
func TestProxyThumbnailPrefersProjectMount(t *testing.T) {
mount := "/api/mount/MediaViewer/thumbnails/" + testThumbnailID + ".jpg"
legacy := "/thumbnails/" + testThumbnailID + ".jpg"
client, node := newThumbnailTestClient(t, map[string]string{mount: "from mount", legacy: "from legacy"})
rec := httptest.NewRecorder()
if !client.ProxyThumbnail(rec, thumbnailRequest(), "MediaViewer", testThumbnailID) {
t.Fatal("ProxyThumbnail missed although the mount holds the thumbnail")
}
if rec.Body.String() != "from mount" {
t.Fatalf("body = %q, want the mount copy", rec.Body.String())
}
want := []string{"GET " + mount}
if got := node.seen(); !slices.Equal(got, want) {
t.Fatalf("requests = %v, want one direct GET to the mount", got)
}
}
func TestProxyThumbnailFallsBackToLegacyRoot(t *testing.T) {
legacy := "/thumbnails/" + testThumbnailID + ".jpg"
client, node := newThumbnailTestClient(t, map[string]string{legacy: "from legacy"})
rec := httptest.NewRecorder()
if !client.ProxyThumbnail(rec, thumbnailRequest(), "ContentScanner", testThumbnailID) {
t.Fatal("ProxyThumbnail missed although the legacy root holds the thumbnail")
}
if rec.Body.String() != "from legacy" {
t.Fatalf("body = %q, want the legacy copy", rec.Body.String())
}
want := []string{"GET /api/mount/ContentScanner/thumbnails/" + testThumbnailID + ".jpg", "GET " + legacy}
if got := node.seen(); !slices.Equal(got, want) {
t.Fatalf("requests = %v, want mount miss followed by legacy GET", got)
}
}
func TestProxyThumbnailCachesResolvedPath(t *testing.T) {
mount := "/api/mount/MediaViewer/thumbnails/" + testThumbnailID + ".jpg"
client, node := newThumbnailTestClient(t, map[string]string{mount: "from mount"})
for range 2 {
if !client.ProxyThumbnail(httptest.NewRecorder(), thumbnailRequest(), "MediaViewer", testThumbnailID) {
t.Fatal("ProxyThumbnail missed although the mount holds the thumbnail")
}
}
want := []string{"GET " + mount, "GET " + mount}
if got := node.seen(); !slices.Equal(got, want) {
t.Fatalf("requests = %v, want one direct GET per request to the cached path", got)
}
}
func TestProxyThumbnailReportsMissingWithoutWriting(t *testing.T) {
client, node := newThumbnailTestClient(t, nil)
rec := httptest.NewRecorder()
if client.ProxyThumbnail(rec, thumbnailRequest(), "ContentScanner", testThumbnailID) {
t.Fatal("ProxyThumbnail reported a hit for a thumbnail neither location holds")
}
if rec.Body.Len() != 0 {
t.Fatalf("ProxyThumbnail wrote %q on a miss; the caller needs a clean fallback", rec.Body.String())
}
want := []string{
"GET /api/mount/ContentScanner/thumbnails/" + testThumbnailID + ".jpg",
"GET /thumbnails/" + testThumbnailID + ".jpg",
}
if got := node.seen(); !slices.Equal(got, want) {
t.Fatalf("requests = %v, want one GET for each candidate path", got)
}
}
func TestFetchThumbnailToScratchFallsBackToLegacyRoot(t *testing.T) {
legacy := "/thumbnails/" + testThumbnailID + ".jpg"
client, _ := newThumbnailTestClient(t, map[string]string{legacy: "from legacy"})
path, cleanup, err := client.FetchThumbnailToScratch(context.Background(), "ContentScanner", testThumbnailID, ".jpg")
if err != nil {
t.Fatalf("FetchThumbnailToScratch error: %v", err)
}
defer cleanup()
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
if string(data) != "from legacy" {
t.Fatalf("scratch contents = %q, want the legacy copy", data)
}
}
func TestDeleteStoredThumbnailRemovesMountAndLegacyCopies(t *testing.T) {
client, node := newThumbnailTestClient(t, nil)
if err := client.DeleteStoredThumbnail(context.Background(), "ContentScanner", testThumbnailID); err != nil {
t.Fatalf("DeleteStoredThumbnail error: %v", err)
}
want := []string{
"DELETE /api/mount/ContentScanner/thumbnails/" + testThumbnailID + ".jpg",
"DELETE /api/thumbnails/" + testThumbnailID,
}
if got := node.seen(); !slices.Equal(got, want) {
t.Fatalf("requests = %v, want %v", got, want)
}
}
func TestThumbnailIDsCannotEscapeTheThumbnailsDirectory(t *testing.T) {
client, node := newThumbnailTestClient(t, nil)
ctx := context.Background()
for _, id := range []string{"", ".", "..", "../secret", "nested/id"} {
if client.ProxyThumbnail(httptest.NewRecorder(), thumbnailRequest(), "ContentScanner", id) {
t.Errorf("ProxyThumbnail accepted id %q", id)
}
if _, _, err := client.FetchThumbnailToScratch(ctx, "ContentScanner", id, ".jpg"); err == nil {
t.Errorf("FetchThumbnailToScratch accepted id %q", id)
}
if _, err := client.StoreThumbnail(ctx, "ContentScanner", id, filepath.Join(t.TempDir(), "x.jpg")); err == nil {
t.Errorf("StoreThumbnail accepted id %q", id)
}
if err := client.DeleteStoredThumbnail(ctx, "ContentScanner", id); err == nil {
t.Errorf("DeleteStoredThumbnail accepted id %q", id)
}
}
if got := node.seen(); len(got) != 0 {
t.Fatalf("invalid thumbnail ids reached CarrierNode: %v", got)
}
}
// TestPushAndDeleteNamesCannotEscapeTheirDirectory checks that the push and delete helpers refuse
// names that are "." or ".." or contain a separator before any request reaches CarrierNode.
func TestPushAndDeleteNamesCannotEscapeTheirDirectory(t *testing.T) {
client, node := newThumbnailTestClient(t, nil)
ctx := context.Background()
local := filepath.Join(t.TempDir(), "payload.bin")
if err := os.WriteFile(local, []byte("x"), 0o600); err != nil {
t.Fatal(err)
}
for _, name := range []string{"", ".", "..", "../escape", `..\escape`, "nested/name"} {
if _, err := client.PushThumbnail(ctx, name, local); err == nil {
t.Errorf("PushThumbnail accepted name %q", name)
}
if err := client.DeleteThumbnail(ctx, name); err == nil {
t.Errorf("DeleteThumbnail accepted name %q", name)
}
}
// Outputs, inputs and copies may nest, but no segment may climb out of its directory.
for _, name := range []string{"", ".", "..", "../escape", `..\escape`, "/abs", "a//b", "a/../b", "a/./b", "a/"} {
if _, err := client.PushOutput(ctx, name, local); err == nil {
t.Errorf("PushOutput accepted name %q", name)
}
if _, err := client.PushInput(ctx, name, local); err == nil {
t.Errorf("PushInput accepted name %q", name)
}
if _, err := client.PushCopy(ctx, name, local); err == nil {
t.Errorf("PushCopy accepted name %q", name)
}
}
if got := node.seen(); len(got) != 0 {
t.Fatalf("invalid names reached CarrierNode: %v", got)
}
}
// TestNestedOutputNamesAreAccepted checks that CraftStudio-style nested output names pass the
// relative-name check, so generator outputs keep their CarrierNode path.
func TestNestedOutputNamesAreAccepted(t *testing.T) {
for _, name := range []string{"CraftStudio/alice/flux/out.png", "a/b.txt"} {
if err := validRelativeName(name); err != nil {
t.Errorf("validRelativeName(%q) = %v, want nil", name, err)
}
}
}
// TestValidNamesAreNotRefused checks that ordinary names, including ones with spaces or query
// characters, pass the name check; the path escaping in MountPath and the push helpers handles them.
func TestValidNamesAreNotRefused(t *testing.T) {
for _, name := range []string{"clip.mp4", "my clip?.mp4", "a#b", "v1.2.final"} {
if err := validName(name); err != nil {
t.Errorf("validName(%q) = %v, want nil", name, err)
}
}
}