fix(05): WR-05 gate public file serving on is_public

This commit is contained in:
Jakub Zych
2026-09-19 15:37:04 +02:00
parent c12e6576f6
commit 56156ae7c3
5 changed files with 195 additions and 0 deletions

View File

@@ -4,6 +4,8 @@ import (
"context"
"database/sql"
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"time"
@@ -185,6 +187,62 @@ func TestFileCreateDefaultsIsPublic(t *testing.T) {
}
}
func TestStaticHandlerPublicLooksUpIsPublic(t *testing.T) {
if testing.Short() {
t.Skip("requires testcontainers postgres")
}
ctx := t.Context()
gdb := attachGorm(t)
if err := lagoon.Migrate(gdb, nil); err != nil {
t.Fatal(err)
}
bucket := memblob.OpenBucket(nil)
t.Cleanup(func() { _ = bucket.Close() })
pub := true
priv := false
publicFile := attach.File{DiskName: "abc123xyz.jpg", FileName: "cover.jpg", FileSize: 1, ContentType: "image/jpeg", IsPublic: &pub}
privateFile := attach.File{DiskName: "def456uvw.jpg", FileName: "secret.jpg", FileSize: 1, ContentType: "image/jpeg", IsPublic: &priv}
if err := gdb.Create(&publicFile).Error; err != nil {
t.Fatal(err)
}
if err := gdb.Create(&privateFile).Error; err != nil {
t.Fatal(err)
}
for _, f := range []attach.File{publicFile, privateFile} {
if err := bucket.WriteAll(ctx, attach.BlobKey(f.DiskName), []byte(f.FileName), &blob.WriterOptions{ContentType: "image/jpeg"}); err != nil {
t.Fatal(err)
}
thumbKey := attach.PartitionDirectory(f.DiskName) + attach.ThumbFilename(f.ID, 50, 50, 0, 0, "crop", "jpg")
if err := bucket.WriteAll(ctx, thumbKey, []byte("thumb"), &blob.WriterOptions{ContentType: "image/jpeg"}); err != nil {
t.Fatal(err)
}
}
h := attach.StaticHandlerPublic(bucket, "/storage/uploads", gdb)
get := func(path string) int {
t.Helper()
rr := httptest.NewRecorder()
h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, path, nil))
return rr.Code
}
if code := get("/storage/uploads/abc/123/xyz/abc123xyz.jpg"); code != http.StatusOK {
t.Fatalf("public original status = %d, want 200", code)
}
if code := get("/storage/uploads/abc/123/xyz/" + attach.ThumbFilename(publicFile.ID, 50, 50, 0, 0, "crop", "jpg")); code != http.StatusOK {
t.Fatalf("public thumb status = %d, want 200", code)
}
if code := get("/storage/uploads/def/456/uvw/def456uvw.jpg"); code != http.StatusNotFound {
t.Fatalf("private original status = %d, want 404", code)
}
if code := get("/storage/uploads/def/456/uvw/" + attach.ThumbFilename(privateFile.ID, 50, 50, 0, 0, "crop", "jpg")); code != http.StatusNotFound {
t.Fatalf("private thumb status = %d, want 404", code)
}
if code := get("/storage/uploads/abc/123/xyz/missing.jpg"); code != http.StatusNotFound {
t.Fatalf("unknown disk_name status = %d, want 404", code)
}
}
func assertFileRow(t *testing.T, gdb *gorm.DB, id uint, want bool) {
t.Helper()
var n int64