package s3api
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3notification"
"github.com/stretchr/testify/require"
)
const testNotificationTargets = `{"targets":[
{"name":"orders","type":"webhook","enabled":true,"endpoint":"https://hooks.internal/orders","bearer_token":"tok","allowed_buckets":["b","orders-*"]},
{"name":"raw","type":"topic","enabled":true,"allowed_buckets":["*"]},
{"name":"off","type":"topic","enabled":false,"allowed_buckets":["*"]}
]}`
func targetsEntry(name, content string) *filer_pb.Entry {
return &filer_pb.Entry{Name: name, Content: []byte(content)}
}
func TestOnNotificationTargetsChange(t *testing.T) {
s3a := &S3ApiServer{}
dir := s3notification.TargetsDirectory
file := s3notification.TargetsFile
s3a.onNotificationTargetsChange(dir, nil, targetsEntry(file, testNotificationTargets))
require.Equal(t, []string{"orders", "raw", "off"}, s3a.notificationTargetRegistry().Names())
// An edit that does not parse keeps what was loaded.
s3a.onNotificationTargetsChange(dir, targetsEntry(file, testNotificationTargets), targetsEntry(file, `{"targets":[{"name":"x","type":"nope"}]}`))
require.Equal(t, []string{"orders", "raw", "off"}, s3a.notificationTargetRegistry().Names())
// A file stored in chunks has no inline content to read; it is not an empty registry.
chunked := &filer_pb.Entry{Name: file, Chunks: []*filer_pb.FileChunk{{FileId: "3,01637037d6", Size: 400}}}
s3a.onNotificationTargetsChange(dir, targetsEntry(file, testNotificationTargets), chunked)
require.Equal(t, []string{"orders", "raw", "off"}, s3a.notificationTargetRegistry().Names())
s3a.onNotificationTargetsChange(dir, targetsEntry(file, testNotificationTargets), targetsEntry(file, `{"targets":[{"name":"raw","type":"topic","enabled":true,"allowed_buckets":["*"]}]}`))
require.Equal(t, []string{"raw"}, s3a.notificationTargetRegistry().Names())
// Other files in the directory and the same name elsewhere are ignored.
s3a.onNotificationTargetsChange(dir, nil, targetsEntry("targets.json.bak", testNotificationTargets))
s3a.onNotificationTargetsChange("/etc/s3", nil, targetsEntry(file, testNotificationTargets))
s3a.onNotificationTargetsChange(dir+"/sub", targetsEntry(file, ""), nil)
require.Equal(t, []string{"raw"}, s3a.notificationTargetRegistry().Names())
// Renamed away within the directory, then back.
s3a.onNotificationTargetsChange(dir, targetsEntry(file, ""), targetsEntry("targets.json.bak", ""))
require.Nil(t, s3a.notificationTargetRegistry())
s3a.onNotificationTargetsChange(dir, targetsEntry("targets.json.bak", ""), targetsEntry(file, testNotificationTargets))
require.Len(t, s3a.notificationTargetRegistry().Names(), 3)
s3a.onNotificationTargetsChange(dir, targetsEntry(file, testNotificationTargets), nil)
require.Nil(t, s3a.notificationTargetRegistry())
// A move to another directory arrives under the destination, then is
// replayed as a delete in the source.
s3a.onNotificationTargetsChange(dir, nil, targetsEntry(file, testNotificationTargets))
s3a.onNotificationTargetsChange("/etc/s3/archive", targetsEntry(file, testNotificationTargets), targetsEntry(file, testNotificationTargets))
require.NotNil(t, s3a.notificationTargetRegistry())
s3a.onNotificationTargetsChange(dir, targetsEntry(file, testNotificationTargets), nil)
require.Nil(t, s3a.notificationTargetRegistry())
}
// fakeNotificationPublisher records what the gateway publishes; it acks
// every message unless stalled.
type fakeNotificationPublisher struct {
mu sync.Mutex
stalled bool
calls int
synced [][]string
messages []s3notification.Message
}
func (f *fakeNotificationPublisher) Sync(reg *s3notification.Registry) {
f.mu.Lock()
defer f.mu.Unlock()
f.synced = append(f.synced, reg.Names())
}
func (f *fakeNotificationPublisher) Publish(ctx context.Context, messages []s3notification.Message) bool {
f.mu.Lock()
defer f.mu.Unlock()
if len(messages) > 0 {
f.calls++
}
f.messages = append(f.messages, messages...)
return !f.stalled
}
func (f *fakeNotificationPublisher) Close() {}
func (f *fakeNotificationPublisher) published() []s3notification.Message {
f.mu.Lock()
defer f.mu.Unlock()
return append([]s3notification.Message(nil), f.messages...)
}
func TestNotificationTargetsChangeSyncsThePublisherAndForwarder(t *testing.T) {
publisher, forwarder := &fakeNotificationPublisher{}, &fakeNotificationPublisher{}
s3a := &S3ApiServer{notificationPublisher: publisher, notificationForwarder: forwarder}
dir, file := s3notification.TargetsDirectory, s3notification.TargetsFile
s3a.onNotificationTargetsChange(dir, nil, targetsEntry(file, testNotificationTargets))
s3a.onNotificationTargetsChange(dir, targetsEntry(file, testNotificationTargets), targetsEntry(file, `{"targets":[{"name":"x","type":"nope"}]}`))
s3a.onNotificationTargetsChange(dir, targetsEntry(file, testNotificationTargets), nil)
require.Equal(t, [][]string{{"orders", "raw", "off"}, nil}, publisher.synced)
require.Equal(t, [][]string{{"orders", "raw", "off"}, nil}, forwarder.synced)
}
func TestLoadNotificationTargets(t *testing.T) {
s3a := newHeadBucketTestServer(t, &fakeLookupFiler{entry: targetsEntry(s3notification.TargetsFile, testNotificationTargets)})
s3a.loadNotificationTargets()
target, ok := s3a.notificationTargetRegistry().Resolve("orders", "orders-eu")
require.True(t, ok)
require.Equal(t, s3notification.TargetTypeWebhook, target.Type)
missing := newHeadBucketTestServer(t, &fakeLookupFiler{})
missing.loadNotificationTargets()
require.Nil(t, missing.notificationTargetRegistry())
broken := newHeadBucketTestServer(t, &fakeLookupFiler{entry: targetsEntry(s3notification.TargetsFile, `{`)})
broken.loadNotificationTargets()
require.Nil(t, broken.notificationTargetRegistry())
chunked := newHeadBucketTestServer(t, &fakeLookupFiler{entry: &filer_pb.Entry{Name: s3notification.TargetsFile, Chunks: []*filer_pb.FileChunk{{FileId: "3,01637037d6", Size: 400}}}})
chunked.loadNotificationTargets()
require.Nil(t, chunked.notificationTargetRegistry())
}
const testNotificationXML = `
created
arn:aws:sns:us-east-1:123456789012:orders
s3:ObjectCreated:*
prefixin/
arn:aws:sqs:::raw
s3:ObjectRemoved:*
`
func newNotificationTestServer(t *testing.T, bucket string, extended map[string][]byte) (*S3ApiServer, *fakeLookupFiler) {
t.Helper()
s3a, filer := newPublicAccessBlockTestServer(t, &filer_pb.Entry{Name: bucket, IsDirectory: true, Extended: extended})
s3a.notificationPublisher = &fakeNotificationPublisher{}
require.NoError(t, s3a.loadNotificationTargetsFromBytes([]byte(testNotificationTargets)))
return s3a, filer
}
func notificationRequest(method, bucket, body string) *http.Request {
return newBucketRequest(method, bucket, "notification=", body)
}
func TestPutBucketNotificationConfigurationStoresDocument(t *testing.T) {
const bucket = "b"
s3a, filer := newNotificationTestServer(t, bucket, map[string][]byte{
s3_constants.ExtVersioningKey: []byte(s3_constants.VersioningEnabled),
})
rec := httptest.NewRecorder()
s3a.PutBucketNotificationConfigurationHandler(rec, notificationRequest(http.MethodPut, bucket, testNotificationXML))
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
// Only the notification key is patched, with the document byte for byte.
require.Len(t, filer.txnSeen, 1)
m := filer.txnSeen[0].Mutations[0]
require.Equal(t, filer_pb.ObjectMutation_PATCH_EXTENDED, m.Type)
require.Equal(t, map[string][]byte{s3_constants.ExtNotificationConfigurationKey: []byte(testNotificationXML)}, m.SetExtended)
require.Empty(t, m.DeleteExtended)
filer.entry.Extended[s3_constants.ExtNotificationConfigurationKey] = m.SetExtended[s3_constants.ExtNotificationConfigurationKey]
rec = httptest.NewRecorder()
s3a.GetBucketNotificationConfigurationHandler(rec, notificationRequest(http.MethodGet, bucket, ""))
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
require.Equal(t, testNotificationXML, rec.Body.String())
require.Contains(t, rec.Header().Get("Content-Type"), "xml")
config, errCode := s3a.getBucketConfig(bucket)
require.Equal(t, s3err.ErrNone, errCode)
require.Equal(t, []s3notification.Match{{ID: "created", Target: "orders"}}, config.Notification.Match("s3:ObjectCreated:Put", "in/x"))
require.Len(t, config.Notification.Match("s3:ObjectRemoved:Delete", "in/x"), 1)
}
func TestPutBucketNotificationConfigurationEmptyRemovesDocument(t *testing.T) {
const bucket = "b"
s3a, filer := newNotificationTestServer(t, bucket, map[string][]byte{
s3_constants.ExtNotificationConfigurationKey: []byte(testNotificationXML),
})
rec := httptest.NewRecorder()
s3a.PutBucketNotificationConfigurationHandler(rec, notificationRequest(http.MethodPut, bucket, ``))
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
require.Len(t, filer.txnSeen, 1)
m := filer.txnSeen[0].Mutations[0]
require.Empty(t, m.SetExtended)
require.Equal(t, []string{s3_constants.ExtNotificationConfigurationKey}, m.DeleteExtended)
}
func TestGetBucketNotificationConfigurationUnconfigured(t *testing.T) {
s3a, _ := newNotificationTestServer(t, "b", nil)
rec := httptest.NewRecorder()
s3a.GetBucketNotificationConfigurationHandler(rec, notificationRequest(http.MethodGet, "b", ""))
require.Equal(t, http.StatusOK, rec.Code)
require.Contains(t, rec.Body.String(), ``)
missing, _ := newPublicAccessBlockTestServer(t, nil)
rec = httptest.NewRecorder()
missing.GetBucketNotificationConfigurationHandler(rec, notificationRequest(http.MethodGet, "gone", ""))
require.Equal(t, http.StatusNotFound, rec.Code)
require.Contains(t, rec.Body.String(), "NoSuchBucket")
}
func TestPutBucketNotificationConfigurationRejects(t *testing.T) {
queue := func(arn, inner string) string {
return `` + arn + `` + inner + ``
}
created := `s3:ObjectCreated:*`
cases := []struct {
name string
bucket string
body string
header string
status int
code string
message string
}{
{"unknown event", "b", queue("arn:aws:sqs:::raw", `s3:ObjectCreated:Whatever`), "", http.StatusBadRequest, "InvalidArgument", "s3:ObjectCreated:Whatever"},
{"two prefixes", "b", queue("arn:aws:sqs:::raw", created+``+
`prefixaprefixb`+
``), "", http.StatusBadRequest, "InvalidArgument", "more than one prefix"},
{"unknown target", "b", queue("arn:aws:sqs:::nope", created), "", http.StatusBadRequest, "InvalidArgument", "arn:aws:sqs:::nope"},
{"bucket not allowed", "c", queue("arn:aws:sqs:::orders", created), "", http.StatusBadRequest, "InvalidArgument", "arn:aws:sqs:::orders"},
{"disabled target", "b", queue("arn:aws:sqs:::off", created), "", http.StatusBadRequest, "InvalidArgument", "arn:aws:sqs:::off"},
{"bad arn", "b", queue("raw", created), "", http.StatusBadRequest, "InvalidArgument", "Invalid ARN"},
{"bad skip header", "b", queue("arn:aws:sqs:::raw", created), "yes", http.StatusBadRequest, "InvalidArgument", s3_constants.AmzSkipDestinationValidation},
{"skip does not bypass the registry", "b", queue("arn:aws:sqs:::nope", created), "true", http.StatusBadRequest, "InvalidArgument", "arn:aws:sqs:::nope"},
{"eventbridge", "b", ``, "", http.StatusNotImplemented, "NotImplemented", ""},
{"malformed", "b", ``, "", http.StatusBadRequest, "MalformedXML", ""},
{"unknown child", "b", ``, "", http.StatusBadRequest, "MalformedXML", ""},
{"wrong root", "b", ``, "", http.StatusBadRequest, "MalformedXML", ""},
{"no event", "b", queue("arn:aws:sqs:::raw", ""), "", http.StatusBadRequest, "MalformedXML", ""},
{"too large", "b", strings.Repeat(" ", s3notification.MaxConfigurationSize+1), "", http.StatusBadRequest, "EntityTooLarge", ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
s3a, filer := newNotificationTestServer(t, tc.bucket, nil)
req := notificationRequest(http.MethodPut, tc.bucket, tc.body)
if tc.header != "" {
req.Header.Set(s3_constants.AmzSkipDestinationValidation, tc.header)
}
rec := httptest.NewRecorder()
s3a.PutBucketNotificationConfigurationHandler(rec, req)
require.Equal(t, tc.status, rec.Code, rec.Body.String())
require.Contains(t, rec.Body.String(), ""+tc.code+"")
require.Contains(t, rec.Body.String(), tc.message)
require.Empty(t, filer.txnSeen, "a rejected configuration must not be stored")
})
}
}
func TestPutBucketNotificationConfigurationAcceptsSkipHeader(t *testing.T) {
for value, testEvents := range map[string]int{"true": 0, "false": 2, "TRUE": 0} {
s3a, filer := newNotificationTestServer(t, "orders-eu", nil)
req := notificationRequest(http.MethodPut, "orders-eu", testNotificationXML)
req.Header.Set(s3_constants.AmzSkipDestinationValidation, value)
rec := httptest.NewRecorder()
s3a.PutBucketNotificationConfigurationHandler(rec, req)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
require.Len(t, filer.txnSeen, 1)
require.Len(t, s3a.notificationPublisher.(*fakeNotificationPublisher).published(), testEvents, value)
}
}
func TestPutBucketNotificationConfigurationSendsTestEvents(t *testing.T) {
s3a, filer := newNotificationTestServer(t, "orders-eu", nil)
rec := httptest.NewRecorder()
s3a.PutBucketNotificationConfigurationHandler(rec, notificationRequest(http.MethodPut, "orders-eu", testNotificationXML))
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
require.Len(t, filer.txnSeen, 1)
messages := s3a.notificationPublisher.(*fakeNotificationPublisher).published()
var targets []string
for _, m := range messages {
targets = append(targets, m.Target)
require.Equal(t, "orders-eu/", string(m.Key))
require.True(t, s3notification.IsTestEvent(m.Value))
require.Equal(t, "orders-eu", m.Value.Fields[s3notification.ColumnBucketName].GetStringValue())
require.NotNil(t, m.Value.Fields[s3notification.ColumnEventTime].GetTimestampValue())
}
require.ElementsMatch(t, []string{"orders", "raw"}, targets)
}
func TestPutBucketNotificationConfigurationFailsWhenTheTestEventIsNotAcked(t *testing.T) {
s3a, filer := newNotificationTestServer(t, "orders-eu", nil)
s3a.notificationPublisher.(*fakeNotificationPublisher).stalled = true
rec := httptest.NewRecorder()
s3a.PutBucketNotificationConfigurationHandler(rec, notificationRequest(http.MethodPut, "orders-eu", testNotificationXML))
require.Equal(t, http.StatusBadRequest, rec.Code)
require.Contains(t, rec.Body.String(), "InvalidArgument")
require.Contains(t, rec.Body.String(), "arn:aws:sns:us-east-1:123456789012:orders, arn:aws:sqs:::raw")
require.Empty(t, filer.txnSeen, "a configuration whose destination did not ack must not be stored")
// Removing the configuration sends nothing, so nothing can fail it.
rec = httptest.NewRecorder()
s3a.PutBucketNotificationConfigurationHandler(rec, notificationRequest(http.MethodPut, "orders-eu", ``))
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
}
func TestPutBucketNotificationConfigurationWithoutTargets(t *testing.T) {
s3a, filer := newPublicAccessBlockTestServer(t, &filer_pb.Entry{Name: "b", IsDirectory: true})
rec := httptest.NewRecorder()
s3a.PutBucketNotificationConfigurationHandler(rec, notificationRequest(http.MethodPut, "b", testNotificationXML))
require.Equal(t, http.StatusBadRequest, rec.Code)
require.Contains(t, rec.Body.String(), "InvalidArgument")
require.Empty(t, filer.txnSeen)
}
func TestPutBucketNotificationConfigurationMissingBucket(t *testing.T) {
s3a, _ := newPublicAccessBlockTestServer(t, nil)
rec := httptest.NewRecorder()
s3a.PutBucketNotificationConfigurationHandler(rec, notificationRequest(http.MethodPut, "gone", testNotificationXML))
require.Equal(t, http.StatusNotFound, rec.Code)
require.Contains(t, rec.Body.String(), "NoSuchBucket")
}