diff --git a/weed/admin/dash/notification_webhooks.go b/weed/admin/dash/notification_webhooks.go new file mode 100644 index 0000000000..8796410a55 --- /dev/null +++ b/weed/admin/dash/notification_webhooks.go @@ -0,0 +1,192 @@ +package dash + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "net/http" + "sync" + + "github.com/gorilla/mux" + "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/notification/webhook" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" +) + +// NotificationWebhook is a stored webhook target as shown to the browser: +// the bearer token never leaves the server. +type NotificationWebhook struct { + webhook.ManagedTarget + HasBearerToken bool `json:"has_bearer_token"` +} + +type NotificationWebhooksData struct { + Webhooks []NotificationWebhook `json:"webhooks"` + ConfigPath string `json:"config_path"` +} + +// NotificationWebhookRequest creates or replaces a target. An empty +// bearer_token keeps the stored one unless clear_bearer_token is set. +type NotificationWebhookRequest struct { + webhook.ManagedTarget + ClearBearerToken bool `json:"clear_bearer_token"` +} + +var notificationWebhooksMu sync.Mutex + +func (s *AdminServer) readNotificationWebhooks(ctx context.Context) (*webhook.ManagedConfig, error) { + var conf *webhook.ManagedConfig + err := s.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error { + var buf bytes.Buffer + err := filer.ReadEntry(s.masterClient, client, filer.DirectoryEtcSeaweedFS, filer.NotificationWebhooksConfName, &buf) + if err != nil && !errors.Is(err, filer_pb.ErrNotFound) { + return err + } + conf, err = webhook.ParseManagedConfig(buf.Bytes()) + return err + }) + return conf, err +} + +func (s *AdminServer) saveNotificationWebhooks(ctx context.Context, conf *webhook.ManagedConfig) error { + if err := conf.Validate(); err != nil { + return err + } + content, err := json.MarshalIndent(conf, "", " ") + if err != nil { + return err + } + return s.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error { + return filer.SaveInsideFiler(ctx, client, filer.DirectoryEtcSeaweedFS, filer.NotificationWebhooksConfName, content) + }) +} + +func (s *AdminServer) GetNotificationWebhooks(ctx context.Context) (*NotificationWebhooksData, error) { + conf, err := s.readNotificationWebhooks(ctx) + if err != nil { + return nil, err + } + data := &NotificationWebhooksData{ + Webhooks: make([]NotificationWebhook, 0, len(conf.Targets)), + ConfigPath: filer.NotificationWebhooksConfPath, + } + for _, t := range conf.Targets { + hasToken := t.BearerToken != "" + t.BearerToken = "" + data.Webhooks = append(data.Webhooks, NotificationWebhook{ManagedTarget: t, HasBearerToken: hasToken}) + } + return data, nil +} + +func (s *AdminServer) GetNotificationWebhooksAPI(w http.ResponseWriter, r *http.Request) { + data, err := s.GetNotificationWebhooks(r.Context()) + if err != nil { + writeJSONError(w, http.StatusInternalServerError, "Failed to read webhook targets: "+err.Error()) + return + } + writeJSON(w, http.StatusOK, data) +} + +func (s *AdminServer) CreateNotificationWebhookAPI(w http.ResponseWriter, r *http.Request) { + s.putNotificationWebhook(w, r, "", true) +} + +func (s *AdminServer) UpdateNotificationWebhookAPI(w http.ResponseWriter, r *http.Request) { + s.putNotificationWebhook(w, r, mux.Vars(r)["name"], false) +} + +func (s *AdminServer) putNotificationWebhook(w http.ResponseWriter, r *http.Request, name string, create bool) { + if !requireSessionCSRFToken(w, r) { + return + } + var req NotificationWebhookRequest + if err := decodeJSONBody(newJSONMaxReader(w, r), &req); err != nil { + writeJSONError(w, http.StatusBadRequest, "Invalid request: "+err.Error()) + return + } + if create { + name = req.Name + } else if req.Name != "" && req.Name != name { + writeJSONError(w, http.StatusBadRequest, "Webhook target name cannot be changed") + return + } + target := req.ManagedTarget + target.Name = name + + notificationWebhooksMu.Lock() + defer notificationWebhooksMu.Unlock() + conf, err := s.readNotificationWebhooks(r.Context()) + if err != nil { + writeJSONError(w, http.StatusInternalServerError, "Failed to read webhook targets: "+err.Error()) + return + } + index := -1 + for i := range conf.Targets { + if conf.Targets[i].Name == name { + index = i + } + } + switch { + case create && index >= 0: + writeJSONError(w, http.StatusConflict, "Webhook target already exists") + return + case !create && index < 0: + writeJSONError(w, http.StatusNotFound, "Webhook target not found") + return + } + if index >= 0 && target.BearerToken == "" && !req.ClearBearerToken { + target.BearerToken = conf.Targets[index].BearerToken + } + if err := target.Validate(); err != nil { + writeJSONError(w, http.StatusBadRequest, err.Error()) + return + } + if index >= 0 { + conf.Targets[index] = target + } else { + conf.Targets = append(conf.Targets, target) + } + if err := s.saveNotificationWebhooks(r.Context(), conf); err != nil { + writeJSONError(w, http.StatusInternalServerError, "Failed to save webhook targets: "+err.Error()) + return + } + status := http.StatusOK + if create { + status = http.StatusCreated + } + hasToken := target.BearerToken != "" + target.BearerToken = "" + writeJSON(w, status, NotificationWebhook{ManagedTarget: target, HasBearerToken: hasToken}) +} + +func (s *AdminServer) DeleteNotificationWebhookAPI(w http.ResponseWriter, r *http.Request) { + if !requireSessionCSRFToken(w, r) { + return + } + name := mux.Vars(r)["name"] + + notificationWebhooksMu.Lock() + defer notificationWebhooksMu.Unlock() + conf, err := s.readNotificationWebhooks(r.Context()) + if err != nil { + writeJSONError(w, http.StatusInternalServerError, "Failed to read webhook targets: "+err.Error()) + return + } + kept := conf.Targets[:0] + for _, t := range conf.Targets { + if t.Name != name { + kept = append(kept, t) + } + } + if len(kept) == len(conf.Targets) { + writeJSONError(w, http.StatusNotFound, "Webhook target not found") + return + } + conf.Targets = kept + if err := s.saveNotificationWebhooks(r.Context(), conf); err != nil { + writeJSONError(w, http.StatusInternalServerError, "Failed to save webhook targets: "+err.Error()) + return + } + writeJSON(w, http.StatusOK, map[string]string{"message": "Webhook target deleted"}) +} diff --git a/weed/admin/handlers/admin_handlers.go b/weed/admin/handlers/admin_handlers.go index a9807185c1..b3a33cd638 100644 --- a/weed/admin/handlers/admin_handlers.go +++ b/weed/admin/handlers/admin_handlers.go @@ -126,6 +126,7 @@ func (h *AdminHandlers) registerUIRoutes(r *mux.Router) { // File browser routes r.HandleFunc("/files", h.fileBrowserHandlers.ShowFileBrowser).Methods(http.MethodGet) + r.HandleFunc("/notifications/webhooks", h.ShowNotificationWebhooks).Methods(http.MethodGet) // Cluster management routes r.HandleFunc("/cluster/masters", h.clusterHandlers.ShowClusterMasters).Methods(http.MethodGet) @@ -275,6 +276,12 @@ func (h *AdminHandlers) registerAPIRoutes(api *mux.Router, enforceWrite bool) { filesApi.HandleFunc("/metadata", h.fileBrowserHandlers.ExportMetadata).Methods(http.MethodGet) filesApi.HandleFunc("/list-folders", h.fileBrowserHandlers.ListFolders).Methods(http.MethodGet) + webhooksApi := api.PathPrefix("/notifications/webhooks").Subrouter() + webhooksApi.HandleFunc("", h.adminServer.GetNotificationWebhooksAPI).Methods(http.MethodGet) + webhooksApi.Handle("", wrapWrite(h.adminServer.CreateNotificationWebhookAPI)).Methods(http.MethodPost) + webhooksApi.Handle("/{name}", wrapWrite(h.adminServer.UpdateNotificationWebhookAPI)).Methods(http.MethodPut) + webhooksApi.Handle("/{name}", wrapWrite(h.adminServer.DeleteNotificationWebhookAPI)).Methods(http.MethodDelete) + volumeApi := api.PathPrefix("/volumes").Subrouter() volumeApi.HandleFunc("/export", h.clusterHandlers.ExportClusterVolumes).Methods(http.MethodGet) volumeApi.Handle("/{id}/{server}/vacuum", wrapWrite(h.clusterHandlers.VacuumVolume)).Methods(http.MethodPost) @@ -386,6 +393,24 @@ func (h *AdminHandlers) ShowS3TablesBuckets(w http.ResponseWriter, r *http.Reque } } +// ShowNotificationWebhooks renders the filer webhook targets page +func (h *AdminHandlers) ShowNotificationWebhooks(w http.ResponseWriter, r *http.Request) { + username := h.getUsername(r) + data, err := h.adminServer.GetNotificationWebhooks(r.Context()) + if err != nil { + writeJSONError(w, http.StatusInternalServerError, "Failed to get webhook targets: "+err.Error()) + return + } + + w.Header().Set("Content-Type", "text/html") + component := app.NotificationWebhooks(*data) + viewCtx := layout.NewViewContext(r, username, dash.CSRFTokenFromContext(r.Context())) + layoutComponent := layout.Layout(viewCtx, component) + if err := layoutComponent.Render(r.Context(), w); err != nil { + writeJSONError(w, http.StatusInternalServerError, "Failed to render template: "+err.Error()) + } +} + // ShowS3VectorsBuckets renders the vector buckets page func (h *AdminHandlers) ShowS3VectorsBuckets(w http.ResponseWriter, r *http.Request) { username := h.getUsername(r) diff --git a/weed/admin/handlers/admin_handlers_routes_test.go b/weed/admin/handlers/admin_handlers_routes_test.go index 1cc0728cad..96c133f22e 100644 --- a/weed/admin/handlers/admin_handlers_routes_test.go +++ b/weed/admin/handlers/admin_handlers_routes_test.go @@ -62,6 +62,20 @@ func TestSetupRoutes_RegistersBucketLifecycleAPI_WithAuth(t *testing.T) { assertHasRoute(t, router, http.MethodDelete, "/api/s3/buckets/example/lifecycle") } +func TestSetupRoutes_RegistersNotificationWebhooks(t *testing.T) { + for _, authRequired := range []bool{false, true} { + router := mux.NewRouter() + + newRouteTestAdminHandlers().SetupRoutes(router, authRequired, "admin", "password", "", "", true) + + assertHasRoute(t, router, http.MethodGet, "/notifications/webhooks") + assertHasRoute(t, router, http.MethodGet, "/api/notifications/webhooks") + assertHasRoute(t, router, http.MethodPost, "/api/notifications/webhooks") + assertHasRoute(t, router, http.MethodPut, "/api/notifications/webhooks/example") + assertHasRoute(t, router, http.MethodDelete, "/api/notifications/webhooks/example") + } +} + func TestSetupRoutes_RegistersBucketPolicyAPI_NoAuth(t *testing.T) { router := mux.NewRouter() diff --git a/weed/admin/view/app/notification_webhooks.templ b/weed/admin/view/app/notification_webhooks.templ new file mode 100644 index 0000000000..9460de5346 --- /dev/null +++ b/weed/admin/view/app/notification_webhooks.templ @@ -0,0 +1,283 @@ +package app + +import ( + "strings" + "github.com/seaweedfs/seaweedfs/weed/admin/dash" +) + +templ NotificationWebhooks(data dash.NotificationWebhooksData) { +
Send filer events to HTTP endpoints, filtered by path and event type
+{ data.ConfigPath } and apply to all filers without a restart.
+ No webhook targets yet.
+| Name | +Status | +Endpoint | +Events | +Path Prefixes | +Token | +Actions | +
|---|---|---|---|---|---|---|
| { hook.Name } | ++ if hook.Enabled { + Enabled + } else { + Disabled + } + | +{ hook.Endpoint } |
+ { webhookFilterLabel(hook.EventTypes) } | +{ webhookFilterLabel(hook.PathPrefixes) } | ++ if hook.HasBearerToken { + + } else { + - + } + | +
+
+
+
+
+ |
+
Send filer events to HTTP endpoints, filtered by path and event type
")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var2 string
+ templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(data.ConfigPath)
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/notification_webhooks.templ`, Line: 24, Col: 70}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, " and apply to all filers without a restart.No webhook targets yet.
| Name | Status | Endpoint | Events | Path Prefixes | Token | Actions |
|---|---|---|---|---|---|---|
| ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var3 string + templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(hook.Name) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/notification_webhooks.templ`, Line: 51, Col: 63} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, " | ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if hook.Enabled { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "Enabled") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } else { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "Disabled") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, " | ")
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ var templ_7745c5c3_Var4 string
+ templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(hook.Endpoint)
+ if templ_7745c5c3_Err != nil {
+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/notification_webhooks.templ`, Line: 59, Col: 65}
+ }
+ _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
+ if templ_7745c5c3_Err != nil {
+ return templ_7745c5c3_Err
+ }
+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, " | ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var5 string + templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(webhookFilterLabel(hook.EventTypes)) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/notification_webhooks.templ`, Line: 60, Col: 81} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, " | ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var6 string + templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(webhookFilterLabel(hook.PathPrefixes)) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/notification_webhooks.templ`, Line: 61, Col: 83} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, " | ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if hook.HasBearerToken { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } else { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "-") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, " |