Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat: add inbound webhook support (#909) (#2182)
Barend4d1fabbda857
diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.goindex 2c2f2bc43..ed171db17 100644--- a/backend/internal/bootstrap/router_bootstrap.go+++ b/backend/internal/bootstrap/router_bootstrap.go@@ -13,6 +13,7 @@ import ("github.com/getarcaneapp/arcane/backend/internal/api""github.com/getarcaneapp/arcane/backend/internal/config""github.com/getarcaneapp/arcane/backend/internal/huma"+ "github.com/getarcaneapp/arcane/backend/internal/huma/handlers""github.com/getarcaneapp/arcane/backend/internal/middleware""github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge""github.com/getarcaneapp/arcane/backend/pkg/utils/cookie"@@ -114,6 +115,9 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *Services)return env.ApiUrl, env.AccessToken, env.Enabled, nil}+ // Register public webhook trigger endpoint before auth middleware (token in URL is the sole auth)+ handlers.RegisterWebhookTrigger(apiGroup, appServices.Webhook) //nolint:contextcheck+apiGroup.Use(middleware.NewEnvProxyMiddlewareWithParam(types.LOCAL_DOCKER_ENVIRONMENT_ID,"id",@@ -155,6 +159,7 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *Services)SystemUpgrade: appServices.SystemUpgrade,GitRepository: appServices.GitRepository,GitOpsSync: appServices.GitOpsSync,+ Webhook: appServices.Webhook,Vulnerability: appServices.Vulnerability,Dashboard: appServices.Dashboard,Config: cfg,diff --git a/backend/internal/bootstrap/services_bootstrap.go b/backend/internal/bootstrap/services_bootstrap.goindex ea6d45eb6..9d51e6dd4 100644--- a/backend/internal/bootstrap/services_bootstrap.go+++ b/backend/internal/bootstrap/services_bootstrap.go@@ -45,6 +45,7 @@ type Services struct {ApiKey *services.ApiKeyServiceGitRepository *services.GitRepositoryServiceGitOpsSync *services.GitOpsSyncService+ Webhook *services.WebhookServiceFont *services.FontServiceVulnerability *services.VulnerabilityServiceDashboard *services.DashboardService@@ -95,6 +96,7 @@ func initializeServices(ctx context.Context, db *database.DB, cfg *config.Configsvcs.SystemUpgrade = services.NewSystemUpgradeService(svcs.Docker, svcs.Version, svcs.Event, svcs.Settings)svcs.Updater = services.NewUpdaterService(db, svcs.Settings, svcs.Docker, svcs.Project, svcs.ImageUpdate, svcs.ContainerRegistry, svcs.Event, svcs.Image, svcs.Notification, svcs.SystemUpgrade)svcs.GitOpsSync = services.NewGitOpsSyncService(db, svcs.GitRepository, svcs.Project, svcs.Event, svcs.Settings)+ svcs.Webhook = services.NewWebhookService(db, svcs.Container, svcs.Updater, svcs.Project, svcs.GitOpsSync, svcs.Event)return svcs, dockerClient, nil}diff --git a/backend/internal/huma/handlers/webhooks.go b/backend/internal/huma/handlers/webhooks.gonew file mode 100644index 000000000..ddf922ef0--- /dev/null+++ b/backend/internal/huma/handlers/webhooks.go@@ -0,0 +1,273 @@+package handlers++import (+ "context"+ "errors"+ "net/http"++ "github.com/danielgtaylor/huma/v2"+ humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"+ "github.com/getarcaneapp/arcane/backend/internal/models"+ "github.com/getarcaneapp/arcane/backend/internal/services"+ "github.com/getarcaneapp/arcane/types/base"+ "github.com/getarcaneapp/arcane/types/webhook"+ "github.com/gin-gonic/gin"+)++type WebhookHandler struct {+ webhookService *services.WebhookService+}++// --- Input/Output types ---++type ListWebhooksInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+}++type ListWebhooksOutput struct {+ Body base.ApiResponse[[]webhook.Summary]+}++type CreateWebhookInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ Body *webhook.CreateInput `required:"true"`+}++type CreateWebhookOutput struct {+ Body base.ApiResponse[webhook.Created]+}++type DeleteWebhookInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ WebhookID string `path:"webhookId" doc:"Webhook ID"`+}++type DeleteWebhookOutput struct {+ Body base.ApiResponse[any]+}++type UpdateWebhookInput struct {+ EnvironmentID string `path:"id" doc:"Environment ID"`+ WebhookID string `path:"webhookId" doc:"Webhook ID"`+ Body *webhook.UpdateInput `required:"true"`+}++type UpdateWebhookOutput struct {+ Body base.ApiResponse[any]+}++// RegisterWebhooks registers the authenticated CRUD routes for webhook management.+func RegisterWebhooks(api huma.API, webhookService *services.WebhookService) {+ h := &WebhookHandler{webhookService: webhookService}++ huma.Register(api, huma.Operation{+ OperationID: "list-webhooks",+ Method: http.MethodGet,+ Path: "/environments/{id}/webhooks",+ Summary: "List webhooks",+ Description: "List all webhooks configured for this environment",+ Tags: []string{"Webhooks"},+ Security: []map[string][]string{+ {"BearerAuth": {}},+ {"ApiKeyAuth": {}},+ },+ }, h.ListWebhooks)++ huma.Register(api, huma.Operation{+ OperationID: "create-webhook",+ Method: http.MethodPost,+ Path: "/environments/{id}/webhooks",+ Summary: "Create webhook",+ Description: "Create a webhook that triggers a container or stack update. The token is only returned once.",+ Tags: []string{"Webhooks"},+ Security: []map[string][]string{+ {"BearerAuth": {}},+ {"ApiKeyAuth": {}},+ },+ }, h.CreateWebhook)++ huma.Register(api, huma.Operation{+ OperationID: "update-webhook",+ Method: http.MethodPatch,+ Path: "/environments/{id}/webhooks/{webhookId}",+ Summary: "Update webhook",+ Description: "Update a webhook's enabled state",+ Tags: []string{"Webhooks"},+ Security: []map[string][]string{+ {"BearerAuth": {}},+ {"ApiKeyAuth": {}},+ },+ }, h.UpdateWebhook)++ huma.Register(api, huma.Operation{+ OperationID: "delete-webhook",+ Method: http.MethodDelete,+ Path: "/environments/{id}/webhooks/{webhookId}",+ Summary: "Delete webhook",+ Description: "Delete a webhook by ID",+ Tags: []string{"Webhooks"},+ Security: []map[string][]string{+ {"BearerAuth": {}},+ {"ApiKeyAuth": {}},+ },+ }, h.DeleteWebhook)+}++// RegisterWebhookTrigger registers the public (unauthenticated) trigger endpoint on the+// raw Gin router, bypassing the Huma auth middleware. The token in the URL is the sole+// authentication mechanism.+//+// Security note: tokens appear in server access logs and browser history. Ensure access+// logs are appropriately protected, and consider rate-limiting this endpoint at the+// reverse-proxy level.+func RegisterWebhookTrigger(router *gin.RouterGroup, webhookService *services.WebhookService) {+ router.POST("/webhooks/trigger/:token", func(c *gin.Context) {+ if webhookService == nil {+ c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "service not available"})+ return+ }++ token := c.Param("token")+ result, err := webhookService.TriggerByToken(c.Request.Context(), token)+ if err != nil {+ status := http.StatusInternalServerError+ if errors.Is(err, services.ErrWebhookNotFound) || errors.Is(err, services.ErrWebhookInvalid) {+ status = http.StatusNotFound+ } else if errors.Is(err, services.ErrWebhookDisabled) {+ status = http.StatusForbidden+ }+ msg := err.Error()+ if status == http.StatusInternalServerError {+ msg = "internal server error"+ }+ c.JSON(status, gin.H{"success": false, "error": msg})+ return+ }++ c.JSON(http.StatusOK, gin.H{"success": true, "data": result})+ })+}++// ListWebhooks returns all webhooks for an environment (tokens are masked).+func (h *WebhookHandler) ListWebhooks(ctx context.Context, input *ListWebhooksInput) (*ListWebhooksOutput, error) {+ if h.webhookService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }++ webhooks, err := h.webhookService.ListWebhookSummaries(ctx, input.EnvironmentID)+ if err != nil {+ return nil, huma.Error500InternalServerError("failed to list webhooks")+ }++ return &ListWebhooksOutput{+ Body: base.ApiResponse[[]webhook.Summary]{+ Success: true,+ Data: webhooks,+ },+ }, nil+}++// CreateWebhook creates a new webhook and returns the raw token (shown once only).+func (h *WebhookHandler) CreateWebhook(ctx context.Context, input *CreateWebhookInput) (*CreateWebhookOutput, error) {+ if h.webhookService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if input.Body == nil {+ return nil, huma.Error400BadRequest("request body is required")+ }++ actor := models.User{}+ if currentUser, exists := humamw.GetCurrentUserFromContext(ctx); exists && currentUser != nil {+ actor = *currentUser+ }++ wh, rawToken, err := h.webhookService.CreateWebhook(+ ctx,+ input.Body.Name,+ input.Body.TargetType,+ input.Body.ActionType,+ input.Body.TargetID,+ input.EnvironmentID,+ actor,+ )+ if err != nil {+ if errors.Is(err, services.ErrWebhookInvalidType) {+ return nil, huma.Error400BadRequest("invalid target type, must be 'container', 'project', 'updater', or 'gitops'")+ }+ if errors.Is(err, services.ErrWebhookMissingTarget) {+ return nil, huma.Error400BadRequest("target ID is required for container, project, and gitops webhook types")+ }+ if errors.Is(err, services.ErrWebhookInvalidAction) {+ return nil, huma.Error400BadRequest("invalid action type for target type")+ }+ return nil, huma.Error500InternalServerError("failed to create webhook")+ }++ return &CreateWebhookOutput{+ Body: base.ApiResponse[webhook.Created]{+ Success: true,+ Data: webhook.Created{+ ID: wh.ID,+ Name: wh.Name,+ Token: rawToken,+ TargetType: wh.TargetType,+ ActionType: wh.ActionType,+ TargetID: wh.TargetID,+ CreatedAt: wh.CreatedAt,+ },+ },+ }, nil+}++// UpdateWebhook updates a webhook's enabled state.+func (h *WebhookHandler) UpdateWebhook(ctx context.Context, input *UpdateWebhookInput) (*UpdateWebhookOutput, error) {+ if h.webhookService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }+ if input.Body == nil {+ return nil, huma.Error400BadRequest("request body is required")+ }++ actor := models.User{}+ if currentUser, exists := humamw.GetCurrentUserFromContext(ctx); exists && currentUser != nil {+ actor = *currentUser+ }++ wh, err := h.webhookService.UpdateWebhook(ctx, input.WebhookID, input.EnvironmentID, input.Body.Enabled, actor)+ if err != nil {+ if errors.Is(err, services.ErrWebhookNotFound) {+ return nil, huma.Error404NotFound("webhook not found")+ }+ return nil, huma.Error500InternalServerError("failed to update webhook")+ }++ _ = wh // updated record available if needed in future+ return &UpdateWebhookOutput{+ Body: base.ApiResponse[any]{Success: true},+ }, nil+}++// DeleteWebhook removes a webhook.+func (h *WebhookHandler) DeleteWebhook(ctx context.Context, input *DeleteWebhookInput) (*DeleteWebhookOutput, error) {+ if h.webhookService == nil {+ return nil, huma.Error500InternalServerError("service not available")+ }++ actor := models.User{}+ if currentUser, exists := humamw.GetCurrentUserFromContext(ctx); exists && currentUser != nil {+ actor = *currentUser+ }++ if err := h.webhookService.DeleteWebhook(ctx, input.WebhookID, input.EnvironmentID, actor); err != nil {+ if errors.Is(err, services.ErrWebhookNotFound) {+ return nil, huma.Error404NotFound("webhook not found")+ }+ return nil, huma.Error500InternalServerError("failed to delete webhook")+ }++ return &DeleteWebhookOutput{+ Body: base.ApiResponse[any]{+ Success: true,+ },+ }, nil+}diff --git a/backend/internal/huma/huma.go b/backend/internal/huma/huma.goindex 848422ec7..b1a19c544 100644--- a/backend/internal/huma/huma.go+++ b/backend/internal/huma/huma.go@@ -170,6 +170,7 @@ type Services struct {SystemUpgrade *services.SystemUpgradeServiceGitRepository *services.GitRepositoryServiceGitOpsSync *services.GitOpsSyncService+ Webhook *services.WebhookServiceVulnerability *services.VulnerabilityServiceDashboard *services.DashboardServiceConfig *config.Config@@ -334,6 +335,7 @@ func registerHandlers(api huma.API, svc *Services) {var systemUpgradeSvc *services.SystemUpgradeServicevar gitRepositorySvc *services.GitRepositoryServicevar gitOpsSyncSvc *services.GitOpsSyncService+ var webhookSvc *services.WebhookServicevar vulnerabilitySvc *services.VulnerabilityServicevar dashboardSvc *services.DashboardServicevar cfg *config.Config@@ -372,6 +374,7 @@ func registerHandlers(api huma.API, svc *Services) {systemUpgradeSvc = svc.SystemUpgradegitRepositorySvc = svc.GitRepositorygitOpsSyncSvc = svc.GitOpsSync+ webhookSvc = svc.WebhookvulnerabilitySvc = svc.VulnerabilitydashboardSvc = svc.Dashboardcfg = svc.Config@@ -405,6 +408,7 @@ func registerHandlers(api huma.API, svc *Services) {handlers.RegisterSystem(api, dockerSvc, systemSvc, systemUpgradeSvc, cfg)handlers.RegisterGitRepositories(api, gitRepositorySvc)handlers.RegisterGitOpsSyncs(api, gitOpsSyncSvc)+ handlers.RegisterWebhooks(api, webhookSvc)handlers.RegisterVulnerability(api, vulnerabilitySvc)handlers.RegisterDashboard(api, dashboardSvc)}diff --git a/backend/internal/models/event.go b/backend/internal/models/event.goindex b204e5128..78e0dc815 100644--- a/backend/internal/models/event.go+++ b/backend/internal/models/event.go@@ -79,6 +79,11 @@ const (EventTypeEnvironmentDelete EventType = "environment.delete"EventTypeEnvironmentApiKeyRegenerated EventType = "environment.api_key.regenerated"+ EventTypeWebhookCreate EventType = "webhook.create"+ EventTypeWebhookUpdate EventType = "webhook.update"+ EventTypeWebhookDelete EventType = "webhook.delete"+ EventTypeWebhookTrigger EventType = "webhook.trigger"+// Event severitiesEventSeverityInfo EventSeverity = "info"EventSeverityWarning EventSeverity = "warning"diff --git a/backend/internal/models/settings.go b/backend/internal/models/settings.goindex fe3febe7e..1bdf6b848 100644--- a/backend/internal/models/settings.go+++ b/backend/internal/models/settings.go@@ -159,6 +159,9 @@ type Settings struct {// API Keys category (admin management page - no actual settings)ApiKeysCategoryPlaceholder SettingVariable `key:"apiKeysCategory,internal" meta:"label=API Keys;type=internal;keywords=api,keys,tokens,authentication,access,programmatic,integration;category=apikeys;description=Manage API keys for programmatic access" catmeta:"id=apikeys;title=API Keys;icon=apikey;url=/settings/api-keys;description=Create and manage API keys for programmatic access to Arcane"`+ // Webhooks category (management page - no actual settings)+ WebhooksCategoryPlaceholder SettingVariable `key:"webhooksCategory,internal" meta:"label=Webhooks;type=internal;keywords=webhooks,trigger,inbound,http,container,stack,gitops,updater,automation,ci,cd;category=webhooks;description=Manage inbound webhooks to trigger updates" catmeta:"id=webhooks;title=Webhooks;icon=globe;url=/settings/webhooks;description=Create and manage inbound webhooks to trigger container, stack, or GitOps updates"`+// Timeout categoryDockerAPITimeout SettingVariable `key:"dockerApiTimeout,envOverride" meta:"label=Docker API Timeout;type=number;keywords=docker,api,timeout,seconds,list,operations;category=timeouts;description=Timeout for Docker list operations in seconds (default: 30)" catmeta:"id=timeouts;title=Timeouts;icon=clock;url=/settings/timeouts;description=Configure operation timeouts for slow networks or hardware"`DockerImagePullTimeout SettingVariable `key:"dockerImagePullTimeout,envOverride" meta:"label=Docker Image Pull Timeout;type=number;keywords=docker,image,pull,timeout,seconds,download;category=timeouts;description=Timeout for Docker image pulls in seconds (default: 600 = 10 minutes)"`diff --git a/backend/internal/models/webhook.go b/backend/internal/models/webhook.gonew file mode 100644index 000000000..5275dde02--- /dev/null+++ b/backend/internal/models/webhook.go@@ -0,0 +1,38 @@+package models++import "time"++const (+ WebhookTargetTypeContainer = "container"+ WebhookTargetTypeProject = "project"+ WebhookTargetTypeUpdater = "updater"+ WebhookTargetTypeGitOps = "gitops"++ WebhookActionTypeUpdate = "update"+ WebhookActionTypeStart = "start"+ WebhookActionTypeStop = "stop"+ WebhookActionTypeRestart = "restart"+ WebhookActionTypeRedeploy = "redeploy"+ WebhookActionTypeUp = "up"+ WebhookActionTypeDown = "down"+ WebhookActionTypeRun = "run"+ WebhookActionTypeSync = "sync"+)++type Webhook struct {+ Name string `json:"name" gorm:"column:name;not null"`+ TokenHash string `json:"-" gorm:"column:token_hash;not null;uniqueIndex"`+ TokenPrefix string `json:"tokenPrefix" gorm:"column:token_prefix;not null"`+ TargetType string `json:"targetType" gorm:"column:target_type;not null"`+ ActionType string `json:"actionType" gorm:"column:action_type;not null;default:''"`+ TargetID string `json:"targetId" gorm:"column:target_id;not null"`+ TargetRef string `json:"-" gorm:"column:target_ref;not null;default:''"`+ EnvironmentID string `json:"environmentId" gorm:"column:environment_id;not null;default:''"`+ Enabled bool `json:"enabled" gorm:"column:enabled;not null;default:true"`+ LastTriggeredAt *time.Time `json:"lastTriggeredAt,omitempty" gorm:"column:last_triggered_at"`+ BaseModel+}++func (Webhook) TableName() string {+ return "webhooks"+}diff --git a/backend/internal/services/container_service.go b/backend/internal/services/container_service.goindex f584d877a..af34c58c8 100644--- a/backend/internal/services/container_service.go+++ b/backend/internal/services/container_service.go@@ -422,13 +422,13 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID streturn createResp.ID, nil}-func (s *ContainerService) GetContainerByID(ctx context.Context, id string) (*container.InspectResponse, error) {+func (s *ContainerService) GetContainerByReference(ctx context.Context, ref string) (*container.InspectResponse, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {return nil, fmt.Errorf("failed to connect to Docker: %w", err)}- containerInspect, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, id, client.ContainerInspectOptions{})+ containerInspect, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, ref, client.ContainerInspectOptions{})if err != nil {return nil, fmt.Errorf("container not found: %w", err)}@@ -437,15 +437,24 @@ func (s *ContainerService) GetContainerByID(ctx context.Context, id string) (*coreturn &containerInfo, nil}-// GetContainerNameByID resolves a container's clean name from its Docker ID.-func (s *ContainerService) GetContainerNameByID(ctx context.Context, id string) (string, error) {- info, err := s.GetContainerByID(ctx, id)+func (s *ContainerService) GetContainerByID(ctx context.Context, id string) (*container.InspectResponse, error) {+ return s.GetContainerByReference(ctx, id)+}++// GetContainerNameByReference resolves a container's clean name from a Docker ID or name.+func (s *ContainerService) GetContainerNameByReference(ctx context.Context, ref string) (string, error) {+ info, err := s.GetContainerByReference(ctx, ref)if err != nil {return "", err}return strings.TrimPrefix(info.Name, "/"), nil}+// GetContainerNameByID resolves a container's clean name from its Docker ID.+func (s *ContainerService) GetContainerNameByID(ctx context.Context, id string) (string, error) {+ return s.GetContainerNameByReference(ctx, id)+}+func (s *ContainerService) DeleteContainer(ctx context.Context, containerID string, force bool, removeVolumes bool, user models.User) error {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {diff --git a/backend/internal/services/webhook_service.go b/backend/internal/services/webhook_service.gonew file mode 100644index 000000000..29918b078--- /dev/null+++ b/backend/internal/services/webhook_service.go@@ -0,0 +1,651 @@+package services++import (+ "context"+ crand "crypto/rand"+ "crypto/sha256"+ "encoding/base64"+ "encoding/hex"+ "errors"+ "fmt"+ "strings"+ "time"++ "github.com/getarcaneapp/arcane/backend/internal/database"+ "github.com/getarcaneapp/arcane/backend/internal/models"+ libcrypto "github.com/getarcaneapp/arcane/backend/pkg/libarcane/crypto"+ "github.com/getarcaneapp/arcane/types/updater"+ webhooktypes "github.com/getarcaneapp/arcane/types/webhook"+ "gorm.io/gorm"+)++var (+ ErrWebhookNotFound = errors.New("webhook not found")+ ErrWebhookInvalid = errors.New("invalid webhook token")+ ErrWebhookDisabled = errors.New("webhook is disabled")+ ErrWebhookInvalidType = errors.New("invalid webhook target type")+ ErrWebhookInvalidAction = errors.New("invalid webhook action type")+ ErrWebhookMissingTarget = errors.New("target ID is required for container, project, and gitops webhook types")+)++const (+ webhookTokenPrefix = "arc_wh_"+ webhookTokenLength = 32 // raw bytes → 64 hex chars+ webhookTokenPrefixLen = 8 // chars of the hex portion used as lookup prefix+)++type WebhookService struct {+ db *database.DB+ containerService *ContainerService+ updaterService *UpdaterService+ projectService *ProjectService+ gitOpsSyncService *GitOpsSyncService+ eventService *EventService+}++func NewWebhookService(db *database.DB, containerService *ContainerService, updaterService *UpdaterService, projectService *ProjectService, gitOpsSyncService *GitOpsSyncService, eventService *EventService) *WebhookService {+ return &WebhookService{+ db: db,+ containerService: containerService,+ updaterService: updaterService,+ projectService: projectService,+ gitOpsSyncService: gitOpsSyncService,+ eventService: eventService,+ }+}++// generateWebhookTokenInternal creates a new random webhook token and returns the raw token+// (to be shown to the user once), its SHA-256 hash, and the lookup prefix.+func generateWebhookTokenInternal() (raw, hash, prefix string, err error) {+ b := make([]byte, webhookTokenLength)+ if _, err = crand.Read(b); err != nil {+ return "", "", "", fmt.Errorf("failed to generate webhook token: %w", err)+ }+ secretHex := hex.EncodeToString(b)+ encrypted, err := libcrypto.Encrypt(secretHex)+ if err != nil {+ return "", "", "", fmt.Errorf("failed to encrypt webhook token: %w", err)+ }+ encryptedBytes, err := base64.StdEncoding.DecodeString(encrypted)+ if err != nil {+ return "", "", "", fmt.Errorf("failed to decode encrypted webhook token: %w", err)+ }+ tokenHex := hex.EncodeToString(encryptedBytes)+ raw = webhookTokenPrefix + tokenHex+ sum := sha256.Sum256([]byte(raw))+ hash = hex.EncodeToString(sum[:])+ prefix = webhookTokenPrefix + tokenHex[:webhookTokenPrefixLen]+ return raw, hash, prefix, nil+}++func hashWebhookTokenInternal(raw string) string {+ sum := sha256.Sum256([]byte(raw))+ return hex.EncodeToString(sum[:])+}++func parseWebhookPrefixInternal(raw string) (string, error) {+ raw = strings.TrimSpace(raw)+ hexPart, ok := strings.CutPrefix(raw, webhookTokenPrefix)+ if !ok || len(hexPart) < webhookTokenPrefixLen {+ return "", ErrWebhookInvalid+ }+ return webhookTokenPrefix + hexPart[:webhookTokenPrefixLen], nil+}++func defaultWebhookActionTypeInternal(targetType string) (string, error) {+ switch targetType {+ case models.WebhookTargetTypeContainer, models.WebhookTargetTypeProject:+ return models.WebhookActionTypeUpdate, nil+ case models.WebhookTargetTypeUpdater:+ return models.WebhookActionTypeRun, nil+ case models.WebhookTargetTypeGitOps:+ return models.WebhookActionTypeSync, nil+ default:+ return "", ErrWebhookInvalidType+ }+}++func resolveWebhookActionTypeInternal(targetType, actionType string) (string, error) {+ switch targetType {+ case models.WebhookTargetTypeContainer, models.WebhookTargetTypeProject, models.WebhookTargetTypeUpdater, models.WebhookTargetTypeGitOps:+ default:+ return "", ErrWebhookInvalidType+ }++ normalizedActionType := strings.TrimSpace(strings.ToLower(actionType))+ if normalizedActionType == "" {+ return defaultWebhookActionTypeInternal(targetType)+ }++ if targetType == models.WebhookTargetTypeProject && normalizedActionType == "deploy" {+ normalizedActionType = models.WebhookActionTypeUp+ }++ switch targetType {+ case models.WebhookTargetTypeContainer:+ switch normalizedActionType {+ case models.WebhookActionTypeUpdate, models.WebhookActionTypeStart, models.WebhookActionTypeStop, models.WebhookActionTypeRestart, models.WebhookActionTypeRedeploy:+ return normalizedActionType, nil+ }+ case models.WebhookTargetTypeProject:+ switch normalizedActionType {+ case models.WebhookActionTypeUpdate, models.WebhookActionTypeUp, models.WebhookActionTypeDown, models.WebhookActionTypeRestart, models.WebhookActionTypeRedeploy:+ return normalizedActionType, nil+ }+ case models.WebhookTargetTypeUpdater:+ if normalizedActionType == models.WebhookActionTypeRun {+ return normalizedActionType, nil+ }+ case models.WebhookTargetTypeGitOps:+ if normalizedActionType == models.WebhookActionTypeSync {+ return normalizedActionType, nil+ }+ }++ return "", ErrWebhookInvalidAction+}++func resolvedWebhookActionTypeInternal(targetType, actionType string) string {+ resolvedActionType, err := resolveWebhookActionTypeInternal(targetType, actionType)+ if err != nil {+ return strings.TrimSpace(strings.ToLower(actionType))+ }+ return resolvedActionType+}++// CreateWebhook creates a new webhook targeting a stack, the environment-wide updater, or a gitops sync.+// It returns the webhook record with the raw token populated (only available at creation time).+func (s *WebhookService) CreateWebhook(ctx context.Context, name, targetType, actionType, targetID, environmentID string, actor models.User) (*models.Webhook, string, error) {+ resolvedActionType, err := resolveWebhookActionTypeInternal(targetType, actionType)+ if err != nil {+ return nil, "", err+ }++ targetRef := ""++ // The updater target type operates environment-wide and has no specific target resource.+ if targetType == models.WebhookTargetTypeUpdater {+ targetID = ""+ } else if strings.TrimSpace(targetID) == "" {+ return nil, "", ErrWebhookMissingTarget+ }++ if targetType == models.WebhookTargetTypeContainer {+ targetRef, err = s.resolveContainerWebhookTargetRefInternal(ctx, targetID)+ if err != nil {+ return nil, "", err+ }+ }++ raw, hash, prefix, err := generateWebhookTokenInternal()+ if err != nil {+ return nil, "", err+ }++ wh := &models.Webhook{+ Name: name,+ TokenHash: hash,+ TokenPrefix: prefix,+ TargetType: targetType,+ ActionType: resolvedActionType,+ TargetID: targetID,+ TargetRef: targetRef,+ EnvironmentID: environmentID,+ Enabled: true,+ }++ if err := s.db.WithContext(ctx).Create(wh).Error; err != nil {+ return nil, "", fmt.Errorf("failed to create webhook: %w", err)+ }++ if s.eventService != nil {+ resourceType := "webhook"+ _, _ = s.eventService.CreateEvent(ctx, CreateEventRequest{+ Type: models.EventTypeWebhookCreate,+ Severity: models.EventSeveritySuccess,+ Title: fmt.Sprintf("Webhook created: %s", wh.Name),+ Description: fmt.Sprintf("Created webhook '%s' targeting %s (%s)", wh.Name, wh.TargetType, wh.ActionType),+ ResourceType: &resourceType,+ ResourceID: &wh.ID,+ ResourceName: &wh.Name,+ UserID: &actor.ID,+ Username: &actor.Username,+ EnvironmentID: &wh.EnvironmentID,+ })+ }++ return wh, raw, nil+}++// ListWebhooks returns all webhooks for an environment.+func (s *WebhookService) ListWebhooks(ctx context.Context, environmentID string) ([]models.Webhook, error) {+ var webhooks []models.Webhook+ if err := s.db.WithContext(ctx).+ Where("environment_id = ?", environmentID).+ Order("created_at DESC").+ Find(&webhooks).Error; err != nil {+ return nil, fmt.Errorf("failed to list webhooks: %w", err)+ }+ return webhooks, nil+}++func (s *WebhookService) ListWebhookSummaries(ctx context.Context, environmentID string) ([]webhooktypes.Summary, error) {+ webhooks, err := s.ListWebhooks(ctx, environmentID)+ if err != nil {+ return nil, err+ }++ summaries := make([]webhooktypes.Summary, len(webhooks))+ for i := range webhooks {+ wh := webhooks[i]+ summaries[i] = webhooktypes.Summary{+ ID: wh.ID,+ Name: wh.Name,+ TokenPrefix: wh.TokenPrefix,+ TargetType: wh.TargetType,+ ActionType: resolvedWebhookActionTypeInternal(wh.TargetType, wh.ActionType),+ TargetID: wh.TargetID,+ TargetName: s.resolveWebhookTargetNameInternal(ctx, &wh),+ EnvironmentID: wh.EnvironmentID,+ Enabled: wh.Enabled,+ LastTriggeredAt: wh.LastTriggeredAt,+ CreatedAt: wh.CreatedAt,+ }+ }++ return summaries, nil+}++func (s *WebhookService) resolveWebhookTargetNameInternal(ctx context.Context, wh *models.Webhook) string {+ switch wh.TargetType {+ case models.WebhookTargetTypeContainer:+ if strings.TrimSpace(wh.TargetRef) != "" {+ if s.containerService == nil {+ return wh.TargetRef+ }+ name, err := s.containerService.GetContainerNameByReference(ctx, wh.TargetRef)+ if err == nil {+ return name+ }+ return wh.TargetRef+ }+ if s.containerService == nil {+ return ""+ }+ name, err := s.containerService.GetContainerNameByID(ctx, wh.TargetID)+ if err != nil {+ return ""+ }+ return name+ case models.WebhookTargetTypeProject:+ var project models.Project+ if err := s.db.WithContext(ctx).+ Select("name").+ Where("id = ?", wh.TargetID).+ First(&project).Error; err != nil {+ return ""+ }+ return project.Name+ case models.WebhookTargetTypeUpdater:+ return "Environment updater"+ case models.WebhookTargetTypeGitOps:+ var sync models.GitOpsSync+ if err := s.db.WithContext(ctx).+ Select("name").+ Where("id = ? AND environment_id = ?", wh.TargetID, wh.EnvironmentID).+ First(&sync).Error; err != nil {+ return ""+ }+ return sync.Name+ default:+ return ""+ }+}++// GetWebhookByID returns a single webhook by ID, scoped to an environment.+func (s *WebhookService) GetWebhookByID(ctx context.Context, id, environmentID string) (*models.Webhook, error) {+ var wh models.Webhook+ err := s.db.WithContext(ctx).+ Where("id = ? AND environment_id = ?", id, environmentID).+ First(&wh).Error+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return nil, ErrWebhookNotFound+ }+ if err != nil {+ return nil, fmt.Errorf("failed to get webhook: %w", err)+ }+ return &wh, nil+}++// DeleteWebhook removes a webhook by ID, scoped to an environment.+func (s *WebhookService) DeleteWebhook(ctx context.Context, id, environmentID string, actor models.User) error {+ wh, err := s.GetWebhookByID(ctx, id, environmentID)+ if err != nil {+ return err+ }++ result := s.db.WithContext(ctx).+ Where("id = ? AND environment_id = ?", id, environmentID).+ Delete(&models.Webhook{})+ if result.Error != nil {+ return fmt.Errorf("failed to delete webhook: %w", result.Error)+ }+ if result.RowsAffected == 0 {+ return ErrWebhookNotFound+ }++ if s.eventService != nil {+ resourceType := "webhook"+ _, _ = s.eventService.CreateEvent(ctx, CreateEventRequest{+ Type: models.EventTypeWebhookDelete,+ Severity: models.EventSeverityInfo,+ Title: fmt.Sprintf("Webhook deleted: %s", wh.Name),+ Description: fmt.Sprintf("Deleted webhook '%s'", wh.Name),+ ResourceType: &resourceType,+ ResourceID: &wh.ID,+ ResourceName: &wh.Name,+ UserID: &actor.ID,+ Username: &actor.Username,+ EnvironmentID: &wh.EnvironmentID,+ })+ }++ return nil+}++// UpdateWebhook updates the enabled state of a webhook, scoped to an environment.+func (s *WebhookService) UpdateWebhook(ctx context.Context, id, environmentID string, enabled bool, actor models.User) (*models.Webhook, error) {+ var wh models.Webhook+ err := s.db.WithContext(ctx).+ Where("id = ? AND environment_id = ?", id, environmentID).+ First(&wh).Error+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return nil, ErrWebhookNotFound+ }+ if err != nil {+ return nil, fmt.Errorf("failed to get webhook: %w", err)+ }++ if err := s.db.WithContext(ctx).Model(&wh).Update("enabled", enabled).Error; err != nil {+ return nil, fmt.Errorf("failed to update webhook: %w", err)+ }++ if s.eventService != nil {+ resourceType := "webhook"+ _, _ = s.eventService.CreateEvent(ctx, CreateEventRequest{+ Type: models.EventTypeWebhookUpdate,+ Severity: models.EventSeveritySuccess,+ Title: fmt.Sprintf("Webhook updated: %s", wh.Name),+ Description: fmt.Sprintf("Updated webhook '%s' enabled=%v", wh.Name, enabled),+ ResourceType: &resourceType,+ ResourceID: &wh.ID,+ ResourceName: &wh.Name,+ UserID: &actor.ID,+ Username: &actor.Username,+ EnvironmentID: &wh.EnvironmentID,+ })+ }++ return &wh, nil+}++// TriggerByToken looks up a webhook by its raw token and executes the configured action.+// Returns an updater result for "updater" webhooks; nil for "project" and "gitops".+func (s *WebhookService) TriggerByToken(ctx context.Context, rawToken string) (*updater.Result, error) {+ prefix, err := parseWebhookPrefixInternal(rawToken)+ if err != nil {+ return nil, ErrWebhookInvalid+ }++ // Narrow by prefix first (indexed), then verify hash+ var candidates []models.Webhook+ if err := s.db.WithContext(ctx).+ Where("token_prefix = ?", prefix).+ Find(&candidates).Error; err != nil {+ return nil, fmt.Errorf("failed to look up webhook: %w", err)+ }++ hash := hashWebhookTokenInternal(rawToken)+ var wh *models.Webhook+ for i := range candidates {+ if candidates[i].TokenHash == hash {+ wh = &candidates[i]+ break+ }+ }+ if wh == nil {+ return nil, ErrWebhookNotFound+ }+ if !wh.Enabled {+ return nil, ErrWebhookDisabled+ }++ var result *updater.Result+ actionType, err := resolveWebhookActionTypeInternal(wh.TargetType, wh.ActionType)+ if err != nil {+ return nil, err+ }++ result, err = s.executeWebhookActionInternal(ctx, wh, actionType)+ if err != nil {+ return nil, err+ }++ // Record trigger time — best-effort, do not fail the request if this update fails.+ now := time.Now()+ _ = s.db.WithContext(ctx).Model(wh).Update("last_triggered_at", now).Error //nolint:errcheck++ s.logWebhookEventInternal(ctx, wh, actionType, models.EventSeveritySuccess, "")++ return result, nil+}++func (s *WebhookService) executeWebhookActionInternal(ctx context.Context, wh *models.Webhook, actionType string) (*updater.Result, error) {+ switch wh.TargetType {+ case models.WebhookTargetTypeContainer:+ return s.executeContainerWebhookActionInternal(ctx, wh, actionType)+ case models.WebhookTargetTypeProject:+ return s.executeProjectWebhookActionInternal(ctx, wh, actionType)+ case models.WebhookTargetTypeUpdater:+ return s.executeUpdaterWebhookActionInternal(ctx, wh, actionType)+ case models.WebhookTargetTypeGitOps:+ return s.executeGitOpsWebhookActionInternal(ctx, wh, actionType)+ default:+ return nil, ErrWebhookInvalidType+ }+}++func (s *WebhookService) executeContainerWebhookActionInternal(ctx context.Context, wh *models.Webhook, actionType string) (*updater.Result, error) {+ containerID, err := s.resolveContainerWebhookTargetIDInternal(ctx, wh)+ if err != nil {+ return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "container", actionType, err)+ }++ switch actionType {+ case models.WebhookActionTypeUpdate:+ result, err := s.updaterService.UpdateSingleContainer(ctx, containerID)+ if err != nil {+ return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "container", actionType, err)+ }+ return result, nil+ case models.WebhookActionTypeStart:+ if err := s.containerService.StartContainer(ctx, containerID, systemUser); err != nil {+ return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "container", actionType, err)+ }+ return nil, nil+ case models.WebhookActionTypeStop:+ if err := s.containerService.StopContainer(ctx, containerID, systemUser); err != nil {+ return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "container", actionType, err)+ }+ return nil, nil+ case models.WebhookActionTypeRestart:+ if err := s.containerService.RestartContainer(ctx, containerID, systemUser); err != nil {+ return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "container", actionType, err)+ }+ return nil, nil+ case models.WebhookActionTypeRedeploy:+ if _, err := s.containerService.RedeployContainer(ctx, containerID, systemUser); err != nil {+ return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "container", actionType, err)+ }+ return nil, nil+ default:+ return nil, ErrWebhookInvalidAction+ }+}++func (s *WebhookService) resolveContainerWebhookTargetRefInternal(ctx context.Context, targetID string) (string, error) {+ if s.containerService == nil {+ return "", nil+ }++ containerName, err := s.containerService.GetContainerNameByReference(ctx, targetID)+ if err != nil {+ return "", fmt.Errorf("failed to resolve container target reference: %w", err)+ }++ return containerName, nil+}++func (s *WebhookService) resolveContainerWebhookTargetIDInternal(ctx context.Context, wh *models.Webhook) (string, error) {+ if s.containerService == nil {+ return wh.TargetID, nil+ }++ references := make([]string, 0, 2)+ if strings.TrimSpace(wh.TargetRef) != "" {+ references = append(references, wh.TargetRef)+ }+ if strings.TrimSpace(wh.TargetID) != "" {+ references = append(references, wh.TargetID)+ }++ var lastErr error+ for _, ref := range references {+ containerInfo, err := s.containerService.GetContainerByReference(ctx, ref)+ if err != nil {+ lastErr = err+ continue+ }++ containerName := strings.TrimPrefix(containerInfo.Name, "/")+ s.syncWebhookContainerTargetInternal(ctx, wh, containerInfo.ID, containerName)+ return containerInfo.ID, nil+ }++ if lastErr != nil {+ return "", lastErr+ }++ return "", ErrWebhookMissingTarget+}++func (s *WebhookService) syncWebhookContainerTargetInternal(ctx context.Context, wh *models.Webhook, containerID, containerName string) {+ updates := map[string]any{}+ if containerID != "" && containerID != wh.TargetID {+ updates["target_id"] = containerID+ wh.TargetID = containerID+ }+ if containerName != "" && containerName != wh.TargetRef {+ updates["target_ref"] = containerName+ wh.TargetRef = containerName+ }+ if len(updates) == 0 {+ return+ }++ _ = s.db.WithContext(ctx).Model(wh).Updates(updates).Error //nolint:errcheck+}++func (s *WebhookService) executeProjectWebhookActionInternal(ctx context.Context, wh *models.Webhook, actionType string) (*updater.Result, error) {+ switch actionType {+ case models.WebhookActionTypeUpdate:+ if err := s.projectService.UpdateProjectServices(ctx, wh.TargetID, nil, systemUser); err != nil {+ return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "project", actionType, err)+ }+ return nil, nil+ case models.WebhookActionTypeUp:+ if err := s.projectService.DeployProject(ctx, wh.TargetID, systemUser, nil); err != nil {+ return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "project", actionType, err)+ }+ return nil, nil+ case models.WebhookActionTypeDown:+ if err := s.projectService.DownProject(ctx, wh.TargetID, systemUser); err != nil {+ return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "project", actionType, err)+ }+ return nil, nil+ case models.WebhookActionTypeRestart:+ if err := s.projectService.RestartProject(ctx, wh.TargetID, systemUser); err != nil {+ return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "project", actionType, err)+ }+ return nil, nil+ case models.WebhookActionTypeRedeploy:+ if err := s.projectService.RedeployProject(ctx, wh.TargetID, systemUser); err != nil {+ return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "project", actionType, err)+ }+ return nil, nil+ default:+ return nil, ErrWebhookInvalidAction+ }+}++func (s *WebhookService) executeUpdaterWebhookActionInternal(ctx context.Context, wh *models.Webhook, actionType string) (*updater.Result, error) {+ if actionType != models.WebhookActionTypeRun {+ return nil, ErrWebhookInvalidAction+ }++ result, err := s.updaterService.ApplyPending(ctx, false)+ if err != nil {+ return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "updater", actionType, err)+ }++ return result, nil+}++func (s *WebhookService) executeGitOpsWebhookActionInternal(ctx context.Context, wh *models.Webhook, actionType string) (*updater.Result, error) {+ if actionType != models.WebhookActionTypeSync {+ return nil, ErrWebhookInvalidAction+ }++ if _, err := s.gitOpsSyncService.PerformSync(ctx, wh.EnvironmentID, wh.TargetID, systemUser); err != nil {+ return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "gitops", actionType, err)+ }++ return nil, nil+}++func (s *WebhookService) wrapWebhookActionErrorInternal(ctx context.Context, wh *models.Webhook, targetKind, actionType string, err error) error {+ msg := fmt.Sprintf("%s %s failed: %s", targetKind, actionType, err)+ s.logWebhookEventInternal(ctx, wh, actionType, models.EventSeverityError, msg)+ return fmt.Errorf("%s %s failed: %w", targetKind, actionType, err)+}++func (s *WebhookService) logWebhookEventInternal(ctx context.Context, wh *models.Webhook, actionType string, severity models.EventSeverity, errMsg string) {+ if s.eventService == nil {+ return+ }+ title := fmt.Sprintf("Webhook triggered: %s", wh.Name)+ if severity == models.EventSeverityError {+ title = fmt.Sprintf("Webhook trigger failed: %s", wh.Name)+ }+ description := fmt.Sprintf("Target type: %s, action: %s", wh.TargetType, actionType)+ if errMsg != "" {+ description = errMsg+ }+ resourceType := "webhook"+ _, _ = s.eventService.CreateEvent(ctx, CreateEventRequest{+ Type: models.EventTypeWebhookTrigger,+ Severity: severity,+ Title: title,+ Description: description,+ ResourceType: &resourceType,+ ResourceID: &wh.ID,+ ResourceName: &wh.Name,+ EnvironmentID: &wh.EnvironmentID,+ Metadata: models.JSON{+ "targetType": wh.TargetType,+ "actionType": actionType,+ "targetId": wh.TargetID,+ "tokenPrefix": wh.TokenPrefix,+ },+ })+}diff --git a/backend/internal/services/webhook_service_test.go b/backend/internal/services/webhook_service_test.gonew file mode 100644index 000000000..badbbec9f--- /dev/null+++ b/backend/internal/services/webhook_service_test.go@@ -0,0 +1,653 @@+package services++import (+ "context"+ "crypto/sha256"+ "encoding/base64"+ "encoding/hex"+ "fmt"+ "strings"+ "testing"++ libcrypto "github.com/getarcaneapp/arcane/backend/pkg/libarcane/crypto"+ glsqlite "github.com/glebarez/sqlite"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+ "gorm.io/gorm"++ "github.com/getarcaneapp/arcane/backend/internal/database"+ "github.com/getarcaneapp/arcane/backend/internal/models"+)++// setupWebhookServiceTestDB creates an isolated in-memory SQLite DB for each test.+func setupWebhookServiceTestDB(t *testing.T) *database.DB {+ t.Helper()+ initWebhookTokenCryptoForTests()++ dsn := fmt.Sprintf("file:%s?mode=memory&cache=shared", strings.NewReplacer("/", "_", " ", "_").Replace(t.Name()))+ db, err := gorm.Open(glsqlite.Open(dsn), &gorm.Config{})+ require.NoError(t, err)+ require.NoError(t, db.AutoMigrate(&models.Webhook{}))++ sqlDB, err := db.DB()+ require.NoError(t, err)+ sqlDB.SetMaxOpenConns(1)+ sqlDB.SetMaxIdleConns(1)++ return &database.DB{DB: db}+}++func initWebhookTokenCryptoForTests() {+ libcrypto.InitEncryption(&libcrypto.Config{+ EncryptionKey: "test-encryption-key-for-testing-32bytes-min",+ Environment: "test",+ })+}++// newTestWebhookService returns a WebhookService with nil updater/project/gitops services,+// sufficient for all tests that exercise lookup, hashing, and CRUD logic.+// Tests that exercise the dispatch path use an unknown target type to avoid a nil dereference.+func newTestWebhookService(db *database.DB) *WebhookService {+ return &WebhookService{db: db}+}++// fetchWebhook loads a webhook directly from the DB to inspect stored fields.+func fetchWebhook(t *testing.T, db *database.DB, id string) models.Webhook {+ t.Helper()+ var wh models.Webhook+ require.NoError(t, db.WithContext(context.Background()).Where("id = ?", id).First(&wh).Error)+ return wh+}++func defaultTestWebhookActionType(targetType string) string {+ switch targetType {+ case models.WebhookTargetTypeContainer, models.WebhookTargetTypeProject:+ return models.WebhookActionTypeUpdate+ case models.WebhookTargetTypeUpdater:+ return models.WebhookActionTypeRun+ case models.WebhookTargetTypeGitOps:+ return models.WebhookActionTypeSync+ default:+ return models.WebhookActionTypeUpdate+ }+}++// --- Token generation & hashing ---++func TestWebhookTokenFormat(t *testing.T) {+ initWebhookTokenCryptoForTests()++ raw, hash, prefix, err := generateWebhookTokenInternal()+ require.NoError(t, err)++ assert.True(t, strings.HasPrefix(raw, webhookTokenPrefix), "token must start with %q", webhookTokenPrefix)+ tokenHex := strings.TrimPrefix(raw, webhookTokenPrefix)+ encryptedBytes, err := hex.DecodeString(tokenHex)+ require.NoError(t, err)+ assert.Equal(t, webhookTokenPrefix+tokenHex[:webhookTokenPrefixLen], prefix, "prefix must be arc_wh_ + first %d chars of token hex", webhookTokenPrefixLen)++ encrypted := base64.StdEncoding.EncodeToString(encryptedBytes)+ decrypted, err := libcrypto.Decrypt(encrypted)+ require.NoError(t, err)+ assert.Len(t, decrypted, webhookTokenLength*2, "decrypted token payload must be 64 hex chars (32 bytes)")++ expected := sha256.Sum256([]byte(raw))+ assert.Equal(t, hex.EncodeToString(expected[:]), hash, "stored hash must be SHA-256 of the raw token")+}++func TestHashWebhookTokenIsDeterministic(t *testing.T) {+ raw := "arc_wh_0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20"+ first := hashWebhookTokenInternal(raw)+ second := hashWebhookTokenInternal(raw)+ assert.Equal(t, first, second)+}++func TestParseWebhookPrefix_ValidToken(t *testing.T) {+ raw := "arc_wh_0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20"+ prefix, err := parseWebhookPrefixInternal(raw)+ require.NoError(t, err)+ assert.Equal(t, "arc_wh_01020304", prefix)+}++func TestParseWebhookPrefix_MissingPrefix(t *testing.T) {+ _, err := parseWebhookPrefixInternal("notawebhooktoken")+ assert.ErrorIs(t, err, ErrWebhookInvalid)+}++func TestParseWebhookPrefix_TooShort(t *testing.T) {+ _, err := parseWebhookPrefixInternal("arc_wh_0102030") // 7 chars after prefix — too short+ assert.ErrorIs(t, err, ErrWebhookInvalid)+}++func TestParseWebhookPrefix_LeadingWhitespaceStripped(t *testing.T) {+ raw := " arc_wh_0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20 "+ prefix, err := parseWebhookPrefixInternal(raw)+ require.NoError(t, err)+ assert.Equal(t, "arc_wh_01020304", prefix)+}++// --- CreateWebhook ---++func TestCreateWebhook_TokenNotStoredInPlaintext(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ wh, rawToken, err := svc.CreateWebhook(ctx, "my-hook", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "project-id", "env-1", models.User{})+ require.NoError(t, err)+ require.NotEmpty(t, rawToken)++ stored := fetchWebhook(t, db, wh.ID)+ assert.NotEqual(t, rawToken, stored.TokenHash, "raw token must not be stored as-is")+ assert.Equal(t, hashWebhookTokenInternal(rawToken), stored.TokenHash, "stored hash must match SHA-256 of raw token")+}++func TestCreateWebhook_PrefixMatchesToken(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ wh, rawToken, err := svc.CreateWebhook(ctx, "prefix-check", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "p1", "env-1", models.User{})+ require.NoError(t, err)++ hexPart := strings.TrimPrefix(rawToken, webhookTokenPrefix)+ expectedPrefix := webhookTokenPrefix + hexPart[:webhookTokenPrefixLen]+ assert.Equal(t, expectedPrefix, wh.TokenPrefix)++ stored := fetchWebhook(t, db, wh.ID)+ assert.Equal(t, expectedPrefix, stored.TokenPrefix)+}++func TestCreateWebhook_InvalidTargetTypeRejected(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ _, _, err := svc.CreateWebhook(ctx, "bad", "invalid-type", models.WebhookActionTypeUpdate, "c1", "env-1", models.User{})+ assert.ErrorIs(t, err, ErrWebhookInvalidType)+}++func TestCreateWebhook_EmptyTargetIDRejectedForNonUpdaterTypes(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ for _, targetType := range []string{+ models.WebhookTargetTypeContainer,+ models.WebhookTargetTypeProject,+ models.WebhookTargetTypeGitOps,+ } {+ _, _, err := svc.CreateWebhook(ctx, "hook", targetType, defaultTestWebhookActionType(targetType), "", "env-1", models.User{})+ assert.ErrorIs(t, err, ErrWebhookMissingTarget, "expected ErrWebhookMissingTarget for type %s with empty targetID", targetType)+ }+}++func TestCreateWebhook_InvalidActionTypeRejected(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ _, _, err := svc.CreateWebhook(ctx, "bad-action", models.WebhookTargetTypeContainer, models.WebhookActionTypeDown, "container-id", "env-1", models.User{})+ assert.ErrorIs(t, err, ErrWebhookInvalidAction)+}++func TestCreateWebhook_EmptyActionTypeDefaultsPerTarget(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ projectWebhook, _, err := svc.CreateWebhook(ctx, "project-hook", models.WebhookTargetTypeProject, "", "project-id", "env-1", models.User{})+ require.NoError(t, err)+ assert.Equal(t, models.WebhookActionTypeUpdate, projectWebhook.ActionType)++ updaterWebhook, _, err := svc.CreateWebhook(ctx, "updater-hook", models.WebhookTargetTypeUpdater, "", "", "env-1", models.User{})+ require.NoError(t, err)+ assert.Equal(t, models.WebhookActionTypeRun, updaterWebhook.ActionType)+}++func TestCreateWebhook_EmptyTargetIDAcceptedForUpdaterType(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ wh, _, err := svc.CreateWebhook(ctx, "updater-hook", models.WebhookTargetTypeUpdater, models.WebhookActionTypeRun, "", "env-1", models.User{})+ require.NoError(t, err)+ assert.Equal(t, "", wh.TargetID)+}++func TestCreateWebhook_ContainerTypeAccepted(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ wh, _, err := svc.CreateWebhook(ctx, "container-hook", models.WebhookTargetTypeContainer, models.WebhookActionTypeUpdate, "container-id", "env-1", models.User{})+ require.NoError(t, err)+ assert.Equal(t, models.WebhookTargetTypeContainer, wh.TargetType)+ assert.Equal(t, models.WebhookActionTypeUpdate, wh.ActionType)+}++func TestCreateWebhook_ProjectTypeAccepted(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ wh, _, err := svc.CreateWebhook(ctx, "stack-hook", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "project-id", "env-1", models.User{})+ require.NoError(t, err)+ assert.Equal(t, models.WebhookTargetTypeProject, wh.TargetType)+ assert.Equal(t, models.WebhookActionTypeUpdate, wh.ActionType)+}++func TestCreateWebhook_UpdaterTypeAccepted(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ wh, _, err := svc.CreateWebhook(ctx, "updater-hook", models.WebhookTargetTypeUpdater, models.WebhookActionTypeRun, "", "env-1", models.User{})+ require.NoError(t, err)+ assert.Equal(t, models.WebhookTargetTypeUpdater, wh.TargetType)+ assert.Equal(t, models.WebhookActionTypeRun, wh.ActionType)+}++func TestCreateWebhook_GitOpsTypeAccepted(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ wh, _, err := svc.CreateWebhook(ctx, "gitops-hook", models.WebhookTargetTypeGitOps, models.WebhookActionTypeSync, "sync-id", "env-1", models.User{})+ require.NoError(t, err)+ assert.Equal(t, models.WebhookTargetTypeGitOps, wh.TargetType)+ assert.Equal(t, models.WebhookActionTypeSync, wh.ActionType)+}++func TestCreateWebhook_EnabledByDefault(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ wh, _, err := svc.CreateWebhook(ctx, "enabled", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "p1", "env-1", models.User{})+ require.NoError(t, err)+ assert.True(t, wh.Enabled)+}++func TestCreateWebhook_UniqueTokensEachCall(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ _, token1, err := svc.CreateWebhook(ctx, "h1", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "p1", "env-1", models.User{})+ require.NoError(t, err)+ _, token2, err := svc.CreateWebhook(ctx, "h2", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "p2", "env-1", models.User{})+ require.NoError(t, err)++ assert.NotEqual(t, token1, token2)+}++// --- ListWebhooks ---++func TestListWebhooks_ScopedToEnvironment(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ _, _, err := svc.CreateWebhook(ctx, "env1-hook", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "p1", "env-1", models.User{})+ require.NoError(t, err)+ _, _, err = svc.CreateWebhook(ctx, "env2-hook", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "p2", "env-2", models.User{})+ require.NoError(t, err)++ list, err := svc.ListWebhooks(ctx, "env-1")+ require.NoError(t, err)+ require.Len(t, list, 1)+ assert.Equal(t, "env1-hook", list[0].Name)+}++func TestListWebhooks_EmptyForUnknownEnvironment(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ list, err := svc.ListWebhooks(ctx, "no-such-env")+ require.NoError(t, err)+ assert.Empty(t, list)+}++func TestListWebhookSummaries_ResolvesTargetNames(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ require.NoError(t, db.WithContext(ctx).Exec(`CREATE TABLE projects (id TEXT PRIMARY KEY, name TEXT NOT NULL)`).Error)+ require.NoError(t, db.WithContext(ctx).Exec(`CREATE TABLE gitops_syncs (id TEXT PRIMARY KEY, environment_id TEXT NOT NULL, name TEXT NOT NULL)`).Error)+ require.NoError(t, db.WithContext(ctx).Exec(`INSERT INTO projects (id, name) VALUES (?, ?)`, "project-1", "Main Project").Error)+ require.NoError(t, db.WithContext(ctx).Exec(`INSERT INTO gitops_syncs (id, environment_id, name) VALUES (?, ?, ?)`, "sync-1", "env-1", "Deploy Sync").Error)++ _, _, err := svc.CreateWebhook(ctx, "project-hook", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "project-1", "env-1", models.User{})+ require.NoError(t, err)+ _, _, err = svc.CreateWebhook(ctx, "updater-hook", models.WebhookTargetTypeUpdater, models.WebhookActionTypeRun, "", "env-1", models.User{})+ require.NoError(t, err)+ _, _, err = svc.CreateWebhook(ctx, "gitops-hook", models.WebhookTargetTypeGitOps, models.WebhookActionTypeSync, "sync-1", "env-1", models.User{})+ require.NoError(t, err)++ summaries, err := svc.ListWebhookSummaries(ctx, "env-1")+ require.NoError(t, err)+ require.Len(t, summaries, 3)++ targetNamesByType := make(map[string]string, len(summaries))+ for _, summary := range summaries {+ targetNamesByType[summary.TargetType] = summary.TargetName+ assert.Equal(t, defaultTestWebhookActionType(summary.TargetType), summary.ActionType)+ }++ assert.Equal(t, "Main Project", targetNamesByType[models.WebhookTargetTypeProject])+ assert.Equal(t, "Environment updater", targetNamesByType[models.WebhookTargetTypeUpdater])+ assert.Equal(t, "Deploy Sync", targetNamesByType[models.WebhookTargetTypeGitOps])+}++func TestListWebhookSummaries_DefaultsLegacyActionType(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ legacyWebhook := &models.Webhook{+ Name: "legacy-hook",+ TokenHash: "hash",+ TokenPrefix: "arc_wh_deadbeef",+ TargetType: models.WebhookTargetTypeProject,+ ActionType: "",+ TargetID: "project-1",+ EnvironmentID: "env-1",+ Enabled: true,+ }+ require.NoError(t, db.WithContext(ctx).Create(legacyWebhook).Error)++ summaries, err := svc.ListWebhookSummaries(ctx, "env-1")+ require.NoError(t, err)+ require.Len(t, summaries, 1)+ assert.Equal(t, models.WebhookActionTypeUpdate, summaries[0].ActionType)+}++// --- GetWebhookByID ---++func TestGetWebhookByID_ReturnsCorrectWebhook(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ created, _, err := svc.CreateWebhook(ctx, "get-me", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "p1", "env-1", models.User{})+ require.NoError(t, err)++ got, err := svc.GetWebhookByID(ctx, created.ID, "env-1")+ require.NoError(t, err)+ assert.Equal(t, created.ID, got.ID)+}++func TestGetWebhookByID_NotFoundForWrongEnvironment(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ created, _, err := svc.CreateWebhook(ctx, "env-scoped", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "p1", "env-1", models.User{})+ require.NoError(t, err)++ _, err = svc.GetWebhookByID(ctx, created.ID, "env-2")+ assert.ErrorIs(t, err, ErrWebhookNotFound)+}++func TestGetWebhookByID_NotFoundForUnknownID(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ _, err := svc.GetWebhookByID(ctx, "does-not-exist", "env-1")+ assert.ErrorIs(t, err, ErrWebhookNotFound)+}++// --- DeleteWebhook ---++func TestDeleteWebhook_RemovesRecord(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ created, _, err := svc.CreateWebhook(ctx, "delete-me", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "p1", "env-1", models.User{})+ require.NoError(t, err)++ require.NoError(t, svc.DeleteWebhook(ctx, created.ID, "env-1", models.User{}))++ _, err = svc.GetWebhookByID(ctx, created.ID, "env-1")+ assert.ErrorIs(t, err, ErrWebhookNotFound)+}++func TestDeleteWebhook_NotFoundForWrongEnvironment(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ created, _, err := svc.CreateWebhook(ctx, "env-scoped-delete", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "p1", "env-1", models.User{})+ require.NoError(t, err)++ err = svc.DeleteWebhook(ctx, created.ID, "env-2", models.User{})+ assert.ErrorIs(t, err, ErrWebhookNotFound)++ // Webhook must still exist in the correct environment+ _, err = svc.GetWebhookByID(ctx, created.ID, "env-1")+ assert.NoError(t, err)+}++func TestDeleteWebhook_NotFoundForUnknownID(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ err := svc.DeleteWebhook(ctx, "does-not-exist", "env-1", models.User{})+ assert.ErrorIs(t, err, ErrWebhookNotFound)+}++// --- UpdateWebhook ---++func TestUpdateWebhook_DisableAndEnable(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ wh, _, err := svc.CreateWebhook(ctx, "hook", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "proj-1", "env-1", models.User{})+ require.NoError(t, err)+ assert.True(t, wh.Enabled)++ updated, err := svc.UpdateWebhook(ctx, wh.ID, "env-1", false, models.User{})+ require.NoError(t, err)+ assert.False(t, updated.Enabled)++ updated, err = svc.UpdateWebhook(ctx, wh.ID, "env-1", true, models.User{})+ require.NoError(t, err)+ assert.True(t, updated.Enabled)+}++func TestUpdateWebhook_NotFoundForWrongEnvironment(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ wh, _, err := svc.CreateWebhook(ctx, "hook", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "proj-1", "env-1", models.User{})+ require.NoError(t, err)++ _, err = svc.UpdateWebhook(ctx, wh.ID, "env-other", false, models.User{})+ assert.ErrorIs(t, err, ErrWebhookNotFound)+}++func TestUpdateWebhook_NotFoundForUnknownID(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ _, err := svc.UpdateWebhook(ctx, "does-not-exist", "env-1", false, models.User{})+ assert.ErrorIs(t, err, ErrWebhookNotFound)+}++// --- TriggerByToken ---++func TestTriggerByToken_InvalidFormat(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ _, err := svc.TriggerByToken(ctx, "not-a-webhook-token")+ assert.ErrorIs(t, err, ErrWebhookInvalid)+}++func TestTriggerByToken_NotFound(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ // Well-formatted token but not in the DB+ raw := "arc_wh_0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20"+ _, err := svc.TriggerByToken(ctx, raw)+ assert.ErrorIs(t, err, ErrWebhookNotFound)+}++func TestTriggerByToken_WrongHash_NotFound(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ _, rawToken, err := svc.CreateWebhook(ctx, "hash-check", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "p1", "env-1", models.User{})+ require.NoError(t, err)++ // Flip the last character of the token+ tampered := rawToken[:len(rawToken)-1]+ if rawToken[len(rawToken)-1] == 'a' {+ tampered += "b"+ } else {+ tampered += "a"+ }++ _, err = svc.TriggerByToken(ctx, tampered)+ assert.ErrorIs(t, err, ErrWebhookNotFound)+}++func TestTriggerByToken_DisabledWebhook(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ created, rawToken, err := svc.CreateWebhook(ctx, "disabled-hook", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "p1", "env-1", models.User{})+ require.NoError(t, err)++ require.NoError(t, db.WithContext(ctx).Model(&models.Webhook{}).Where("id = ?", created.ID).Update("enabled", false).Error)++ _, err = svc.TriggerByToken(ctx, rawToken)+ assert.ErrorIs(t, err, ErrWebhookDisabled)+}++func TestTriggerByToken_UnknownTargetType_ReturnsInvalidType(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ rawToken := "arc_wh_aabbccdd0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c"+ hash := hashWebhookTokenInternal(rawToken)+ hexPart := strings.TrimPrefix(rawToken, webhookTokenPrefix)+ prefix := webhookTokenPrefix + hexPart[:webhookTokenPrefixLen]++ wh := &models.Webhook{+ Name: "bad-type",+ TokenHash: hash,+ TokenPrefix: prefix,+ TargetType: "unknown-type",+ TargetID: "some-id",+ EnvironmentID: "env-1",+ Enabled: true,+ }+ require.NoError(t, db.WithContext(ctx).Create(wh).Error)++ _, err := svc.TriggerByToken(ctx, rawToken)+ assert.ErrorIs(t, err, ErrWebhookInvalidType)+}++// insertWebhookDirect inserts a webhook record directly, bypassing CreateWebhook validation,+// so dispatch tests can use known target types without needing real service dependencies.+func insertWebhookDirect(t *testing.T, ctx context.Context, db *database.DB, rawToken, targetType, actionType, targetID, envID string) *models.Webhook {+ t.Helper()+ hash := hashWebhookTokenInternal(rawToken)+ hexPart := strings.TrimPrefix(rawToken, webhookTokenPrefix)+ wh := &models.Webhook{+ Name: "test-hook",+ TokenHash: hash,+ TokenPrefix: webhookTokenPrefix + hexPart[:webhookTokenPrefixLen],+ TargetType: targetType,+ ActionType: actionType,+ TargetID: targetID,+ EnvironmentID: envID,+ Enabled: true,+ }+ require.NoError(t, db.WithContext(ctx).Create(wh).Error)+ return wh+}++func TestTriggerByToken_ContainerType_NilServiceReturnsError(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db) // updaterService is nil++ rawToken := "arc_wh_ccddeeff01020304aabbccdd0102030405060708090a0b0c0d0e0f1011121314"+ insertWebhookDirect(t, ctx, db, rawToken, models.WebhookTargetTypeContainer, models.WebhookActionTypeUpdate, "container-id", "env-1")++ assert.Panics(t, func() {+ _, _ = svc.TriggerByToken(ctx, rawToken) //nolint:errcheck+ })+}++func TestTriggerByToken_UpdaterType_NilServiceReturnsError(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db) // updaterService is nil++ rawToken := "arc_wh_1122334401020304aabbccdd0102030405060708090a0b0c0d0e0f1011121314"+ insertWebhookDirect(t, ctx, db, rawToken, models.WebhookTargetTypeUpdater, models.WebhookActionTypeRun, "", "env-1")++ // nil updaterService causes a panic, which we verify the dispatch path is reached+ // by recovering — in production the service is always non-nil+ assert.Panics(t, func() {+ _, _ = svc.TriggerByToken(ctx, rawToken) //nolint:errcheck+ })+}++func TestTriggerByToken_GitOpsType_NilServiceReturnsError(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db) // gitOpsSyncService is nil++ rawToken := "arc_wh_aabbccdd11223344aabbccdd0102030405060708090a0b0c0d0e0f1011121314"+ insertWebhookDirect(t, ctx, db, rawToken, models.WebhookTargetTypeGitOps, models.WebhookActionTypeSync, "sync-id", "env-1")++ assert.Panics(t, func() {+ _, _ = svc.TriggerByToken(ctx, rawToken) //nolint:errcheck+ })+}++func TestTriggerByToken_DoesNotUpdateLastTriggeredAtOnError(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ rawToken := "arc_wh_1122334401020304aabbccdd0102030405060708090a0b0c0d0e0f1011121315"+ wh := insertWebhookDirect(t, ctx, db, rawToken, "unknown-type", models.WebhookActionTypeUpdate, "some-id", "env-1")++ _, err := svc.TriggerByToken(ctx, rawToken)+ require.Error(t, err)++ stored := fetchWebhook(t, db, wh.ID)+ assert.Nil(t, stored.LastTriggeredAt, "last_triggered_at must not be set when trigger fails")+}++func TestTriggerByToken_UnknownActionType_ReturnsInvalidAction(t *testing.T) {+ ctx := context.Background()+ db := setupWebhookServiceTestDB(t)+ svc := newTestWebhookService(db)++ rawToken := "arc_wh_0011223344556677aabbccdd0102030405060708090a0b0c0d0e0f1011121314"+ insertWebhookDirect(t, ctx, db, rawToken, models.WebhookTargetTypeProject, "bogus", "project-id", "env-1")++ _, err := svc.TriggerByToken(ctx, rawToken)+ assert.ErrorIs(t, err, ErrWebhookInvalidAction)+}diff --git a/backend/resources/migrations/postgres/045_add_webhooks.down.sql b/backend/resources/migrations/postgres/045_add_webhooks.down.sqlnew file mode 100644index 000000000..0457cf1c1--- /dev/null+++ b/backend/resources/migrations/postgres/045_add_webhooks.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS webhooks;diff --git a/backend/resources/migrations/postgres/045_add_webhooks.up.sql b/backend/resources/migrations/postgres/045_add_webhooks.up.sqlnew file mode 100644index 000000000..0f70c3734--- /dev/null+++ b/backend/resources/migrations/postgres/045_add_webhooks.up.sql@@ -0,0 +1,18 @@+CREATE TABLE IF NOT EXISTS webhooks (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ token_hash TEXT NOT NULL UNIQUE,+ token_prefix TEXT NOT NULL,+ target_type TEXT NOT NULL,+ action_type TEXT NOT NULL DEFAULT '',+ target_id TEXT NOT NULL,+ target_ref TEXT NOT NULL DEFAULT '',+ environment_id TEXT NOT NULL DEFAULT '',+ enabled BOOLEAN NOT NULL DEFAULT TRUE,+ last_triggered_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ+);++CREATE INDEX IF NOT EXISTS idx_webhooks_token_prefix ON webhooks (token_prefix);+CREATE INDEX IF NOT EXISTS idx_webhooks_environment_id ON webhooks (environment_id);diff --git a/backend/resources/migrations/sqlite/045_add_webhooks.down.sql b/backend/resources/migrations/sqlite/045_add_webhooks.down.sqlnew file mode 100644index 000000000..0457cf1c1--- /dev/null+++ b/backend/resources/migrations/sqlite/045_add_webhooks.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS webhooks;diff --git a/backend/resources/migrations/sqlite/045_add_webhooks.up.sql b/backend/resources/migrations/sqlite/045_add_webhooks.up.sqlnew file mode 100644index 000000000..ddd78c2fd--- /dev/null+++ b/backend/resources/migrations/sqlite/045_add_webhooks.up.sql@@ -0,0 +1,18 @@+CREATE TABLE IF NOT EXISTS webhooks (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ token_hash TEXT NOT NULL UNIQUE,+ token_prefix TEXT NOT NULL,+ target_type TEXT NOT NULL,+ action_type TEXT NOT NULL DEFAULT '',+ target_id TEXT NOT NULL,+ target_ref TEXT NOT NULL DEFAULT '',+ environment_id TEXT NOT NULL DEFAULT '',+ enabled INTEGER NOT NULL DEFAULT 1,+ last_triggered_at DATETIME,+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updated_at DATETIME+);++CREATE INDEX IF NOT EXISTS idx_webhooks_token_prefix ON webhooks(token_prefix);+CREATE INDEX IF NOT EXISTS idx_webhooks_environment_id ON webhooks(environment_id);diff --git a/frontend/messages/en.json b/frontend/messages/en.jsonindex 3c54ba6b7..cf18bd764 100644--- a/frontend/messages/en.json+++ b/frontend/messages/en.json@@ -2545,5 +2545,86 @@"settings_default_deploy_pull_policy": "Default Deploy Pull Policy","settings_default_deploy_pull_policy_description": "Default image pull policy when deploying projects","authentication_title": "Authentication",- "authentication_description": "Configure authentication providers, password policy, and session behavior."+ "authentication_description": "Configure authentication providers, password policy, and session behavior.",++ "webhook_page_title": "Webhooks",+ "webhook_page_description": "Manage inbound webhooks to trigger container, project, updater, or GitOps actions from external systems.",+ "webhook_create_button": "Create Webhook",+ "webhook_create_title": "Create Webhook",+ "webhook_create_description": "Create a webhook to trigger a specific container, project, updater, or GitOps action. The webhook URL is shown once only.",+ "webhook_created_title": "Webhook Created",+ "webhook_created_description": "Copy your webhook URL now — it will not be shown again.",+ "webhook_token_label": "Webhook URL",+ "webhook_token_copied": "Webhook URL copied to clipboard",+ "webhook_token_warning": "Store this webhook URL securely. It will not be displayed again. Send a POST request to this URL to trigger the webhook.",+ "webhook_name_label": "Name",+ "webhook_name_placeholder": "e.g. Deploy on push",+ "webhook_name_description": "A human-readable name to identify this webhook.",+ "webhook_target_type_label": "Target Type",+ "webhook_target_type_description": "What this webhook will trigger when called.",+ "webhook_target_type_container": "Container",+ "webhook_target_type_container_description": "Run a container action",+ "webhook_target_type_project": "Project",+ "webhook_target_type_project_description": "Run a project action",+ "webhook_target_type_updater": "Updater",+ "webhook_target_type_updater_description": "Run the environment-wide updater",+ "webhook_target_type_gitops": "GitOps",+ "webhook_target_type_gitops_description": "Run a GitOps sync action",+ "webhook_action_type_label": "Action Type",+ "webhook_action_type_description": "Which action should run for the selected target type.",+ "webhook_action_type_update": "Update",+ "webhook_action_type_update_description": "Update the selected resource using Arcane's update flow.",+ "webhook_action_type_start": "Start",+ "webhook_action_type_start_description": "Start the selected container.",+ "webhook_action_type_stop": "Stop",+ "webhook_action_type_stop_description": "Stop the selected container.",+ "webhook_action_type_restart": "Restart",+ "webhook_action_type_restart_description": "Restart the selected resource.",+ "webhook_action_type_redeploy": "Redeploy",+ "webhook_action_type_redeploy_description": "Redeploy the selected resource.",+ "webhook_action_type_up": "Up",+ "webhook_action_type_up_description": "Run compose up for the selected project.",+ "webhook_action_type_down": "Down",+ "webhook_action_type_down_description": "Run compose down for the selected project.",+ "webhook_action_type_run": "Run",+ "webhook_action_type_run_description": "Run the environment-wide updater.",+ "webhook_action_type_sync": "Sync",+ "webhook_action_type_sync_description": "Run the selected GitOps sync.",+ "webhook_target_resource_label_container": "Container",+ "webhook_target_resource_label_project": "Project",+ "webhook_target_resource_label_gitops": "GitOps Sync",+ "webhook_target_resource_description": "The specific resource this action applies to.",+ "webhook_target_resource_loading": "Loading...",+ "webhook_target_resource_placeholder": "Select a resource",+ "webhook_delete_title": "Delete webhook \"{name}\"?",+ "webhook_delete_message": "This will permanently delete the webhook \"{name}\". Any integrations using this webhook will stop working.",+ "webhook_delete_success": "Webhook \"{name}\" deleted",+ "webhook_delete_failed": "Failed to delete webhook \"{name}\"",+ "webhook_create_success": "Webhook \"{name}\" created",+ "webhook_create_failed": "Failed to create webhook \"{name}\"",+ "webhook_empty_title": "No webhooks configured yet.",+ "webhook_empty_description": "Create one to trigger updates from external systems.",+ "webhook_col_name": "Name",+ "webhook_col_token_prefix": "Token Prefix",+ "webhook_col_target_type": "Target Type",+ "webhook_col_action_type": "Action",+ "webhook_col_target_name": "Target",+ "webhook_col_last_triggered": "Last Triggered",+ "webhook_col_created": "Created",+ "webhook_type_container": "Container",+ "webhook_type_project": "Project",+ "webhook_type_updater": "Updater",+ "webhook_type_gitops": "GitOps",+ "webhook_hint_title": "Webhook alternative",+ "webhook_hint_description": "You can also trigger this sync on demand via a webhook. Create one in",+ "git_sync_webhook_hint_suffix": "and select this sync as the target.",+ "webhook_enable": "Enable",+ "webhook_disable": "Disable",+ "webhook_enable_success": "Webhook \"{name}\" enabled",+ "webhook_disable_success": "Webhook \"{name}\" disabled",+ "webhook_enable_failed": "Failed to enable webhook \"{name}\"",+ "webhook_disable_failed": "Failed to disable webhook \"{name}\"",+ "webhook_status_enabled": "Enabled",+ "webhook_status_disabled": "Disabled",+ "webhook_col_status": "Status"}diff --git a/frontend/src/lib/components/dialogs/gitops-sync-dialog.svelte b/frontend/src/lib/components/dialogs/gitops-sync-dialog.svelteindex 0bea510ef..64f080cbb 100644--- a/frontend/src/lib/components/dialogs/gitops-sync-dialog.svelte+++ b/frontend/src/lib/components/dialogs/gitops-sync-dialog.svelte@@ -13,7 +13,8 @@import { createForm, preventDefault } from '$lib/utils/form.utils';import { queryKeys } from '$lib/query/query-keys';import { m } from '$lib/paraglide/messages';- import { FolderOpenIcon } from '$lib/icons';+ import { FolderOpenIcon, InfoIcon } from '$lib/icons';+ import * as Alert from '$lib/components/ui/alert';import { createQuery } from '@tanstack/svelte-query';type GitOpsSyncFormProps = {@@ -240,6 +241,16 @@/><FormInput label={m.git_sync_sync_interval()} type="number" placeholder="5" bind:input={$inputs.syncInterval} />++ <Alert.Root class="border-primary/20 bg-primary/5 dark:border-primary/30 dark:bg-primary/10">+ <InfoIcon class="size-4" />+ <Alert.Title>{m.webhook_hint_title()}</Alert.Title>+ <Alert.Description>+ {m.webhook_hint_description()}+ <a href="/settings/webhooks" class="underline">{m.sidebar_settings()} → {m.webhook_page_title()}</a>+ {m.git_sync_webhook_hint_suffix()}+ </Alert.Description>+ </Alert.Root></form>{/if}{/snippet}diff --git a/frontend/src/lib/components/sheets/webhook-form-sheet.svelte b/frontend/src/lib/components/sheets/webhook-form-sheet.sveltenew file mode 100644index 000000000..fb1b6c204--- /dev/null+++ b/frontend/src/lib/components/sheets/webhook-form-sheet.svelte@@ -0,0 +1,244 @@+<script lang="ts">+ import * as ResponsiveDialog from '$lib/components/ui/responsive-dialog/index.js';+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';+ import FormInput from '$lib/components/form/form-input.svelte';+ import SelectWithLabel from '$lib/components/form/select-with-label.svelte';+ import type { WebhookActionType, WebhookTargetType, CreateWebhook } from '$lib/types/webhook.type';+ import { containerService } from '$lib/services/container-service';+ import { projectService } from '$lib/services/project-service';+ import { gitOpsSyncService } from '$lib/services/gitops-sync-service';+ import { environmentStore } from '$lib/stores/environment.store.svelte';+ import { z } from 'zod/v4';+ import { createForm, preventDefault } from '$lib/utils/form.utils';+ import * as m from '$lib/paraglide/messages.js';++ type WebhookFormProps = {+ open: boolean;+ onSubmit: (data: CreateWebhook) => void;+ isLoading: boolean;+ };++ let { open = $bindable(false), onSubmit, isLoading }: WebhookFormProps = $props();++ const targetTypeOptions = $derived([+ { value: 'container', label: m.webhook_target_type_container(), description: m.webhook_target_type_container_description() },+ { value: 'project', label: m.webhook_target_type_project(), description: m.webhook_target_type_project_description() },+ { value: 'updater', label: m.webhook_target_type_updater(), description: m.webhook_target_type_updater_description() },+ { value: 'gitops', label: m.webhook_target_type_gitops(), description: m.webhook_target_type_gitops_description() }+ ]);++ function getDefaultActionType(targetType: WebhookTargetType): WebhookActionType {+ switch (targetType) {+ case 'container':+ case 'project':+ return 'update';+ case 'updater':+ return 'run';+ case 'gitops':+ return 'sync';+ default:+ return 'update';+ }+ }++ function getActionTypeOptions(+ targetType: WebhookTargetType+ ): { value: WebhookActionType; label: string; description: string }[] {+ switch (targetType) {+ case 'container':+ return [+ { value: 'update', label: m.webhook_action_type_update(), description: m.webhook_action_type_update_description() },+ { value: 'start', label: m.webhook_action_type_start(), description: m.webhook_action_type_start_description() },+ { value: 'stop', label: m.webhook_action_type_stop(), description: m.webhook_action_type_stop_description() },+ { value: 'restart', label: m.webhook_action_type_restart(), description: m.webhook_action_type_restart_description() },+ {+ value: 'redeploy',+ label: m.webhook_action_type_redeploy(),+ description: m.webhook_action_type_redeploy_description()+ }+ ];+ case 'project':+ return [+ { value: 'update', label: m.webhook_action_type_update(), description: m.webhook_action_type_update_description() },+ { value: 'up', label: m.webhook_action_type_up(), description: m.webhook_action_type_up_description() },+ { value: 'down', label: m.webhook_action_type_down(), description: m.webhook_action_type_down_description() },+ { value: 'restart', label: m.webhook_action_type_restart(), description: m.webhook_action_type_restart_description() },+ {+ value: 'redeploy',+ label: m.webhook_action_type_redeploy(),+ description: m.webhook_action_type_redeploy_description()+ }+ ];+ case 'updater':+ return [{ value: 'run', label: m.webhook_action_type_run(), description: m.webhook_action_type_run_description() }];+ case 'gitops':+ return [{ value: 'sync', label: m.webhook_action_type_sync(), description: m.webhook_action_type_sync_description() }];+ default:+ return [];+ }+ }++ let selectedTargetType = $state<WebhookTargetType>('container');+ let selectedActionType = $state<WebhookActionType>(getDefaultActionType('container'));+ let selectedTargetId = $state('');+ let targetOptions = $state<{ label: string; value: string }[]>([]);+ let targetOptionsLoading = $state(false);+ let loadGeneration = 0;+ let actionTypeOptions = $derived(getActionTypeOptions(selectedTargetType));++ const formSchema = z.object({+ name: z.string().min(1, m.common_field_required({ field: m.webhook_name_label() }))+ });++ let formData = $derived({ name: '' });+ let { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));++ async function loadTargetOptions(type: WebhookTargetType) {+ if (type === 'updater') {+ targetOptions = [];+ selectedTargetId = '';+ return;+ }++ const generation = ++loadGeneration;+ targetOptionsLoading = true;+ try {+ const envId = await environmentStore.getCurrentEnvironmentId();+ let options: { label: string; value: string }[] = [];+ if (type === 'container') {+ const res = await containerService.getContainersForEnvironment(envId, { pagination: { page: 1, limit: 200 } });+ options = res.data.map((c) => ({ value: c.id, label: c.names[0]?.replace(/^\//, '') ?? c.id }));+ } else if (type === 'project') {+ const res = await projectService.getProjectsForEnvironment(envId, { pagination: { page: 1, limit: 200 } });+ options = res.data.map((p) => ({ value: p.id, label: p.name }));+ } else if (type === 'gitops') {+ const res = await gitOpsSyncService.getSyncs(envId, { pagination: { page: 1, limit: 200 } });+ options = res.data.map((s) => ({ value: s.id, label: s.name }));+ }+ if (generation === loadGeneration) {+ targetOptions = options;+ selectedTargetId = options[0]?.value ?? '';+ }+ } catch {+ if (generation === loadGeneration) {+ targetOptions = [];+ }+ } finally {+ if (generation === loadGeneration) {+ targetOptionsLoading = false;+ }+ }+ }++ function handleTargetTypeChange(value: string) {+ selectedTargetType = value as WebhookTargetType;+ selectedActionType = getDefaultActionType(selectedTargetType);+ selectedTargetId = '';+ void loadTargetOptions(selectedTargetType);+ }++ function handleSubmit() {+ const data = form.validate();+ if (!data) return;+ if (selectedTargetType !== 'updater' && !selectedTargetId) return;++ onSubmit({+ name: data.name,+ targetType: selectedTargetType,+ actionType: selectedActionType,+ targetId: selectedTargetId+ });+ }++ function handleOpenChange(newOpenState: boolean) {+ open = newOpenState;+ if (newOpenState) {+ void loadTargetOptions(selectedTargetType);+ return;+ }+ if (!newOpenState) {+ selectedTargetType = 'container';+ selectedActionType = getDefaultActionType('container');+ selectedTargetId = '';+ targetOptions = [];+ }+ }+</script>++<ResponsiveDialog.Root+ {open}+ onOpenChange={handleOpenChange}+ variant="sheet"+ title={m.webhook_create_title()}+ description={m.webhook_create_description()}+ contentClass="sm:max-w-[500px]"+>+ {#snippet children()}+ <form onsubmit={preventDefault(handleSubmit)} class="grid gap-4 py-6">+ <FormInput+ label={m.webhook_name_label()}+ type="text"+ placeholder={m.webhook_name_placeholder()}+ description={m.webhook_name_description()}+ bind:input={$inputs.name}+ />++ <SelectWithLabel+ id="webhook-target-type"+ label={m.webhook_target_type_label()}+ description={m.webhook_target_type_description()}+ value={selectedTargetType}+ options={targetTypeOptions}+ onValueChange={handleTargetTypeChange}+ />++ <SelectWithLabel+ id="webhook-action-type"+ label={m.webhook_action_type_label()}+ description={m.webhook_action_type_description()}+ value={selectedActionType}+ options={actionTypeOptions}+ onValueChange={(value) => (selectedActionType = value as WebhookActionType)}+ disabled={actionTypeOptions.length === 1}+ />++ {#if selectedTargetType !== 'updater'}+ <SelectWithLabel+ id="webhook-target-id"+ label={selectedTargetType === 'container'+ ? m.webhook_target_resource_label_container()+ : selectedTargetType === 'project'+ ? m.webhook_target_resource_label_project()+ : m.webhook_target_resource_label_gitops()}+ description={m.webhook_target_resource_description()}+ bind:value={selectedTargetId}+ options={targetOptions}+ disabled={targetOptionsLoading || targetOptions.length === 0}+ placeholder={targetOptionsLoading ? m.webhook_target_resource_loading() : m.webhook_target_resource_placeholder()}+ />+ {/if}+ </form>+ {/snippet}++ {#snippet footer()}+ <div class="flex w-full flex-row gap-2">+ <ArcaneButton+ action="cancel"+ tone="outline"+ type="button"+ class="flex-1"+ onclick={() => (open = false)}+ disabled={isLoading}+ />+ <ArcaneButton+ action="create"+ type="submit"+ class="flex-1"+ disabled={isLoading || (selectedTargetType !== 'updater' && !selectedTargetId)}+ loading={isLoading}+ onclick={handleSubmit}+ customLabel={m.webhook_create_button()}+ />+ </div>+ {/snippet}+</ResponsiveDialog.Root>diff --git a/frontend/src/lib/config/navigation-config.ts b/frontend/src/lib/config/navigation-config.tsindex 5e1e73b1d..fd0f870ef 100644--- a/frontend/src/lib/config/navigation-config.ts+++ b/frontend/src/lib/config/navigation-config.ts@@ -21,7 +21,8 @@ import {GitBranchIcon,ShieldAlertIcon,HammerIcon,- TemplateIcon+ TemplateIcon,+ GlobeIcon} from '$lib/icons';import { m } from '$lib/paraglide/messages';import type { ShortcutKey } from '$lib/utils/keyboard-shortcut.utils';@@ -90,6 +91,7 @@ export const navigationItems: NavigationSections = {shortcut: ['mod', '0'],items: [{ title: m.api_key_page_title(), url: '/settings/api-keys', icon: ApiKeyIcon, shortcut: ['mod', 'shift', '1'] },+ { title: m.webhook_page_title(), url: '/settings/webhooks', icon: GlobeIcon },{ title: m.appearance_title(), url: '/settings/appearance', icon: ApperanceIcon, shortcut: ['mod', 'shift', '2'] },{title: m.authentication_title(),diff --git a/frontend/src/lib/services/webhook-service.ts b/frontend/src/lib/services/webhook-service.tsnew file mode 100644index 000000000..88e371689--- /dev/null+++ b/frontend/src/lib/services/webhook-service.ts@@ -0,0 +1,32 @@+import BaseAPIService from './api-service';+import { environmentStore } from '$lib/stores/environment.store.svelte';+import type { Webhook, WebhookCreated, CreateWebhook, UpdateWebhook } from '$lib/types/webhook.type';++export default class WebhookAPIService extends BaseAPIService {+ private async resolveEnvironmentId(environmentId?: string): Promise<string> {+ return environmentId ?? (await environmentStore.getCurrentEnvironmentId());+ }++ async getWebhooks(environmentId?: string): Promise<Webhook[]> {+ const envId = await this.resolveEnvironmentId(environmentId);+ const res = await this.api.get(`/environments/${envId}/webhooks`);+ return res.data.data;+ }++ async create(webhook: CreateWebhook, environmentId?: string): Promise<WebhookCreated> {+ const envId = await this.resolveEnvironmentId(environmentId);+ return this.handleResponse(this.api.post(`/environments/${envId}/webhooks`, webhook)) as Promise<WebhookCreated>;+ }++ async update(webhookId: string, data: UpdateWebhook, environmentId?: string): Promise<Webhook> {+ const envId = await this.resolveEnvironmentId(environmentId);+ return this.handleResponse(this.api.patch(`/environments/${envId}/webhooks/${webhookId}`, data)) as Promise<Webhook>;+ }++ async delete(webhookId: string, environmentId?: string): Promise<void> {+ const envId = await this.resolveEnvironmentId(environmentId);+ return this.handleResponse(this.api.delete(`/environments/${envId}/webhooks/${webhookId}`)) as Promise<void>;+ }+}++export const webhookService = new WebhookAPIService();diff --git a/frontend/src/lib/types/webhook.type.ts b/frontend/src/lib/types/webhook.type.tsnew file mode 100644index 000000000..2d7aa65cc--- /dev/null+++ b/frontend/src/lib/types/webhook.type.ts@@ -0,0 +1,37 @@+export type WebhookTargetType = 'container' | 'project' | 'updater' | 'gitops';+export type WebhookActionType = 'update' | 'start' | 'stop' | 'restart' | 'redeploy' | 'up' | 'down' | 'run' | 'sync';++export type Webhook = {+ id: string;+ name: string;+ tokenPrefix: string;+ targetType: WebhookTargetType;+ actionType: WebhookActionType;+ targetId: string;+ targetName?: string;+ environmentId: string;+ enabled: boolean;+ lastTriggeredAt?: string;+ createdAt: string;+};++export type WebhookCreated = {+ id: string;+ name: string;+ token: string;+ targetType: WebhookTargetType;+ actionType: WebhookActionType;+ targetId: string;+ createdAt: string;+};++export type CreateWebhook = {+ name: string;+ targetType: WebhookTargetType;+ actionType: WebhookActionType;+ targetId: string;+};++export type UpdateWebhook = {+ enabled: boolean;+};diff --git a/frontend/src/routes/(app)/settings/+layout.svelte b/frontend/src/routes/(app)/settings/+layout.svelteindex 77014221f..b1ea724f0 100644--- a/frontend/src/routes/(app)/settings/+layout.svelte+++ b/frontend/src/routes/(app)/settings/+layout.svelte@@ -149,6 +149,8 @@return m.notifications_title();case 'api-keys':return m.api_key_page_title();+ case 'webhooks':+ return m.webhook_page_title();case 'build':return 'Build';default:diff --git a/frontend/src/routes/(app)/settings/+page.svelte b/frontend/src/routes/(app)/settings/+page.svelteindex 5c8f0ceea..10dc8a106 100644--- a/frontend/src/routes/(app)/settings/+page.svelte+++ b/frontend/src/routes/(app)/settings/+page.svelte@@ -14,7 +14,8 @@ApperanceIcon,CloseIcon,JobsIcon,- CodeIcon+ CodeIcon,+ GlobeIcon} from '$lib/icons';import { ArcaneButton } from '$lib/components/arcane-button/index.js';import { Card } from '$lib/components/ui/card';@@ -44,7 +45,8 @@user: UserIcon,apikey: ApiKeyIcon,jobs: JobsIcon,- code: CodeIcon+ code: CodeIcon,+ globe: GlobeIcon};onMount(async () => {diff --git a/frontend/src/routes/(app)/settings/webhooks/+page.svelte b/frontend/src/routes/(app)/settings/webhooks/+page.sveltenew file mode 100644index 000000000..37158b269--- /dev/null+++ b/frontend/src/routes/(app)/settings/webhooks/+page.svelte@@ -0,0 +1,119 @@+<script lang="ts">+ import { toast } from 'svelte-sonner';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';+ import { tryCatch } from '$lib/utils/try-catch';+ import WebhookTable from './webhook-table.svelte';+ import WebhookFormSheet from '$lib/components/sheets/webhook-form-sheet.svelte';+ import type { Webhook, WebhookCreated, CreateWebhook } from '$lib/types/webhook.type';+ import { webhookService } from '$lib/services/webhook-service';+ import { SettingsPageLayout, type SettingsActionButton } from '$lib/layouts/index.js';+ import * as ResponsiveDialog from '$lib/components/ui/responsive-dialog/index.js';+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';+ import { Snippet } from '$lib/components/ui/snippet/index.js';+ import { untrack } from 'svelte';+ import { GlobeIcon } from '$lib/icons';+ import * as m from '$lib/paraglide/messages.js';++ let { data } = $props();++ let webhooks = $state<Webhook[]>(untrack(() => data.webhooks));++ let isDialogOpen = $state({+ create: false,+ showToken: false+ });++ let newlyCreatedWebhook = $state<WebhookCreated | null>(null);++ let isLoading = $state({ creating: false });++ let newlyCreatedWebhookUrl = $derived.by(() => {+ if (!newlyCreatedWebhook?.token) {+ return '';+ }++ const origin = globalThis.location?.origin ?? '';+ return `${origin}/api/webhooks/trigger/${encodeURIComponent(newlyCreatedWebhook.token)}`;+ });++ async function handleCreateWebhook(webhook: CreateWebhook) {+ isLoading.creating = true;+ const result = await tryCatch(webhookService.create(webhook));+ handleApiResultWithCallbacks({+ result,+ message: m.webhook_create_failed({ name: webhook.name }),+ setLoadingState: (value) => (isLoading.creating = value),+ onSuccess: async (created) => {+ toast.success(m.webhook_create_success({ name: webhook.name }));+ webhooks = await webhookService.getWebhooks();+ isDialogOpen.create = false;+ newlyCreatedWebhook = created as WebhookCreated;+ isDialogOpen.showToken = true;+ }+ });+ }++ const actionButtons: SettingsActionButton[] = $derived.by(() => [+ {+ id: 'create',+ action: 'create',+ label: m.webhook_create_button(),+ onclick: () => (isDialogOpen.create = true),+ loading: isLoading.creating,+ disabled: isLoading.creating+ }+ ]);+</script>++<SettingsPageLayout+ title={m.webhook_page_title()}+ description={m.webhook_page_description()}+ icon={GlobeIcon}+ pageType="management"+ {actionButtons}+>+ {#snippet mainContent()}+ <WebhookTable+ bind:webhooks+ onWebhooksChanged={async () => {+ webhooks = await webhookService.getWebhooks();+ }}+ />+ {/snippet}++ {#snippet additionalContent()}+ <WebhookFormSheet bind:open={isDialogOpen.create} onSubmit={handleCreateWebhook} isLoading={isLoading.creating} />++ <ResponsiveDialog.Root+ bind:open={isDialogOpen.showToken}+ title={m.webhook_created_title()}+ description={m.webhook_created_description()}+ contentClass="!max-w-fit"+ >+ {#snippet children()}+ <div class="space-y-4 py-4">+ <div class="bg-muted rounded-lg p-4">+ <p class="text-muted-foreground mb-2 text-sm font-medium">{m.webhook_token_label()}</p>+ <Snippet+ text={newlyCreatedWebhookUrl}+ onCopy={(status) => {+ if (status === 'success') {+ toast.success(m.webhook_token_copied());+ }+ }}+ />+ </div>+ <div class="rounded-lg border border-yellow-200 bg-yellow-50 p-4 dark:border-yellow-800 dark:bg-yellow-900/20">+ <p class="text-sm text-yellow-800 dark:text-yellow-200">+ <strong>{m.common_important()}:</strong>+ {m.webhook_token_warning()}+ </p>+ </div>+ </div>+ {/snippet}+ {#snippet footer()}+ <ArcaneButton action="confirm" onclick={() => (isDialogOpen.showToken = false)} customLabel={m.common_done()} />+ {/snippet}+ </ResponsiveDialog.Root>+ {/snippet}+</SettingsPageLayout>diff --git a/frontend/src/routes/(app)/settings/webhooks/+page.ts b/frontend/src/routes/(app)/settings/webhooks/+page.tsnew file mode 100644index 000000000..d61f99503--- /dev/null+++ b/frontend/src/routes/(app)/settings/webhooks/+page.ts@@ -0,0 +1,7 @@+import { webhookService } from '$lib/services/webhook-service';+import type { PageLoad } from './$types';++export const load: PageLoad = async () => {+ const webhooks = await webhookService.getWebhooks();+ return { webhooks };+};diff --git a/frontend/src/routes/(app)/settings/webhooks/webhook-table.svelte b/frontend/src/routes/(app)/settings/webhooks/webhook-table.sveltenew file mode 100644index 000000000..21f82aaf1--- /dev/null+++ b/frontend/src/routes/(app)/settings/webhooks/webhook-table.svelte@@ -0,0 +1,312 @@+<script lang="ts">+ import ArcaneTable from '$lib/components/arcane-table/arcane-table.svelte';+ import { UniversalMobileCard } from '$lib/components/arcane-table';+ import type { ColumnSpec, MobileFieldVisibility } from '$lib/components/arcane-table';+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';+ import StatusBadge from '$lib/components/badges/status-badge.svelte';+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';+ import { CopyButton } from '$lib/components/ui/copy-button';+ import { toast } from 'svelte-sonner';+ import { openConfirmDialog } from '$lib/components/confirm-dialog';+ import { handleApiResultWithCallbacks } from '$lib/utils/api.util';+ import { tryCatch } from '$lib/utils/try-catch';+ import type { Webhook } from '$lib/types/webhook.type';+ import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';+ import { webhookService } from '$lib/services/webhook-service';+ import { TrashIcon, EllipsisIcon, GlobeIcon } from '$lib/icons';+ import * as m from '$lib/paraglide/messages.js';++ let {+ webhooks = $bindable(),+ onWebhooksChanged+ }: {+ webhooks: Webhook[];+ onWebhooksChanged: () => Promise<void>;+ } = $props();++ let isLoading = $state({ removing: false, toggling: false });+ let requestOptions = $state<SearchPaginationSortRequest>({ pagination: { page: 1, limit: 20 } });+ let mobileFieldVisibility = $state<MobileFieldVisibility>({});++ function formatDate(dateString?: string): string {+ if (!dateString) return '-';+ return new Date(dateString).toLocaleString();+ }++ function targetTypeLabel(type: string): string {+ switch (type) {+ case 'container':+ return m.webhook_type_container();+ case 'project':+ return m.webhook_type_project();+ case 'updater':+ return m.webhook_type_updater();+ case 'gitops':+ return m.webhook_type_gitops();+ default:+ return type;+ }+ }++ function actionTypeLabel(type: string): string {+ switch (type) {+ case 'update':+ return m.webhook_action_type_update();+ case 'start':+ return m.webhook_action_type_start();+ case 'stop':+ return m.webhook_action_type_stop();+ case 'restart':+ return m.webhook_action_type_restart();+ case 'redeploy':+ return m.webhook_action_type_redeploy();+ case 'up':+ return m.webhook_action_type_up();+ case 'down':+ return m.webhook_action_type_down();+ case 'run':+ return m.webhook_action_type_run();+ case 'sync':+ return m.webhook_action_type_sync();+ default:+ return type;+ }+ }++ function targetNameLabel(webhook: Webhook): string {+ return webhook.targetName?.trim() || '-';+ }++ function webhookStatusLabel(webhook: Webhook): string {+ return webhook.enabled ? m.webhook_status_enabled() : m.webhook_status_disabled();+ }++ function webhookStatusVariant(webhook: Webhook): 'green' | 'gray' {+ return webhook.enabled ? 'green' : 'gray';+ }++ function buildWebhookTableData(items: Webhook[]): Paginated<Webhook> {+ return {+ data: items,+ pagination: {+ totalPages: 1,+ totalItems: items.length,+ currentPage: 1,+ itemsPerPage: Math.max(items.length, 1)+ }+ };+ }++ const tableData = $derived(buildWebhookTableData(webhooks));++ async function handleToggleWebhook(webhook: Webhook) {+ const name = webhook.name;+ const enabling = !webhook.enabled;+ isLoading.toggling = true;+ handleApiResultWithCallbacks({+ result: await tryCatch(webhookService.update(webhook.id, { enabled: enabling })),+ message: enabling ? m.webhook_enable_failed({ name }) : m.webhook_disable_failed({ name }),+ setLoadingState: (value) => (isLoading.toggling = value),+ onSuccess: async () => {+ toast.success(enabling ? m.webhook_enable_success({ name }) : m.webhook_disable_success({ name }));+ await onWebhooksChanged();+ }+ });+ }++ async function handleDeleteWebhook(webhookId: string, name: string) {+ openConfirmDialog({+ title: m.webhook_delete_title({ name }),+ message: m.webhook_delete_message({ name }),+ confirm: {+ label: m.common_delete(),+ destructive: true,+ action: async () => {+ isLoading.removing = true;+ handleApiResultWithCallbacks({+ result: await tryCatch(webhookService.delete(webhookId)),+ message: m.webhook_delete_failed({ name }),+ setLoadingState: (value) => (isLoading.removing = value),+ onSuccess: async () => {+ toast.success(m.webhook_delete_success({ name }));+ await onWebhooksChanged();+ }+ });+ }+ }+ });+ }++ const columns = [+ { accessorKey: 'name', title: m.webhook_col_name(), sortable: true, cell: NameCell },+ { accessorKey: 'enabled', title: m.webhook_col_status(), sortable: true, cell: StatusCell },+ { accessorKey: 'tokenPrefix', title: m.webhook_col_token_prefix(), sortable: true, cell: TokenPrefixCell },+ { accessorKey: 'targetType', title: m.webhook_col_target_type(), sortable: true, cell: TargetTypeCell },+ { accessorKey: 'actionType', title: m.webhook_col_action_type(), sortable: true, cell: ActionTypeCell },+ { accessorKey: 'targetName', title: m.webhook_col_target_name(), sortable: true, cell: TargetNameCell },+ { accessorKey: 'lastTriggeredAt', title: m.webhook_col_last_triggered(), sortable: true, cell: LastTriggeredCell },+ { accessorKey: 'createdAt', title: m.webhook_col_created(), sortable: true, cell: CreatedCell }+ ] satisfies ColumnSpec<Webhook>[];++ const mobileFields = [+ { id: 'enabled', label: m.webhook_col_status(), defaultVisible: true },+ { id: 'tokenPrefix', label: m.webhook_col_token_prefix(), defaultVisible: true },+ { id: 'targetType', label: m.webhook_col_target_type(), defaultVisible: true },+ { id: 'actionType', label: m.webhook_col_action_type(), defaultVisible: true },+ { id: 'targetName', label: m.webhook_col_target_name(), defaultVisible: true },+ { id: 'lastTriggeredAt', label: m.webhook_col_last_triggered(), defaultVisible: true },+ { id: 'createdAt', label: m.webhook_col_created(), defaultVisible: false }+ ];+</script>++{#if webhooks.length === 0}+ <div class="text-muted-foreground flex flex-col items-center justify-center py-12 text-sm">+ <GlobeIcon class="mb-3 size-10 opacity-40" />+ <p>{m.webhook_empty_title()}</p>+ <p class="mt-1">{m.webhook_empty_description()}</p>+ </div>+{:else}+ <ArcaneTable+ persistKey="arcane-webhooks-table"+ items={tableData}+ bind:requestOptions+ bind:mobileFieldVisibility+ selectionDisabled={true}+ withoutSearch+ withoutPagination+ onRefresh={async () => {+ await onWebhooksChanged();+ return buildWebhookTableData(webhooks);+ }}+ {columns}+ {mobileFields}+ rowActions={RowActions}+ mobileCard={WebhookMobileCardSnippet}+ />+{/if}++{#snippet NameCell({ item }: { item: Webhook })}+ <span class="font-medium">{item.name}</span>+{/snippet}++{#snippet StatusCell({ item }: { item: Webhook })}+ <StatusBadge text={webhookStatusLabel(item)} variant={webhookStatusVariant(item)} />+{/snippet}++{#snippet TokenPrefixCell({ item }: { item: Webhook })}+ <div class="flex items-center gap-2">+ <code class="bg-muted rounded px-2 py-1 text-xs">{item.tokenPrefix}...</code>+ <CopyButton text={item.tokenPrefix} class="size-6" />+ </div>+{/snippet}++{#snippet TargetTypeCell({ item }: { item: Webhook })}+ <span class="bg-muted rounded px-2 py-1 text-xs font-medium">{targetTypeLabel(item.targetType)}</span>+{/snippet}++{#snippet ActionTypeCell({ item }: { item: Webhook })}+ <span class="bg-muted rounded px-2 py-1 text-xs font-medium">{actionTypeLabel(item.actionType)}</span>+{/snippet}++{#snippet TargetNameCell({ item }: { item: Webhook })}+ <span class="text-muted-foreground">{targetNameLabel(item)}</span>+{/snippet}++{#snippet LastTriggeredCell({ item }: { item: Webhook })}+ <span class="text-muted-foreground">{formatDate(item.lastTriggeredAt)}</span>+{/snippet}++{#snippet CreatedCell({ item }: { item: Webhook })}+ <span class="text-muted-foreground">{formatDate(item.createdAt)}</span>+{/snippet}++{#snippet WebhookMobileCardSnippet({+ item,+ mobileFieldVisibility+}: {+ item: Webhook;+ mobileFieldVisibility: MobileFieldVisibility;+})}+ <UniversalMobileCard+ {item}+ icon={{ component: GlobeIcon, variant: 'blue' }}+ title={(item: Webhook) => item.name}+ subtitle={(item: Webhook) => ((mobileFieldVisibility['targetName'] ?? true) ? targetNameLabel(item) : null)}+ badges={[+ (item: Webhook) => ({+ variant: webhookStatusVariant(item),+ text: webhookStatusLabel(item)+ })+ ]}+ fields={[+ {+ label: m.webhook_col_token_prefix(),+ getValue: (item: Webhook) => `${item.tokenPrefix}...`,+ icon: GlobeIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility['tokenPrefix'] ?? true+ },+ {+ label: m.webhook_col_target_type(),+ getValue: (item: Webhook) => targetTypeLabel(item.targetType),+ icon: GlobeIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility['targetType'] ?? true+ },+ {+ label: m.webhook_col_action_type(),+ getValue: (item: Webhook) => actionTypeLabel(item.actionType),+ icon: GlobeIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility['actionType'] ?? true+ },+ {+ label: m.webhook_col_target_name(),+ getValue: (item: Webhook) => targetNameLabel(item),+ icon: GlobeIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility['targetName'] ?? true+ },+ {+ label: m.webhook_col_last_triggered(),+ getValue: (item: Webhook) => formatDate(item.lastTriggeredAt),+ icon: GlobeIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility['lastTriggeredAt'] ?? true+ },+ {+ label: m.webhook_col_created(),+ getValue: (item: Webhook) => formatDate(item.createdAt),+ icon: GlobeIcon,+ iconVariant: 'gray' as const,+ show: mobileFieldVisibility['createdAt'] ?? false+ }+ ]}+ rowActions={RowActions}+ />+{/snippet}++{#snippet RowActions({ item }: { item: Webhook })}+ <DropdownMenu.Root>+ <DropdownMenu.Trigger>+ {#snippet child({ props })}+ <ArcaneButton {...props} action="base" tone="ghost" size="icon" class="size-8">+ <span class="sr-only">{m.common_open_menu()}</span>+ <EllipsisIcon class="size-4" />+ </ArcaneButton>+ {/snippet}+ </DropdownMenu.Trigger>+ <DropdownMenu.Content align="end">+ <DropdownMenu.Group>+ <DropdownMenu.Item onclick={() => handleToggleWebhook(item)} disabled={isLoading.toggling}>+ {item.enabled ? m.webhook_disable() : m.webhook_enable()}+ </DropdownMenu.Item>+ <DropdownMenu.Separator />+ <DropdownMenu.Item variant="destructive" onclick={() => handleDeleteWebhook(item.id, item.name)}>+ <TrashIcon class="size-4" />+ {m.common_delete()}+ </DropdownMenu.Item>+ </DropdownMenu.Group>+ </DropdownMenu.Content>+ </DropdownMenu.Root>+{/snippet}diff --git a/types/webhook/webhook.go b/types/webhook/webhook.gonew file mode 100644index 000000000..bd926c478--- /dev/null+++ b/types/webhook/webhook.go@@ -0,0 +1,42 @@+package webhook++import "time"++// CreateInput is the request body for creating a webhook.+type CreateInput struct {+ Name string `json:"name" minLength:"1" maxLength:"255" doc:"Human-readable name for this webhook"`+ TargetType string `json:"targetType" doc:"Resource type this webhook targets: 'container', 'project', 'updater', or 'gitops'" enum:"container,project,updater,gitops"`+ ActionType string `json:"actionType" doc:"Action to run for the selected target type. Supported values depend on targetType." enum:"update,start,stop,restart,redeploy,up,down,run,sync"`+ TargetID string `json:"targetId" doc:"Container ID, project ID, or GitOps sync ID to target. Leave empty for 'updater' webhooks."`+}++// Summary is returned in list responses — the token is masked.+type Summary struct {+ ID string `json:"id" doc:"Webhook ID"`+ Name string `json:"name" doc:"Webhook name"`+ TokenPrefix string `json:"tokenPrefix" doc:"Masked token prefix for identification"`+ TargetType string `json:"targetType" doc:"Target type: 'container', 'project', 'updater', or 'gitops'"`+ ActionType string `json:"actionType" doc:"Action type resolved for this webhook"`+ TargetID string `json:"targetId" doc:"Target resource ID"`+ TargetName string `json:"targetName,omitempty" doc:"Resolved target resource name when available"`+ EnvironmentID string `json:"environmentId" doc:"Environment ID"`+ Enabled bool `json:"enabled" doc:"Whether the webhook is active"`+ LastTriggeredAt *time.Time `json:"lastTriggeredAt,omitempty" doc:"Timestamp of last successful trigger"`+ CreatedAt time.Time `json:"createdAt" doc:"Creation timestamp"`+}++// UpdateInput is the request body for updating a webhook.+type UpdateInput struct {+ Enabled bool `json:"enabled" doc:"Whether the webhook is active"`+}++// Created is returned once when a webhook is first created, including the raw token.+type Created struct {+ ID string `json:"id" doc:"Webhook ID"`+ Name string `json:"name" doc:"Webhook name"`+ Token string `json:"token" doc:"Full webhook token — store this securely, it will not be shown again"`+ TargetType string `json:"targetType" doc:"Target type"`+ ActionType string `json:"actionType" doc:"Action type"`+ TargetID string `json:"targetId" doc:"Target resource ID"`+ CreatedAt time.Time `json:"createdAt" doc:"Creation timestamp"`+}