package s3notification import ( "context" "encoding/json" "errors" "fmt" "io" "net" "net/http" "net/http/httptest" "strings" "sync" "testing" "github.com/seaweedfs/seaweedfs/weed/pb/schema_pb" "github.com/seaweedfs/seaweedfs/weed/util/netguard" ) // webhookServer records what reaches it and answers with status. type webhookServer struct { *httptest.Server mu sync.Mutex status int bodies []string auth []string received int } func newWebhookServer(t *testing.T) *webhookServer { t.Helper() s := &webhookServer{status: http.StatusOK} s.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { body, _ := io.ReadAll(r.Body) s.mu.Lock() s.received++ status := s.status if status/100 == 2 { s.bodies = append(s.bodies, string(body)) s.auth = append(s.auth, r.Header.Get("Authorization")) } s.mu.Unlock() w.WriteHeader(status) })) t.Cleanup(s.Close) return s } func (s *webhookServer) setStatus(status int) { s.mu.Lock() defer s.mu.Unlock() s.status = status } func (s *webhookServer) delivered() []string { s.mu.Lock() defer s.mu.Unlock() return append([]string(nil), s.bodies...) } func (s *webhookServer) attempts() int { s.mu.Lock() defer s.mu.Unlock() return s.received } func webhookTarget(endpoint string) *Target { return &Target{Name: "hook", Type: TargetTypeWebhook, Enabled: true, Endpoint: endpoint, BearerToken: "secret"} } // namedRecord is a PUT of the object name, or, for a name starting with // test-event, an s3:TestEvent with that request id. func namedRecord(name string) *schema_pb.RecordValue { if strings.HasPrefix(name, "test-event") { return TestEventRecord("photos", name, 1) } return (&Event{Name: EventObjectCreatedPut, Bucket: "photos", Key: name, LogTsNs: 1}).RecordValue("rule") } // bodyNames is the object keys of a {"Records":[...]} body, or the request id // of a test event. func bodyNames(t *testing.T, body string) []string { t.Helper() var test TestEvent if err := json.Unmarshal([]byte(body), &test); err == nil && test.Event == EventTest { return []string{test.RequestID} } var batch Records if err := json.Unmarshal([]byte(body), &batch); err != nil { t.Fatalf("body %s: %v", body, err) } var names []string for _, r := range batch.Records { names = append(names, r.S3.Object.Key) } return names } // renderRefusing renders as Render does, but refuses a record named unrenderable. func renderRefusing(records ...*schema_pb.RecordValue) ([]byte, error) { for _, r := range records { if r.Fields[ColumnObjectKey].GetStringValue() == "unrenderable" { return nil, errors.New("unrenderable record") } } return Render(records...) } func TestWebhookPostsATestEventOnItsOwnInOrder(t *testing.T) { server := newWebhookServer(t) hook := newWebhook(webhookTarget(server.URL)) err := hook.Send(context.Background(), []*schema_pb.RecordValue{ namedRecord("a"), namedRecord("test-event-1"), namedRecord("test-event-2"), namedRecord("b"), namedRecord("c"), }) if err != nil { t.Fatal(err) } var got []string for _, body := range server.delivered() { got = append(got, strings.Join(bodyNames(t, body), ",")) } if want := "a|test-event-1|test-event-2|b,c"; strings.Join(got, "|") != want { t.Fatalf("posted %v, want %s", got, want) } } func TestWebhookPostsOneBodyPerBatch(t *testing.T) { server := newWebhookServer(t) server.setStatus(http.StatusNoContent) hook := newWebhook(webhookTarget(server.URL + "/events")) if err := hook.Send(context.Background(), []*schema_pb.RecordValue{namedRecord("a"), namedRecord("b")}); err != nil { t.Fatal(err) } bodies := server.delivered() if len(bodies) != 1 { t.Fatalf("%d posts, want 1", len(bodies)) } if got := strings.Join(bodyNames(t, bodies[0]), ","); got != "a,b" { t.Fatalf("body %s carries %s, want a,b", bodies[0], got) } server.mu.Lock() defer server.mu.Unlock() if server.auth[0] != "Bearer secret" { t.Fatalf("authorization %q", server.auth[0]) } } func TestWebhookNamesTheRecordsItCannotRenderAndPostsNothing(t *testing.T) { server := newWebhookServer(t) hook := newWebhook(webhookTarget(server.URL)) hook.render = renderRefusing err := hook.Send(context.Background(), []*schema_pb.RecordValue{ namedRecord("a"), namedRecord("test-event"), namedRecord("b"), namedRecord("unrenderable"), namedRecord("c"), }) var unrenderable *unrenderableError if !errors.As(err, &unrenderable) || fmt.Sprint(unrenderable.indexes) != "[3]" { t.Fatalf("send with an unrenderable record: %v", err) } if n := server.attempts(); n != 0 { t.Fatalf("%d posts before the batch was known to render", n) } } func TestWebhookTreatsAnythingButTwoHundredsAsFailed(t *testing.T) { server := newWebhookServer(t) hook := newWebhook(webhookTarget(server.URL)) for _, status := range []int{http.StatusInternalServerError, http.StatusUnauthorized, http.StatusBadRequest} { server.setStatus(status) if err := hook.Send(context.Background(), []*schema_pb.RecordValue{namedRecord("x")}); err == nil || !strings.Contains(err.Error(), http.StatusText(status)) { t.Fatalf("status %d: %v", status, err) } } } func TestWebhookErrorsCarryNoEndpointSecrets(t *testing.T) { original := netguard.LookupIPAddr t.Cleanup(func() { netguard.LookupIPAddr = original }) netguard.LookupIPAddr = func(ctx context.Context, host string) ([]net.IPAddr, error) { return []net.IPAddr{{IP: net.ParseIP("169.254.10.1")}}, nil } for _, endpoint := range []string{ "http://user:hunter2@169.254.169.254/hook?token=sekrit", "http://user:hunter2@rebound.example.com:8080/hook?token=sekrit", "http://user:hunter2@[fe80::1]:8080/hook?token=sekrit#frag", } { err := newWebhook(webhookTarget(endpoint)).Send(context.Background(), []*schema_pb.RecordValue{namedRecord("a")}) if err == nil { t.Fatalf("%s: sent", endpoint) } for _, secret := range []string{"hunter2", "sekrit", "user"} { if strings.Contains(err.Error(), secret) { t.Errorf("error %q carries %q", err, secret) } } if !strings.Contains(err.Error(), "/hook") { t.Errorf("error %q no longer names the endpoint", err) } } } func TestWebhookFollowsOnlyRedirectsThatKeepThePost(t *testing.T) { for _, code := range []int{http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect} { var mu sync.Mutex var landed []string server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/old" { http.Redirect(w, r, "/new", code) return } body, _ := io.ReadAll(r.Body) mu.Lock() landed = append(landed, r.Method+" "+string(body)) mu.Unlock() })) err := newWebhook(webhookTarget(server.URL+"/old")).Send(context.Background(), []*schema_pb.RecordValue{namedRecord("a")}) server.Close() mu.Lock() got := strings.Join(landed, "|") mu.Unlock() if method, body, ok := strings.Cut(got, " "); ok && method == "POST" && strings.HasPrefix(body, "{") { got = "POST " + strings.Join(bodyNames(t, body), ",") } if code == http.StatusTemporaryRedirect || code == http.StatusPermanentRedirect { if err != nil || got != "POST a" { t.Errorf("%d: %v, landed %q, want the POST resent", code, err, got) } continue } if err == nil || got != "" { t.Errorf("%d: %v, landed %q, want a failure and nothing sent", code, err, got) } } } func TestWebhookFollowsOnlySameHostRedirects(t *testing.T) { target := newWebhookServer(t) redirector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/moved" { http.Redirect(w, r, "/here", http.StatusTemporaryRedirect) return } if r.URL.Path == "/here" { w.WriteHeader(http.StatusOK) return } http.Redirect(w, r, target.URL+"/stolen", http.StatusTemporaryRedirect) })) t.Cleanup(redirector.Close) if err := newWebhook(webhookTarget(redirector.URL+"/moved")).Send(context.Background(), []*schema_pb.RecordValue{namedRecord("x")}); err != nil { t.Fatalf("same-host redirect: %v", err) } err := newWebhook(webhookTarget(redirector.URL+"/elsewhere")).Send(context.Background(), []*schema_pb.RecordValue{namedRecord("x")}) if err == nil || !strings.Contains(err.Error(), "refusing redirect") { t.Fatalf("cross-host redirect: %v", err) } if n := target.attempts(); n != 0 { t.Fatalf("the other host got %d requests", n) } } func TestWebhookRefusesMetadataAndLinkLocalAddresses(t *testing.T) { original := netguard.LookupIPAddr t.Cleanup(func() { netguard.LookupIPAddr = original }) netguard.LookupIPAddr = func(ctx context.Context, host string) ([]net.IPAddr, error) { return []net.IPAddr{{IP: net.ParseIP("169.254.10.1")}}, nil } for _, endpoint := range []string{ "http://169.254.169.254/latest", "http://[fe80::1]:8080/", "http://metadata.google.internal/", "http://rebound.example.com/hook", } { err := newWebhook(webhookTarget(endpoint)).Send(context.Background(), []*schema_pb.RecordValue{namedRecord("x")}) if err == nil || !(strings.Contains(err.Error(), "metadata") || strings.Contains(err.Error(), "link-local")) { t.Errorf("%s: %v", endpoint, err) } } }