241 lines
8.1 KiB
Go
241 lines
8.1 KiB
Go
package seaweedfs
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
|
|
"lincodex/backend/config"
|
|
"lincodex/backend/internal/port/outbound"
|
|
)
|
|
|
|
func TestStorageStreamsUploadWithExplicitCredentials(t *testing.T) {
|
|
t.Setenv("AWS_ENDPOINT_URL_S3", "http://unused.invalid")
|
|
t.Setenv("AWS_ACCESS_KEY_ID", "wrong-access")
|
|
t.Setenv("AWS_SECRET_ACCESS_KEY", "wrong-secret")
|
|
payload := bytes.Repeat([]byte("stream-data"), 1024)
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPut || r.URL.Path != "/test-files/private/file" {
|
|
t.Errorf("unexpected upload route: %s %s", r.Method, r.URL.Path)
|
|
}
|
|
if !strings.Contains(r.Header.Get("Authorization"), "Credential=test-access/") {
|
|
t.Error("configured credentials were not used")
|
|
}
|
|
if r.ContentLength != int64(len(payload)) || r.Header.Get("Content-Type") != "application/pdf" {
|
|
t.Error("upload metadata differs")
|
|
}
|
|
body, err := io.ReadAll(r.Body)
|
|
if err != nil || !bytes.Equal(body, payload) {
|
|
t.Errorf("upload body differs: %v", err)
|
|
}
|
|
w.WriteHeader(http.StatusOK)
|
|
}))
|
|
defer server.Close()
|
|
storage := newTestStorage(t, server.URL, time.Second)
|
|
// Hide Seek to exercise streaming inputs such as request bodies.
|
|
body := struct{ io.Reader }{bytes.NewReader(payload)}
|
|
if err := storage.Put(t.Context(), "private/file", body, int64(len(payload)), "application/pdf"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
func TestStorageGetKeepsBodyAliveUntilClose(t *testing.T) {
|
|
release := make(chan struct{})
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Length", "6")
|
|
w.Header().Set("Content-Type", "text/plain")
|
|
_, _ = io.WriteString(w, "abc")
|
|
w.(http.Flusher).Flush()
|
|
select {
|
|
case <-release:
|
|
_, _ = io.WriteString(w, "def")
|
|
case <-r.Context().Done():
|
|
}
|
|
}))
|
|
defer server.Close()
|
|
storage := newTestStorage(t, server.URL, time.Second)
|
|
object, err := storage.Get(t.Context(), "private/file")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer object.Body.Close()
|
|
if object.Size != 6 || object.ContentType != "text/plain" {
|
|
t.Fatal("download metadata differs")
|
|
}
|
|
first := make([]byte, 3)
|
|
if _, err := io.ReadFull(object.Body, first); err != nil || string(first) != "abc" {
|
|
t.Fatalf("Get returned a closed or buffered body: %q, %v", first, err)
|
|
}
|
|
close(release)
|
|
remaining, err := io.ReadAll(object.Body)
|
|
if err != nil || string(remaining) != "def" {
|
|
t.Fatalf("remaining body: %q, %v", remaining, err)
|
|
}
|
|
}
|
|
|
|
func TestStorageGetBodyHonorsCancellationAndTimeout(t *testing.T) {
|
|
for _, mode := range []string{"caller", "timeout", "close"} {
|
|
t.Run(mode, func(t *testing.T) {
|
|
disconnected := make(chan struct{})
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Length", "100")
|
|
w.WriteHeader(http.StatusOK)
|
|
w.(http.Flusher).Flush()
|
|
<-r.Context().Done()
|
|
close(disconnected)
|
|
}))
|
|
defer server.Close()
|
|
timeout := time.Second
|
|
if mode == "timeout" {
|
|
timeout = 100 * time.Millisecond
|
|
}
|
|
storage := newTestStorage(t, server.URL, timeout)
|
|
ctx, cancel := context.WithCancel(t.Context())
|
|
defer cancel()
|
|
object, err := storage.Get(ctx, "private/file")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer object.Body.Close()
|
|
switch mode {
|
|
case "close":
|
|
if err := object.Body.Close(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
case "caller", "timeout":
|
|
want := context.DeadlineExceeded
|
|
if mode == "caller" {
|
|
cancel()
|
|
want = context.Canceled
|
|
}
|
|
if _, err := object.Body.Read(make([]byte, 1)); !errors.Is(err, want) {
|
|
t.Fatalf("body cancellation: %v, want %v", err, want)
|
|
}
|
|
}
|
|
select {
|
|
case <-disconnected:
|
|
case <-time.After(time.Second):
|
|
t.Fatal("response body left the server connection open")
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestStorageClassifiesOnlyMissingObjectsAsNotFound(t *testing.T) {
|
|
for _, test := range []struct {
|
|
name, code string
|
|
status int
|
|
missing bool
|
|
}{
|
|
{name: "object", code: "NoSuchKey", status: http.StatusNotFound, missing: true},
|
|
{name: "bucket", code: "NoSuchBucket", status: http.StatusNotFound},
|
|
{name: "generic 404", code: "NotFound", status: http.StatusNotFound},
|
|
{name: "credentials", code: "InvalidAccessKeyId", status: http.StatusForbidden},
|
|
{name: "permission", code: "AccessDenied", status: http.StatusForbidden},
|
|
{name: "server", code: "InternalError", status: http.StatusInternalServerError},
|
|
} {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
var requests atomic.Int32
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
|
requests.Add(1)
|
|
w.Header().Set("Content-Type", "application/xml")
|
|
w.WriteHeader(test.status)
|
|
_, _ = fmt.Fprintf(w, "<Error><Code>%s</Code><Message>private-file test-secret</Message><Key>private-file</Key></Error>", test.code)
|
|
}))
|
|
defer server.Close()
|
|
storage := newTestStorage(t, server.URL, time.Second)
|
|
_, err := storage.Get(t.Context(), "private-file")
|
|
if err == nil || errors.Is(err, outbound.ErrObjectNotFound) != test.missing {
|
|
t.Fatalf("wrong object error classification: %v", err)
|
|
}
|
|
if !strings.HasPrefix(err.Error(), "Storage.Get - get object: ") {
|
|
t.Fatalf("storage error lacks method context: %v", err)
|
|
}
|
|
if requests.Load() != 1 {
|
|
t.Fatal("request unexpectedly retried")
|
|
}
|
|
for _, sensitive := range []string{"private-file", "test-secret", server.URL} {
|
|
if strings.Contains(err.Error(), sensitive) {
|
|
t.Fatal("storage error disclosed sensitive request data")
|
|
}
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestStorageReadinessDoesNotProvisionBucket(t *testing.T) {
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodHead || r.URL.Path != "/test-files/" {
|
|
t.Errorf("readiness attempted a mutation or wrong bucket: %s %s", r.Method, r.URL.Path)
|
|
}
|
|
w.WriteHeader(http.StatusForbidden)
|
|
}))
|
|
defer server.Close()
|
|
storage := newTestStorage(t, server.URL, time.Second)
|
|
if err := storage.Check(t.Context()); !errors.Is(err, outbound.ErrObjectStorage) {
|
|
t.Fatalf("unavailable bucket passed readiness: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestStorageDoesNotFollowRedirects(t *testing.T) {
|
|
var redirected atomic.Bool
|
|
other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
|
redirected.Store(true)
|
|
w.WriteHeader(http.StatusOK)
|
|
}))
|
|
defer other.Close()
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
http.Redirect(w, r, other.URL, http.StatusTemporaryRedirect)
|
|
}))
|
|
defer server.Close()
|
|
storage := newTestStorage(t, server.URL, time.Second)
|
|
if _, err := storage.Get(t.Context(), "private-file"); err == nil || redirected.Load() {
|
|
t.Fatal("storage followed a redirect away from the configured endpoint")
|
|
}
|
|
}
|
|
|
|
func TestStorageRequestCancellation(t *testing.T) {
|
|
server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) { t.Error("canceled request reached server") }))
|
|
defer server.Close()
|
|
storage := newTestStorage(t, server.URL, time.Second)
|
|
ctx, cancel := context.WithCancel(t.Context())
|
|
cancel()
|
|
for name, call := range map[string]func() error{
|
|
"get": func() error { _, err := storage.Get(ctx, "file"); return err },
|
|
"put": func() error { return storage.Put(ctx, "file", strings.NewReader("data"), 4, "text/plain") },
|
|
"delete": func() error { return storage.Delete(ctx, "file") },
|
|
"readiness": func() error { return storage.Check(ctx) },
|
|
} {
|
|
t.Run(name, func(t *testing.T) {
|
|
if err := call(); !errors.Is(err, context.Canceled) {
|
|
t.Fatalf("cancellation lost: %v", err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func newTestStorage(t *testing.T, endpoint string, timeout time.Duration) *Storage {
|
|
t.Helper()
|
|
storage, cleanup, err := NewStorage(config.Config{
|
|
SeaweedFSEndpoint: endpoint,
|
|
SeaweedFSAccessKey: "test-access",
|
|
SeaweedFSSecretKey: "test-secret",
|
|
SeaweedFSBucket: "test-files",
|
|
SeaweedFSRegion: "us-east-1",
|
|
SeaweedFSTimeout: timeout,
|
|
})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(cleanup)
|
|
return storage
|
|
}
|