An open-source, faster Devin alternative
TypeScript
feat(webhooks): implement P1 sandbox lifecycle webhooks backend
Igor Zalutski8e10f15b73e4
diff --git a/.agents/work/sandbox-lifecycle-webhooks.md b/.agents/work/sandbox-lifecycle-webhooks.mdindex fa48c24f..0cf1c1b8 100644--- a/.agents/work/sandbox-lifecycle-webhooks.md+++ b/.agents/work/sandbox-lifecycle-webhooks.md@@ -1,9 +1,17 @@# Sandbox lifecycle webhooks — implementation plan-Status: **design draft, rev 3 (second review folded in 2026-06-24), implementation not-started** (off `main` @ `6ed835c`). Branch: `feat/sandbox-webhooks`. This is a **complete-reference** — a future implementer should be able to work from this doc + the cited code-without the conversation that produced it.+Status: **rev 6 — P1 backend IMPLEMENTED (2026-06-24)**, not yet deployed. Branch:+`feat/sandbox-webhooks`. This is a **complete reference** — a future implementer should be able+to work from this doc + the cited code without the conversation that produced it.++**P1 build landed** (migration `049_sandbox_webhooks`, `pkg/types/webhook.go`,+`internal/webhook/{sign,ssrf}.go` + tests, `internal/db/webhooks.go` + the in-tx CP-origin+capture in `store.go:UpdateSandboxSessionStatus`, `internal/api/webhooks.go` + routes ++inline-on-create, `internal/controlplane/{webhook_materializer,webhook_dispatcher,lifecycle_ingress}.go`,+wired in `cmd/server/main.go`). Builds + `go vet` clean; signing/SSRF unit tests pass. Reuses+the existing `crypto.Encryptor` (O5 ✓ — `OPENSANDBOX_SECRET_ENCRYPTION_KEY`). Remaining before+prod: end-to-end test on the single-host dev VM (★O9), then deploy + publish SDK/docs. P2/P3+polish (per-type payload normalization at the ingress, LISTEN/NOTIFY latency) tracked below.- **Rev 2** resolved the plumbing blockers — signing-secret behavior, source durability (dualprojection), Redis reclaim (XPENDING+XCLAIM), deterministic event IDs, the delivery statediff --git a/cmd/server/main.go b/cmd/server/main.goindex a1935ff9..aff803b8 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -286,6 +286,26 @@ func main() {cr.Start(context.Background())defer cr.Stop()}++ // Worker-origin webhook ingress — consumes the events:{cell_id} stream+ // and records canonical lifecycle events (created/ready/migrated) for+ // sandbox webhooks. CP-origin events (stopped/hibernated) are recorded+ // in-tx and don't need this. (.agents/work/sandbox-lifecycle-webhooks.md §5)+ if opts.Store != nil && cfg.CellID != "" {+ ingress, err := controlplane.NewLifecycleIngress(redisRegistry.RedisClient(), opts.Store, cfg.CellID)+ if err != nil {+ log.Fatalf("lifecycle_ingress: %v", err)+ }+ if err := ingress.Start(context.Background()); err != nil {+ log.Fatalf("lifecycle_ingress start: %v", err)+ }+ defer func() {+ stopCtx, stopCancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer stopCancel()+ _ = ingress.Stop(stopCtx)+ }()+ log.Printf("opensandbox: webhook lifecycle ingress started (cell=%s)", cfg.CellID)+ }}// Hoisted at function scope so the per-sandbox autoscaler (created@@ -859,6 +879,21 @@ func main() {senderOpts.Interval, senderOpts.Batch)}+ // Sandbox webhooks — the materializer (canonical events → delivery rows) and+ // the dispatcher (send/retry/dead-letter) need only Postgres, so they run in+ // any mode; the worker-origin ingress (started above, server mode) feeds them+ // the worker events. Dormant until a destination exists.+ // (.agents/work/sandbox-lifecycle-webhooks.md)+ if opts.Store != nil {+ mat := controlplane.NewWebhookMaterializer(opts.Store)+ mat.Start()+ defer mat.Stop()+ disp := controlplane.NewWebhookDispatcher(opts.Store, cfg.CellID)+ disp.Start()+ defer disp.Stop()+ log.Printf("opensandbox: sandbox webhook materializer + dispatcher started")+ }+// Start NATS sync consumer if both PG and NATS are configuredif opts.Store != nil && cfg.NATSURL != "" {consumer, err := db.NewSyncConsumer(opts.Store, cfg.NATSURL)diff --git a/internal/api/router.go b/internal/api/router.goindex 87df9046..76a902f9 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -430,6 +430,17 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, oapi.GET("/sandboxes/:id/tags", s.getSandboxTags)api.PUT("/sandboxes/:id/tags", s.putSandboxTags)+ // Sandbox lifecycle webhooks (.agents/work/sandbox-lifecycle-webhooks.md)+ api.POST("/webhooks", s.createWebhook)+ api.GET("/webhooks", s.listWebhooks)+ api.GET("/webhooks/:id", s.getWebhook)+ api.PATCH("/webhooks/:id", s.updateWebhook)+ api.DELETE("/webhooks/:id", s.deleteWebhook)+ api.POST("/webhooks/:id/test", s.testWebhook)+ api.GET("/webhooks/:id/deliveries", s.listWebhookDeliveries)+ api.GET("/webhooks/:id/deliveries/:deliveryId", s.getWebhookDelivery)+ api.POST("/webhooks/:id/deliveries/:deliveryId/redeliver", s.redeliverWebhookDelivery)+// Hibernationapi.POST("/sandboxes/:id/hibernate", s.hibernateSandbox)api.POST("/sandboxes/:id/wake", s.wakeSandbox)diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 5045e19e..657e2ae7 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -252,6 +252,12 @@ func (s *Server) createSandbox(c echo.Context) error {template = "default"}_, _ = s.store.CreateSandboxSession(ctx, sb.ID, orgID, auth.GetUserID(c), template, region, workerID, cfgJSON, metadataJSON, secretStoreID)++ // Inline webhooks: register them pinned to this sandbox so they catch+ // created/ready. Best-effort (see registerInlineWebhooks).+ if len(cfg.Webhooks) > 0 {+ sb.Webhooks = s.registerInlineWebhooks(ctx, orgID, sb.ID, cfg.Webhooks)+ }}// Preview-URL auth: same flow as createSandboxRemote — validate thediff --git a/internal/api/webhooks.go b/internal/api/webhooks.gonew file mode 100644index 00000000..a12f6203--- /dev/null+++ b/internal/api/webhooks.go@@ -0,0 +1,500 @@+package api++import (+ "bytes"+ "context"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "log"+ "net/http"+ "strconv"+ "time"++ "github.com/google/uuid"+ "github.com/labstack/echo/v4"+ "github.com/opensandbox/opensandbox/internal/auth"+ "github.com/opensandbox/opensandbox/internal/db"+ "github.com/opensandbox/opensandbox/internal/webhook"+ "github.com/opensandbox/opensandbox/pkg/types"+)++// Sandbox lifecycle webhooks — the org-scoped management API. Auth is the org+// API key (no granular scopes); ownership is enforced by org id on every query.+// See .agents/work/sandbox-lifecycle-webhooks.md.++const (+ webhookConnectTimeout = 10 * time.Second+ webhookSendTimeout = 15 * time.Second+)++// webhookCtx resolves the store + org id, writing the appropriate error response+// and returning ok=false if either is unavailable.+func (s *Server) webhookCtx(c echo.Context) (*db.Store, uuid.UUID, bool) {+ if s.store == nil {+ _ = c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "webhooks require the control-plane database"})+ return nil, uuid.Nil, false+ }+ orgID, ok := auth.GetOrgID(c)+ if !ok {+ _ = c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})+ return nil, uuid.Nil, false+ }+ return s.store, orgID, true+}++func webhookStoreError(c echo.Context, err error) error {+ switch {+ case errors.Is(err, db.ErrWebhookNotFound):+ return c.JSON(http.StatusNotFound, map[string]string{"error": "webhook not found"})+ case errors.Is(err, db.ErrWebhookNameConflict):+ return c.JSON(http.StatusConflict, map[string]string{"error": "a webhook with this name already exists with a different configuration"})+ case errors.Is(err, db.ErrWebhookIdempotencyConflict):+ return c.JSON(http.StatusConflict, map[string]string{"error": "Idempotency-Key reused with a different request"})+ case errors.Is(err, db.ErrEncryptionNotConfigured):+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "webhook secret encryption is not configured on this server"})+ default:+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+}++func toWireDestination(d *db.WebhookDestinationRow, secret string) types.WebhookDestination {+ et := d.EventTypes+ if et == nil {+ et = []string{}+ }+ return types.WebhookDestination{+ ID: d.ID,+ Name: d.Name,+ URL: d.URL,+ EventTypes: et,+ SandboxID: d.SandboxID,+ Enabled: d.Enabled,+ HasSecret: d.HasSecret,+ CreatedAt: d.CreatedAt,+ UpdatedAt: d.UpdatedAt,+ Secret: secret,+ }+}++func toWireDelivery(d *db.WebhookDeliveryRow) types.WebhookDelivery {+ return types.WebhookDelivery{+ ID: d.ID,+ Destination: d.DestinationID,+ EventID: d.EventID,+ EventType: d.EventType,+ Status: d.Status,+ Attempts: d.Attempts,+ RetryCount: d.RetryCount,+ LastAttemptAt: d.LastAttemptAt,+ ResponseCode: d.ResponseCode,+ Error: d.Error,+ CreatedAt: d.CreatedAt,+ UpdatedAt: d.UpdatedAt,+ DeliveredAt: d.DeliveredAt,+ }+}++// webhookRequestHash fingerprints a create request for Idempotency-Key matching.+func webhookRequestHash(req types.CreateWebhookRequest) string {+ h := sha256.New()+ fmt.Fprintf(h, "url=%s\n", req.URL)+ fmt.Fprintf(h, "eventTypes=%v\n", req.EventTypes)+ sb := ""+ if req.SandboxID != nil {+ sb = *req.SandboxID+ }+ fmt.Fprintf(h, "sandboxId=%s\n", sb)+ nm := ""+ if req.Name != nil {+ nm = *req.Name+ }+ fmt.Fprintf(h, "name=%s\n", nm)+ return hex.EncodeToString(h.Sum(nil))+}++// registerInlineWebhooks registers webhooks supplied inline on sandbox create,+// each pinned to the sandbox with no watermark floor (created_after_event_seq=0+// → full lifecycle from `created`). Best-effort: a bad URL or register error is+// logged and skipped rather than failing an already-created sandbox. Returns the+// results to echo on the create response (secret included once when generated).+func (s *Server) registerInlineWebhooks(ctx context.Context, orgID uuid.UUID, sandboxID string, specs []types.SandboxWebhookSpec) []types.SandboxWebhookResult {+ if s.store == nil || len(specs) == 0 {+ return nil+ }+ out := make([]types.SandboxWebhookResult, 0, len(specs))+ for _, spec := range specs {+ if spec.URL == "" {+ continue+ }+ if err := webhook.ValidateURL(ctx, spec.URL); err != nil {+ log.Printf("sandbox %s: skipping inline webhook %q: %v", sandboxID, spec.URL, err)+ continue+ }+ secret := spec.Secret+ generated := false+ if secret == "" {+ gen, err := webhook.GenerateSecret()+ if err != nil {+ log.Printf("sandbox %s: inline webhook secret generation failed: %v", sandboxID, err)+ continue+ }+ secret = gen+ generated = true+ }+ sid := sandboxID+ row, _, err := s.store.CreateWebhookDestination(ctx, db.CreateDestinationParams{+ OrgID: orgID,+ URL: spec.URL,+ EventTypes: spec.EventTypes,+ SandboxID: &sid,+ Enabled: true,+ SecretPlain: secret,+ CreatedAfterEventSeq: 0,+ })+ if err != nil {+ log.Printf("sandbox %s: inline webhook register failed: %v", sandboxID, err)+ continue+ }+ res := types.SandboxWebhookResult{ID: row.ID, URL: row.URL}+ if generated {+ res.Secret = secret+ }+ out = append(out, res)+ }+ return out+}++// POST /api/webhooks+func (s *Server) createWebhook(c echo.Context) error {+ store, orgID, ok := s.webhookCtx(c)+ if !ok {+ return nil+ }+ ctx := c.Request().Context()+ var req types.CreateWebhookRequest+ if err := c.Bind(&req); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body: " + err.Error()})+ }+ if req.URL == "" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "url is required"})+ }+ if err := webhook.ValidateURL(ctx, req.URL); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid webhook url: " + err.Error()})+ }++ idemKey := c.Request().Header.Get("Idempotency-Key")+ reqHash := webhookRequestHash(req)+ if idemKey != "" {+ stored, found, err := store.GetWebhookIdempotentResponse(ctx, orgID, idemKey, reqHash)+ if err != nil {+ return webhookStoreError(c, err)+ }+ if found {+ return c.JSONBlob(http.StatusCreated, stored)+ }+ }++ secret := req.Secret+ generated := false+ if secret == "" {+ gen, err := webhook.GenerateSecret()+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to generate signing secret"})+ }+ secret = gen+ generated = true+ }+ enabled := true+ if req.Enabled != nil {+ enabled = *req.Enabled+ }+ seq, err := store.CurrentLifecycleSeq(ctx)+ if err != nil {+ return webhookStoreError(c, err)+ }++ row, reused, err := store.CreateWebhookDestination(ctx, db.CreateDestinationParams{+ OrgID: orgID,+ Name: req.Name,+ URL: req.URL,+ EventTypes: req.EventTypes,+ SandboxID: req.SandboxID,+ Enabled: enabled,+ SecretPlain: secret,+ CreatedAfterEventSeq: seq,+ })+ if err != nil {+ return webhookStoreError(c, err)+ }+ if reused {+ // Name matched an existing destination — return it without a secret.+ return c.JSON(http.StatusOK, toWireDestination(row, ""))+ }++ echoSecret := ""+ if generated {+ echoSecret = secret+ }+ resp := toWireDestination(row, echoSecret)+ if idemKey != "" {+ body, _ := json.Marshal(resp)+ _ = store.PutWebhookIdempotentResponse(ctx, orgID, idemKey, reqHash, row.ID, body)+ }+ return c.JSON(http.StatusCreated, resp)+}++// GET /api/webhooks+func (s *Server) listWebhooks(c echo.Context) error {+ store, orgID, ok := s.webhookCtx(c)+ if !ok {+ return nil+ }+ rows, err := store.ListWebhookDestinations(c.Request().Context(), orgID)+ if err != nil {+ return webhookStoreError(c, err)+ }+ out := make([]types.WebhookDestination, 0, len(rows))+ for _, r := range rows {+ out = append(out, toWireDestination(r, ""))+ }+ return c.JSON(http.StatusOK, out)+}++// GET /api/webhooks/:id+func (s *Server) getWebhook(c echo.Context) error {+ store, orgID, ok := s.webhookCtx(c)+ if !ok {+ return nil+ }+ row, err := store.GetWebhookDestination(c.Request().Context(), orgID, c.Param("id"))+ if err != nil {+ return webhookStoreError(c, err)+ }+ return c.JSON(http.StatusOK, toWireDestination(row, ""))+}++// PATCH /api/webhooks/:id+func (s *Server) updateWebhook(c echo.Context) error {+ store, orgID, ok := s.webhookCtx(c)+ if !ok {+ return nil+ }+ ctx := c.Request().Context()+ id := c.Param("id")++ raw := map[string]json.RawMessage{}+ if err := json.NewDecoder(c.Request().Body).Decode(&raw); err != nil && !errors.Is(err, io.EOF) {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body: " + err.Error()})+ }+ if _, present := raw["sandboxId"]; present {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "sandboxId (scope) is immutable and cannot be changed"})+ }++ var p db.UpdateDestinationParams+ badField := func(field string) error {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid value for " + field})+ }+ if v, present := raw["url"]; present {+ var u string+ if err := json.Unmarshal(v, &u); err != nil {+ return badField("url")+ }+ if err := webhook.ValidateURL(ctx, u); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid webhook url: " + err.Error()})+ }+ p.URL = &u+ }+ if v, present := raw["eventTypes"]; present {+ if string(v) == "null" {+ p.ClearEventTypes = true+ } else {+ var et []string+ if err := json.Unmarshal(v, &et); err != nil {+ return badField("eventTypes")+ }+ if len(et) == 0 {+ p.ClearEventTypes = true+ } else {+ p.EventTypes = &et+ }+ }+ }+ if v, present := raw["enabled"]; present {+ var b bool+ if err := json.Unmarshal(v, &b); err != nil {+ return badField("enabled")+ }+ p.Enabled = &b+ }+ if v, present := raw["name"]; present {+ var n string+ if err := json.Unmarshal(v, &n); err != nil {+ return badField("name")+ }+ p.Name = &n+ }+ if v, present := raw["secret"]; present {+ var sec string+ if err := json.Unmarshal(v, &sec); err != nil {+ return badField("secret")+ }+ if sec != "" {+ p.NewSecretPlain = &sec+ }+ }+ generated := false+ if v, present := raw["rotateSecret"]; present {+ var rot bool+ if err := json.Unmarshal(v, &rot); err != nil {+ return badField("rotateSecret")+ }+ if rot {+ gen, err := webhook.GenerateSecret()+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to generate signing secret"})+ }+ p.NewSecretPlain = &gen+ generated = true+ }+ }++ row, err := store.UpdateWebhookDestination(ctx, orgID, id, p)+ if err != nil {+ return webhookStoreError(c, err)+ }+ echoSecret := ""+ if generated && p.NewSecretPlain != nil {+ echoSecret = *p.NewSecretPlain+ }+ return c.JSON(http.StatusOK, toWireDestination(row, echoSecret))+}++// DELETE /api/webhooks/:id+func (s *Server) deleteWebhook(c echo.Context) error {+ store, orgID, ok := s.webhookCtx(c)+ if !ok {+ return nil+ }+ if err := store.SoftDeleteWebhookDestination(c.Request().Context(), orgID, c.Param("id")); err != nil {+ return webhookStoreError(c, err)+ }+ return c.NoContent(http.StatusNoContent)+}++// POST /api/webhooks/:id/test — synchronous connectivity check. Bypasses the+// event-type filter, creates no delivery row, and is not retried.+func (s *Server) testWebhook(c echo.Context) error {+ store, orgID, ok := s.webhookCtx(c)+ if !ok {+ return nil+ }+ ctx := c.Request().Context()+ id := c.Param("id")+ dest, err := store.GetWebhookDestination(ctx, orgID, id)+ if err != nil {+ return webhookStoreError(c, err)+ }+ secret, err := store.GetWebhookDestinationSecret(ctx, id)+ if err != nil {+ return webhookStoreError(c, err)+ }++ sandboxID := ""+ if dest.SandboxID != nil {+ sandboxID = *dest.SandboxID+ }+ deliveryID := "whd_test_" + uuid.NewString()+ now := time.Now().UTC()+ env := types.SandboxWebhookEnvelope{+ Type: types.WebhookEventTest,+ SandboxID: sandboxID,+ EventID: "evt_test",+ DeliveryID: deliveryID,+ Event: types.SandboxLifecycleEvent{+ ID: "evt_test",+ Ts: now,+ OrgID: orgID.String(),+ SandboxID: sandboxID,+ Type: types.WebhookEventTest,+ Data: json.RawMessage(`{"message":"Test event from OpenComputer."}`),+ },+ }+ body, _ := json.Marshal(env)++ headers := webhook.Headers(secret, deliveryID, sandboxID, now.Unix(), body)+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, dest.URL, bytes.NewReader(body))+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid destination url"})+ }+ for k, v := range headers {+ req.Header.Set(k, v)+ }++ client := webhook.SafeClient(webhookConnectTimeout, webhookSendTimeout)+ resp, err := client.Do(req)+ result := types.WebhookTestResult{}+ if err != nil {+ result.Delivered = false+ result.Error = err.Error()+ return c.JSON(http.StatusOK, result)+ }+ defer resp.Body.Close()+ _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64*1024))+ code := resp.StatusCode+ result.ResponseCode = &code+ result.Delivered = code >= 200 && code < 300+ if !result.Delivered {+ result.Error = fmt.Sprintf("non-2xx response: %d", code)+ }+ return c.JSON(http.StatusOK, result)+}++// GET /api/webhooks/:id/deliveries+func (s *Server) listWebhookDeliveries(c echo.Context) error {+ store, orgID, ok := s.webhookCtx(c)+ if !ok {+ return nil+ }+ limit, _ := strconv.Atoi(c.QueryParam("limit"))+ rows, next, hasMore, err := store.ListWebhookDeliveries(+ c.Request().Context(), orgID, c.Param("id"),+ c.QueryParam("status"), c.QueryParam("cursor"), limit)+ if err != nil {+ return webhookStoreError(c, err)+ }+ data := make([]types.WebhookDelivery, 0, len(rows))+ for _, r := range rows {+ data = append(data, toWireDelivery(r))+ }+ return c.JSON(http.StatusOK, types.WebhookDeliveryPage{Data: data, NextCursor: next, HasMore: hasMore})+}++// GET /api/webhooks/:id/deliveries/:deliveryId+func (s *Server) getWebhookDelivery(c echo.Context) error {+ store, orgID, ok := s.webhookCtx(c)+ if !ok {+ return nil+ }+ row, err := store.GetWebhookDelivery(c.Request().Context(), orgID, c.Param("id"), c.Param("deliveryId"))+ if err != nil {+ return webhookStoreError(c, err)+ }+ return c.JSON(http.StatusOK, toWireDelivery(row))+}++// POST /api/webhooks/:id/deliveries/:deliveryId/redeliver+func (s *Server) redeliverWebhookDelivery(c echo.Context) error {+ store, orgID, ok := s.webhookCtx(c)+ if !ok {+ return nil+ }+ row, err := store.RedeliverDelivery(c.Request().Context(), orgID, c.Param("id"), c.Param("deliveryId"))+ if err != nil {+ return webhookStoreError(c, err)+ }+ return c.JSON(http.StatusAccepted, toWireDelivery(row))+}diff --git a/internal/controlplane/lifecycle_ingress.go b/internal/controlplane/lifecycle_ingress.gonew file mode 100644index 00000000..a362eda0--- /dev/null+++ b/internal/controlplane/lifecycle_ingress.go@@ -0,0 +1,296 @@+package controlplane++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "log"+ "os"+ "sync"+ "time"++ "github.com/google/uuid"+ "github.com/redis/go-redis/v9"++ "github.com/opensandbox/opensandbox/internal/db"+ "github.com/opensandbox/opensandbox/pkg/types"+)++// LifecycleIngress is the worker-origin half of the webhook pipeline: it consumes+// the events:{cell_id} Redis stream with its own consumer group and materializes+// the webhook-eligible worker events into the canonical sandbox_lifecycle_events+// table (via the single recordLifecycleEvent primitive). CP-origin events+// (stopped/hibernated/resumed) are recorded in-tx and are intentionally NOT+// handled here — this consumer maps only the worker-origin types below.+//+// Independent of EventForwarder's consumer group (each group gets its own copy of+// the stream). Reclaim mirrors event_forwarder: plain XPENDING + XCLAIM JUSTID+// (Azure Redis 6.0 lacks XAUTOCLAIM). See §5 / §12 of the design doc.+type LifecycleIngress struct {+ rdb *redis.Client+ store *db.Store+ streamKey string+ groupName string+ consumer string+ batchSize int64+ blockDur time.Duration++ stopCh chan struct{}+ doneCh chan struct{}+ wg sync.WaitGroup+ once sync.Once+}++// ingressTypeMap maps the internal worker event strings to public lifecycle+// types. Only these worker-origin events become webhooks via the ingress; every+// other stream entry is acked and ignored by this consumer group.+var ingressTypeMap = map[string]string{+ "created": types.WebhookEventCreated,+ "running": types.WebhookEventReady,+ "migrated": types.WebhookEventMigrated,+}++// streamLifecycleEnvelope is the subset of the stream "event" payload we need.+// Both the worker publisher and the CP PublishLifecycle helper share these keys.+type streamLifecycleEnvelope struct {+ ID string `json:"id"`+ Type string `json:"type"`+ SandboxID string `json:"sandbox_id"`+ OrgID string `json:"org_id"`+ Payload json.RawMessage `json:"payload"`+ Timestamp string `json:"timestamp"`+}++// NewLifecycleIngress constructs the ingress. Caller must Start it. Requires a+// Redis client (server mode) and the cell id (the stream is events:{cellID}).+func NewLifecycleIngress(rdb *redis.Client, store *db.Store, cellID string) (*LifecycleIngress, error) {+ if rdb == nil {+ return nil, errors.New("lifecycle_ingress: Redis client required")+ }+ if store == nil {+ return nil, errors.New("lifecycle_ingress: store required")+ }+ if cellID == "" {+ return nil, errors.New("lifecycle_ingress: cellID required")+ }+ host, _ := os.Hostname()+ return &LifecycleIngress{+ rdb: rdb,+ store: store,+ streamKey: "events:" + cellID,+ groupName: "webhook-ingress",+ consumer: fmt.Sprintf("%s-%d", host, os.Getpid()),+ batchSize: 200,+ blockDur: 5 * time.Second,+ stopCh: make(chan struct{}),+ doneCh: make(chan struct{}),+ }, nil+}++func (g *LifecycleIngress) Start(ctx context.Context) error {+ if err := g.rdb.XGroupCreateMkStream(ctx, g.streamKey, g.groupName, "$").Err(); err != nil {+ if !isBusyGroup(err) {+ return fmt.Errorf("lifecycle_ingress: create consumer group: %w", err)+ }+ }+ g.wg.Add(2)+ go g.readLoop(ctx)+ go g.reclaimLoop(ctx)+ go func() {+ g.wg.Wait()+ close(g.doneCh)+ }()+ log.Printf("lifecycle_ingress: started (stream=%s group=%s consumer=%s)", g.streamKey, g.groupName, g.consumer)+ return nil+}++func (g *LifecycleIngress) Stop(ctx context.Context) error {+ g.once.Do(func() { close(g.stopCh) })+ select {+ case <-g.doneCh:+ case <-ctx.Done():+ return ctx.Err()+ }+ return nil+}++func (g *LifecycleIngress) readLoop(ctx context.Context) {+ defer g.wg.Done()+ for {+ select {+ case <-ctx.Done():+ return+ case <-g.stopCh:+ return+ default:+ }+ streams, err := g.rdb.XReadGroup(ctx, &redis.XReadGroupArgs{+ Group: g.groupName,+ Consumer: g.consumer,+ Streams: []string{g.streamKey, ">"},+ Count: g.batchSize,+ Block: g.blockDur,+ }).Result()+ if err != nil {+ if errors.Is(err, redis.Nil) || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {+ continue+ }+ log.Printf("lifecycle_ingress: XREADGROUP error: %v", err)+ select {+ case <-time.After(2 * time.Second):+ case <-ctx.Done():+ return+ case <-g.stopCh:+ return+ }+ continue+ }+ for _, s := range streams {+ for _, m := range s.Messages {+ g.process(ctx, m)+ }+ }+ }+}++func (g *LifecycleIngress) reclaimLoop(ctx context.Context) {+ defer g.wg.Done()+ ticker := time.NewTicker(30 * time.Second)+ defer ticker.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-g.stopCh:+ return+ case <-ticker.C:+ g.reclaimOnce(ctx)+ }+ }+}++// reclaimOnce recovers entries whose owning consumer died. Plain XPENDING + XCLAIM+// JUSTID with MinIdle (Azure Redis 6.0 compatible — no XAUTOCLAIM/IDLE filter).+func (g *LifecycleIngress) reclaimOnce(ctx context.Context) {+ start := "-"+ const batch = 100+ for {+ pending, err := g.rdb.XPendingExt(ctx, &redis.XPendingExtArgs{+ Stream: g.streamKey,+ Group: g.groupName,+ Start: start,+ End: "+",+ Count: batch,+ }).Result()+ if err != nil {+ log.Printf("lifecycle_ingress: XPENDING error: %v", err)+ return+ }+ if len(pending) == 0 {+ return+ }+ ids := make([]string, 0, len(pending))+ for _, p := range pending {+ ids = append(ids, p.ID)+ }+ claimed, err := g.rdb.XClaimJustID(ctx, &redis.XClaimArgs{+ Stream: g.streamKey,+ Group: g.groupName,+ Consumer: g.consumer,+ MinIdle: 60 * time.Second,+ Messages: ids,+ }).Result()+ if err != nil {+ log.Printf("lifecycle_ingress: XCLAIM error (%d ids): %v", len(ids), err)+ return+ }+ for _, id := range claimed {+ entries, rerr := g.rdb.XRange(ctx, g.streamKey, id, id).Result()+ if rerr != nil {+ log.Printf("lifecycle_ingress: XRANGE %s error: %v", id, rerr)+ continue+ }+ if len(entries) == 0 {+ g.ack(ctx, id) // trimmed away — clear the orphaned PEL entry+ continue+ }+ g.process(ctx, entries[0])+ }+ if len(pending) < batch {+ return+ }+ start = bumpStreamID(pending[len(pending)-1].ID)+ if start == "" {+ return+ }+ }+}++// process handles one stream entry: map to a public lifecycle type, record the+// canonical event, and ack. Irrelevant/malformed entries are acked and dropped;+// a transient store error leaves the entry in the PEL for reclaim.+func (g *LifecycleIngress) process(ctx context.Context, m redis.XMessage) {+ raw, ok := m.Values["event"].(string)+ if !ok || !json.Valid([]byte(raw)) {+ g.ack(ctx, m.ID)+ return+ }+ var env streamLifecycleEnvelope+ if err := json.Unmarshal([]byte(raw), &env); err != nil {+ g.ack(ctx, m.ID)+ return+ }+ publicType, eligible := ingressTypeMap[env.Type]+ if !eligible {+ g.ack(ctx, m.ID) // not a webhook-eligible worker event+ return+ }+ if env.OrgID == "" || env.SandboxID == "" {+ log.Printf("lifecycle_ingress: %s (%s) missing org/sandbox — dropping", m.ID, env.Type)+ g.ack(ctx, m.ID)+ return+ }+ orgID, err := uuid.Parse(env.OrgID)+ if err != nil {+ g.ack(ctx, m.ID)+ return+ }+ ts := time.Now().UTC()+ if env.Timestamp != "" {+ if t, perr := time.Parse(time.RFC3339Nano, env.Timestamp); perr == nil {+ ts = t+ }+ }+ id := env.ID+ if id == "" {+ id = fmt.Sprintf("%s:%s:%s", env.SandboxID, env.Type, m.ID)+ }+ // P3 normalizes worker payload keys to the documented camelCase taxonomy+ // (e.g. created → {template,cpuCount,memoryMB}); for now we pass it through.+ data := env.Payload+ if len(data) == 0 {+ data = json.RawMessage("{}")+ }+ if err := g.store.RecordLifecycleEvent(ctx, db.LifecycleEvent{+ ID: id,+ OrgID: orgID,+ SandboxID: env.SandboxID,+ Type: publicType,+ Data: data,+ Ts: ts,+ }); err != nil {+ log.Printf("lifecycle_ingress: record %s: %v — leaving in PEL", id, err)+ return // do not ack; reclaim retries+ }+ g.ack(ctx, m.ID)+}++func (g *LifecycleIngress) ack(ctx context.Context, ids ...string) {+ if len(ids) == 0 {+ return+ }+ if err := g.rdb.XAck(ctx, g.streamKey, g.groupName, ids...).Err(); err != nil {+ log.Printf("lifecycle_ingress: XACK error: %v", err)+ }+}diff --git a/internal/controlplane/webhook_dispatcher.go b/internal/controlplane/webhook_dispatcher.gonew file mode 100644index 00000000..44fc48a1--- /dev/null+++ b/internal/controlplane/webhook_dispatcher.go@@ -0,0 +1,275 @@+package controlplane++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "log"+ "net/http"+ "strconv"+ "sync"+ "time"++ "github.com/opensandbox/opensandbox/internal/db"+ "github.com/opensandbox/opensandbox/internal/webhook"+)++// WebhookDispatcher delivers due webhook_deliveries rows: it claims a batch+// (FOR UPDATE SKIP LOCKED, so multiple CP instances are safe), sends them+// concurrently through a bounded pool, classifies the outcome, and records it+// with the right backoff / dead-letter. A slower sweep reclaims senders that+// crashed mid-flight. Mirrors billing.BillableEventsSender's lifecycle.+//+// See .agents/work/sandbox-lifecycle-webhooks.md §6/§9.+type WebhookDispatcher struct {+ store *db.Store+ client *http.Client+ id string // locked_by — identifies this dispatcher instance+ interval time.Duration+ batch int+ pool int+ lockFor time.Duration+ stop chan struct{}+ stopped chan struct{}+}++const (+ webhookMaxAttempts = 12 // retry budget before dead-letter (~a few hours)+ webhookConnectTimeout = 10 * time.Second+ webhookSendTimeout = 15 * time.Second+ webhookLockFor = 2 * time.Minute+ webhookErrCap = 400 // max chars stored in deliveries.error+)++// webhookBackoff is the retry schedule, indexed by (retry_count-1); capped at+// the last entry. Mirrors the documented 10s/30s/60s/5m/15m.+var webhookBackoff = []time.Duration{+ 10 * time.Second, 30 * time.Second, 60 * time.Second, 5 * time.Minute, 15 * time.Minute,+}++func backoffFor(retryCount int) time.Duration {+ idx := retryCount - 1+ if idx < 0 {+ idx = 0+ }+ if idx >= len(webhookBackoff) {+ idx = len(webhookBackoff) - 1+ }+ return webhookBackoff[idx]+}++// NewWebhookDispatcher builds a dispatcher. instanceID identifies the lock owner+// (use the cell id / hostname).+func NewWebhookDispatcher(store *db.Store, instanceID string) *WebhookDispatcher {+ if instanceID == "" {+ instanceID = "webhook-dispatcher"+ }+ return &WebhookDispatcher{+ store: store,+ client: webhook.SafeClient(webhookConnectTimeout, webhookSendTimeout),+ id: instanceID,+ interval: 1 * time.Second,+ batch: 20,+ pool: 8,+ lockFor: webhookLockFor,+ stop: make(chan struct{}),+ stopped: make(chan struct{}),+ }+}++func (d *WebhookDispatcher) Start() { go d.loop() }++func (d *WebhookDispatcher) Stop() {+ close(d.stop)+ <-d.stopped+}++func (d *WebhookDispatcher) loop() {+ defer close(d.stopped)+ tick := time.NewTicker(d.interval)+ defer tick.Stop()+ reconcile := time.NewTicker(30 * time.Second)+ defer reconcile.Stop()+ for {+ select {+ case <-d.stop:+ return+ case <-tick.C:+ d.runSafe(d.dispatch)+ case <-reconcile.C:+ d.runSafe(d.reconcile)+ }+ }+}++func (d *WebhookDispatcher) runSafe(fn func()) {+ defer func() {+ if r := recover(); r != nil {+ log.Printf("webhook_dispatcher: recovered from panic: %v", r)+ }+ }()+ fn()+}++// dispatch claims and sends due deliveries until the queue is drained for now.+func (d *WebhookDispatcher) dispatch() {+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)+ defer cancel()+ for {+ claims, err := d.store.ClaimDueDeliveries(ctx, d.id, d.batch, d.lockFor)+ if err != nil {+ log.Printf("webhook_dispatcher: claim: %v", err)+ return+ }+ if len(claims) == 0 {+ return+ }+ sem := make(chan struct{}, d.pool)+ var wg sync.WaitGroup+ for _, dd := range claims {+ wg.Add(1)+ sem <- struct{}{}+ go func(dd db.DueDelivery) {+ defer wg.Done()+ defer func() { <-sem }()+ d.runSafe(func() { d.sendOne(ctx, dd) })+ }(dd)+ }+ wg.Wait()+ if len(claims) < d.batch {+ return+ }+ }+}++func (d *WebhookDispatcher) reconcile() {+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()+ n, err := d.store.ReclaimStaleDeliveries(ctx)+ if err != nil {+ log.Printf("webhook_dispatcher: reclaim: %v", err)+ return+ }+ if n > 0 {+ log.Printf("webhook_dispatcher: reclaimed %d stale delivering row(s)", n)+ }+}++func (d *WebhookDispatcher) sendOne(ctx context.Context, dd db.DueDelivery) {+ sandboxID := extractSandboxID(dd.Payload)+ headers := webhook.Headers(dd.Secret, dd.ID, sandboxID, time.Now().Unix(), dd.Payload)+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, dd.URL, bytes.NewReader(dd.Payload))+ if err != nil {+ d.recordTerminal(ctx, dd, nil, "invalid url: "+err.Error())+ return+ }+ for k, v := range headers {+ req.Header.Set(k, v)+ }++ resp, err := d.client.Do(req)+ if err != nil {+ // A blocked address (SSRF) is permanent; transport/timeout is retryable.+ if webhook.IsSSRFError(err) {+ d.recordTerminal(ctx, dd, nil, "blocked: "+err.Error())+ return+ }+ d.recordRetryable(ctx, dd, nil, 0, err.Error())+ return+ }+ defer resp.Body.Close()+ snippet := readSnippet(resp.Body)+ code := resp.StatusCode+ switch {+ case code >= 200 && code < 300:+ if err := d.store.RecordDeliveryResult(ctx, dd.ID, db.DeliveryResult{+ Status: "delivered", ResponseCode: &code,+ }); err != nil {+ log.Printf("webhook_dispatcher: record delivered %s: %v", dd.ID, err)+ }+ case code == http.StatusTooManyRequests:+ d.recordRetryable(ctx, dd, &code, parseRetryAfter(resp.Header.Get("Retry-After")), "429 rate limited"+snippet)+ case code >= 500:+ d.recordRetryable(ctx, dd, &code, 0, fmt.Sprintf("server error %d%s", code, snippet))+ default: // 3xx (redirects not followed) and 4xx (non-429) are permanent+ d.recordTerminalCode(ctx, dd, &code, fmt.Sprintf("non-retryable response %d%s", code, snippet))+ }+}++// recordRetryable schedules a retry, or dead-letters if the budget is spent.+func (d *WebhookDispatcher) recordRetryable(ctx context.Context, dd db.DueDelivery, code *int, retryAfter time.Duration, msg string) {+ if dd.RetryCount >= webhookMaxAttempts {+ d.recordTerminalCode(ctx, dd, code, "retry budget exhausted: "+msg)+ return+ }+ wait := backoffFor(dd.RetryCount)+ if retryAfter > wait {+ wait = retryAfter+ }+ next := time.Now().Add(wait)+ e := capErr(msg)+ if err := d.store.RecordDeliveryResult(ctx, dd.ID, db.DeliveryResult{+ Status: "failed", ResponseCode: code, Error: &e, NextAttemptAt: &next,+ }); err != nil {+ log.Printf("webhook_dispatcher: record failed %s: %v", dd.ID, err)+ }+}++func (d *WebhookDispatcher) recordTerminal(ctx context.Context, dd db.DueDelivery, code *int, msg string) {+ d.recordTerminalCode(ctx, dd, code, msg)+}++func (d *WebhookDispatcher) recordTerminalCode(ctx context.Context, dd db.DueDelivery, code *int, msg string) {+ e := capErr(msg)+ if err := d.store.RecordDeliveryResult(ctx, dd.ID, db.DeliveryResult{+ Status: "dead_letter", ResponseCode: code, Error: &e,+ }); err != nil {+ log.Printf("webhook_dispatcher: record dead_letter %s: %v", dd.ID, err)+ }+}++// extractSandboxID pulls sandboxId out of the rendered envelope for the+// X-OC-Sandbox-ID header (the field is always present on lifecycle envelopes).+func extractSandboxID(payload []byte) string {+ var env struct {+ SandboxID string `json:"sandboxId"`+ }+ _ = json.Unmarshal(payload, &env)+ return env.SandboxID+}++func readSnippet(body io.Reader) string {+ b, _ := io.ReadAll(io.LimitReader(body, 64*1024))+ if len(b) == 0 {+ return ""+ }+ s := string(b)+ if len(s) > 200 {+ s = s[:200]+ }+ return ": " + s+}++func parseRetryAfter(h string) time.Duration {+ if h == "" {+ return 0+ }+ if secs, err := strconv.Atoi(h); err == nil && secs > 0 {+ return time.Duration(secs) * time.Second+ }+ if t, err := http.ParseTime(h); err == nil {+ if d := time.Until(t); d > 0 {+ return d+ }+ }+ return 0+}++func capErr(s string) string {+ if len(s) > webhookErrCap {+ return s[:webhookErrCap]+ }+ return s+}diff --git a/internal/controlplane/webhook_materializer.go b/internal/controlplane/webhook_materializer.gonew file mode 100644index 00000000..003740ee--- /dev/null+++ b/internal/controlplane/webhook_materializer.go@@ -0,0 +1,75 @@+package controlplane++import (+ "context"+ "log"+ "time"++ "github.com/opensandbox/opensandbox/internal/db"+)++// WebhookMaterializer turns canonical sandbox_lifecycle_events into+// webhook_deliveries rows — the single place delivery rows are created (the+// match / filter / watermark / metadata logic lives in the store). It runs on a+// short tick and drains the backlog each pass. Needs only Postgres, so it runs+// in combined mode too (CP-origin events still flow without Redis).+//+// See .agents/work/sandbox-lifecycle-webhooks.md §5.+type WebhookMaterializer struct {+ store *db.Store+ interval time.Duration+ batch int+ stop chan struct{}+ stopped chan struct{}+}++func NewWebhookMaterializer(store *db.Store) *WebhookMaterializer {+ return &WebhookMaterializer{+ store: store,+ interval: 1 * time.Second,+ batch: 100,+ stop: make(chan struct{}),+ stopped: make(chan struct{}),+ }+}++func (m *WebhookMaterializer) Start() { go m.loop() }++func (m *WebhookMaterializer) Stop() {+ close(m.stop)+ <-m.stopped+}++func (m *WebhookMaterializer) loop() {+ defer close(m.stopped)+ tick := time.NewTicker(m.interval)+ defer tick.Stop()+ for {+ select {+ case <-m.stop:+ return+ case <-tick.C:+ m.drainSafe()+ }+ }+}++func (m *WebhookMaterializer) drainSafe() {+ defer func() {+ if r := recover(); r != nil {+ log.Printf("webhook_materializer: recovered from panic: %v", r)+ }+ }()+ ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)+ defer cancel()+ for {+ n, err := m.store.MaterializePendingLifecycleEvents(ctx, m.batch)+ if err != nil {+ log.Printf("webhook_materializer: materialize: %v", err)+ return+ }+ if n < m.batch {+ return // backlog drained for now+ }+ }+}diff --git a/internal/db/migrations/049_sandbox_webhooks.down.sql b/internal/db/migrations/049_sandbox_webhooks.down.sqlnew file mode 100644index 00000000..5b46451f--- /dev/null+++ b/internal/db/migrations/049_sandbox_webhooks.down.sql@@ -0,0 +1,4 @@+DROP TABLE IF EXISTS webhook_idempotency_keys;+DROP TABLE IF EXISTS webhook_deliveries;+DROP TABLE IF EXISTS sandbox_lifecycle_events;+DROP TABLE IF EXISTS webhook_destinations;diff --git a/internal/db/migrations/049_sandbox_webhooks.up.sql b/internal/db/migrations/049_sandbox_webhooks.up.sqlnew file mode 100644index 00000000..c67c9400--- /dev/null+++ b/internal/db/migrations/049_sandbox_webhooks.up.sql@@ -0,0 +1,90 @@+-- Sandbox lifecycle webhooks (.agents/work/sandbox-lifecycle-webhooks.md).+-- Four additive tables; no outbox (the deliveries ledger is the work queue).+-- The feature is dormant until a destination exists, so this migration is safe+-- to apply ahead of the rest of the rollout.++-- Subscriptions.+CREATE TABLE IF NOT EXISTS webhook_destinations (+ id TEXT PRIMARY KEY, -- 'whk_' + random+ org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,+ name TEXT, -- optional; get-or-create idempotency key+ url TEXT NOT NULL, -- https only; SSRF-validated at write + send+ event_types TEXT[] NOT NULL DEFAULT '{}', -- empty = all; exact ('sandbox.stopped') or prefix ('sandbox.*')+ sandbox_id TEXT, -- optional: scope to one sandbox (NULL = all org sandboxes)+ -- signing secret, ALWAYS present (auto-generated 'whsec_…' if not supplied), returned ONCE on+ -- create/rotate then write-only. Encrypted via internal/crypto (nonce‖ciphertext bytea).+ secret_enc BYTEA NOT NULL,+ enabled BOOLEAN NOT NULL DEFAULT true, -- false = paused (pending rows not claimed)+ created_after_event_seq BIGINT NOT NULL DEFAULT 0, -- watermark = sandbox_lifecycle_events.seq at+ -- creation (skew-free); 0 = no floor+ deleted_at TIMESTAMPTZ, -- soft-delete tombstone; history retained+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE INDEX IF NOT EXISTS webhook_dest_org_idx+ ON webhook_destinations (org_id) WHERE enabled AND deleted_at IS NULL;+CREATE UNIQUE INDEX IF NOT EXISTS webhook_dest_name_uq+ ON webhook_destinations (org_id, name) WHERE name IS NOT NULL AND deleted_at IS NULL;++-- Canonical lifecycle event store — the merge point for both origins. The single+-- recordLifecycleEvent primitive inserts here (CP in-tx; worker via the stream+-- ingress); the materializer reads it and creates delivery rows. `id` is the+-- deterministic event id (dedupe in one place); `seq` is the monotonic watermark.+CREATE TABLE IF NOT EXISTS sandbox_lifecycle_events (+ id TEXT PRIMARY KEY, -- deterministic event id+ seq BIGSERIAL NOT NULL, -- monotonic; the unified watermark+ org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,+ sandbox_id TEXT NOT NULL,+ type TEXT NOT NULL, -- public type, e.g. 'sandbox.stopped'+ data JSONB NOT NULL DEFAULT '{}',+ ts TIMESTAMPTZ NOT NULL DEFAULT now(),+ materialized_at TIMESTAMPTZ -- NULL until the materializer has created deliveries+);+CREATE INDEX IF NOT EXISTS sandbox_lifecycle_events_unmat_idx+ ON sandbox_lifecycle_events (seq) WHERE materialized_at IS NULL;++-- Delivery ledger (also the work queue).+CREATE TABLE IF NOT EXISTS webhook_deliveries (+ id TEXT PRIMARY KEY, -- 'whd_' + random+ org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,+ destination_id TEXT NOT NULL REFERENCES webhook_destinations(id) ON DELETE CASCADE,+ event_id TEXT NOT NULL, -- deterministic; dedup+ event_type TEXT NOT NULL,+ payload JSONB NOT NULL, -- the rendered envelope+ -- pending: scheduled | delivering: claimed, in flight | delivered: 2xx (terminal)+ -- failed: RETRYABLE, carries a future next_attempt_at | dead_letter: TERMINAL (permanent or exhausted)+ -- canceled: TERMINAL (destination soft-deleted while non-terminal)+ status TEXT NOT NULL DEFAULT 'pending',+ attempts INT NOT NULL DEFAULT 0, -- lifetime total (audit; never reset)+ retry_count INT NOT NULL DEFAULT 0, -- retry BUDGET vs MAX_ATTEMPTS; reset on manual redeliver+ next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(), -- the timer (meaningful for pending|failed)+ locked_by TEXT,+ locked_until TIMESTAMPTZ,+ response_code INT,+ error TEXT,+ last_attempt_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ delivered_at TIMESTAMPTZ,+ UNIQUE (destination_id, event_id), -- idempotent projection+ CHECK (status IN ('pending','delivering','delivered','failed','dead_letter','canceled'))+);+-- The poll query's index: rows that are due.+CREATE INDEX IF NOT EXISTS webhook_deliveries_due_idx+ ON webhook_deliveries (next_attempt_at) WHERE status IN ('pending','failed');+CREATE INDEX IF NOT EXISTS webhook_deliveries_dest_idx+ ON webhook_deliveries (destination_id, created_at DESC);++-- Idempotency-Key storage for POST /api/webhooks. Same (org,key) + same request+-- → replay the stored ORIGINAL RESPONSE (incl. the one-time generated secret);+-- same key + different request → 409. response_enc is the rendered create+-- response, encrypted (it carries the plaintext secret). Prune past a ~24h TTL.+CREATE TABLE IF NOT EXISTS webhook_idempotency_keys (+ org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,+ key TEXT NOT NULL, -- caller's Idempotency-Key header+ request_hash TEXT NOT NULL, -- fingerprint of the create body+ destination_id TEXT NOT NULL REFERENCES webhook_destinations(id) ON DELETE CASCADE,+ response_enc BYTEA NOT NULL, -- the original create response (incl. secret), encrypted+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (org_id, key)+);diff --git a/internal/db/store.go b/internal/db/store.goindex 5c908bc4..aa88aba0 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -196,6 +196,7 @@ func (s *Store) Migrate(ctx context.Context) error {{46, "migrations/046_preview_auth.up.sql"},{47, "migrations/047_orgs_billing_provider.up.sql"},{48, "migrations/048_orgs_usage_sync_watermark.up.sql"},+ {49, "migrations/049_sandbox_webhooks.up.sql"},}for _, m := range migrations {@@ -857,6 +858,36 @@ func (s *Store) UpdateSandboxSessionStatus(ctx context.Context, sandboxID, statu// Capture org for the lifecycle publish below (same tx; cheap)._ = tx.QueryRow(ctx,`SELECT org_id FROM sandbox_sessions WHERE sandbox_id = $1`, sandboxID).Scan(&orgID)++ // Record the canonical lifecycle event in THIS tx (CP-origin → durable+ // from the state change) so sandbox webhooks fire. Only the public+ // moments owned by the control plane; worker-origin events+ // (created/ready/migrated) arrive via the Redis stream ingress.+ if orgID != uuid.Nil {+ var evType string+ var data json.RawMessage+ switch status {+ case "stopped":+ evType = "sandbox.stopped"+ data = json.RawMessage(`{"reason":"user_requested"}`)+ case "error":+ evType = "sandbox.stopped"+ data = json.RawMessage(`{"reason":"crash"}`)+ case "hibernated":+ evType = "sandbox.hibernated"+ }+ if evType != "" {+ if err := recordLifecycleEvent(ctx, tx, LifecycleEvent{+ ID: fmt.Sprintf("%s:%s:%d", sandboxID, evType, time.Now().UnixNano()),+ OrgID: orgID,+ SandboxID: sandboxID,+ Type: evType,+ Data: data,+ }); err != nil {+ return fmt.Errorf("record lifecycle event: %w", err)+ }+ }+ }}if err := tx.Commit(ctx); err != nil {return errdiff --git a/internal/db/webhooks.go b/internal/db/webhooks.gonew file mode 100644index 00000000..5916c8be--- /dev/null+++ b/internal/db/webhooks.go@@ -0,0 +1,895 @@+package db++import (+ "context"+ "crypto/rand"+ "encoding/base64"+ "encoding/hex"+ "encoding/json"+ "errors"+ "fmt"+ "strconv"+ "strings"+ "time"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5"+)++// Sandbox lifecycle webhooks store layer. The wire/types mapping lives in the+// API layer (internal/db stays decoupled from pkg/types); methods here return+// db row structs and operate on raw SQL via the shared pool.+//+// See .agents/work/sandbox-lifecycle-webhooks.md for the full design.++// Sentinel errors surfaced to the API layer.+var (+ ErrWebhookNotFound = errors.New("webhook destination not found")+ ErrWebhookNameConflict = errors.New("webhook name already used with a different config")+ ErrWebhookIdempotencyConflict = errors.New("idempotency key reused with a different request")+ ErrEncryptionNotConfigured = errors.New("secret encryption not configured")+)++// newWebhookID mints a prefixed random id, e.g. "whk_" / "whd_" + 24 hex chars.+func newWebhookID(prefix string) string {+ var b [12]byte+ _, _ = rand.Read(b[:])+ return prefix + hex.EncodeToString(b[:])+}++// ---------------------------------------------------------------------------+// Canonical lifecycle events (the single recordLifecycleEvent primitive)+// ---------------------------------------------------------------------------++// LifecycleEvent is one canonical sandbox lifecycle moment.+type LifecycleEvent struct {+ ID string // deterministic event id (dedup key)+ OrgID uuid.UUID+ SandboxID string+ Type string // public type, e.g. "sandbox.stopped"+ Data json.RawMessage // event-specific, camelCase; nil → {}+ Ts time.Time // zero → now()+}++// recordLifecycleEvent inserts a canonical lifecycle event within the given tx.+// ON CONFLICT (id) DO NOTHING makes stream replays / double-emits idempotent in+// exactly one place. Both origins call it (CP in-tx; worker via the ingress's+// own tx through RecordLifecycleEvent).+func recordLifecycleEvent(ctx context.Context, tx pgx.Tx, ev LifecycleEvent) error {+ if len(ev.Data) == 0 {+ ev.Data = json.RawMessage("{}")+ }+ ts := ev.Ts+ if ts.IsZero() {+ ts = time.Now().UTC()+ }+ _, err := tx.Exec(ctx,+ `INSERT INTO sandbox_lifecycle_events (id, org_id, sandbox_id, type, data, ts)+ VALUES ($1, $2, $3, $4, $5, $6)+ ON CONFLICT (id) DO NOTHING`,+ ev.ID, ev.OrgID, ev.SandboxID, ev.Type, string(ev.Data), ts)+ if err != nil {+ return fmt.Errorf("record lifecycle event: %w", err)+ }+ return nil+}++// RecordLifecycleEvent records a canonical event in its own transaction (used by+// the worker-stream ingress). CP-origin callers instead use recordLifecycleEvent+// inside their existing transaction for in-tx durability.+func (s *Store) RecordLifecycleEvent(ctx context.Context, ev LifecycleEvent) error {+ tx, err := s.pool.Begin(ctx)+ if err != nil {+ return err+ }+ defer tx.Rollback(ctx)+ if err := recordLifecycleEvent(ctx, tx, ev); err != nil {+ return err+ }+ return tx.Commit(ctx)+}++// CurrentLifecycleSeq returns the current max event seq, used as a destination's+// creation watermark (it then receives only strictly-later events).+func (s *Store) CurrentLifecycleSeq(ctx context.Context) (int64, error) {+ var seq int64+ err := s.pool.QueryRow(ctx, `SELECT COALESCE(MAX(seq), 0) FROM sandbox_lifecycle_events`).Scan(&seq)+ return seq, err+}++// ---------------------------------------------------------------------------+// Destinations+// ---------------------------------------------------------------------------++// WebhookDestinationRow is the stored destination (secret never exposed).+type WebhookDestinationRow struct {+ ID string+ OrgID uuid.UUID+ Name *string+ URL string+ EventTypes []string+ SandboxID *string+ Enabled bool+ HasSecret bool+ CreatedAfterEventSeq int64+ DeletedAt *time.Time+ CreatedAt time.Time+ UpdatedAt time.Time+}++// CreateDestinationParams is the resolved input for CreateWebhookDestination+// (the handler has already chosen the secret — generated or caller-supplied).+type CreateDestinationParams struct {+ OrgID uuid.UUID+ Name *string+ URL string+ EventTypes []string+ SandboxID *string+ Enabled bool+ SecretPlain string+ CreatedAfterEventSeq int64+}++const destCols = `id, org_id, name, url, event_types, sandbox_id, enabled,+ (secret_enc IS NOT NULL) AS has_secret, created_after_event_seq, deleted_at, created_at, updated_at`++func scanDestination(row pgx.Row) (*WebhookDestinationRow, error) {+ d := &WebhookDestinationRow{}+ if d.EventTypes == nil {+ d.EventTypes = []string{}+ }+ err := row.Scan(&d.ID, &d.OrgID, &d.Name, &d.URL, &d.EventTypes, &d.SandboxID,+ &d.Enabled, &d.HasSecret, &d.CreatedAfterEventSeq, &d.DeletedAt, &d.CreatedAt, &d.UpdatedAt)+ if err != nil {+ return nil, err+ }+ if d.EventTypes == nil {+ d.EventTypes = []string{}+ }+ return d, nil+}++func samePtrStr(a, b *string) bool {+ if a == nil || b == nil {+ return a == nil && b == nil+ }+ return *a == *b+}++func sameStrSlice(a, b []string) bool {+ if len(a) != len(b) {+ return false+ }+ for i := range a {+ if a[i] != b[i] {+ return false+ }+ }+ return true+}++// CreateWebhookDestination inserts a destination, encrypting the secret. If a+// Name is given and a live destination with that name already exists: a matching+// config (url + eventTypes + sandboxId) returns the existing row with reused=true+// (caller responds 200 without a secret); a differing config returns+// ErrWebhookNameConflict.+func (s *Store) CreateWebhookDestination(ctx context.Context, p CreateDestinationParams) (row *WebhookDestinationRow, reused bool, err error) {+ if s.encryptor == nil {+ return nil, false, ErrEncryptionNotConfigured+ }+ if p.EventTypes == nil {+ p.EventTypes = []string{}+ }++ if p.Name != nil {+ existing, found, ferr := s.getDestinationByName(ctx, p.OrgID, *p.Name)+ if ferr != nil {+ return nil, false, ferr+ }+ if found {+ if existing.URL == p.URL && sameStrSlice(existing.EventTypes, p.EventTypes) && samePtrStr(existing.SandboxID, p.SandboxID) {+ return existing, true, nil+ }+ return nil, false, ErrWebhookNameConflict+ }+ }++ secretEnc, err := s.encryptor.Encrypt([]byte(p.SecretPlain))+ if err != nil {+ return nil, false, fmt.Errorf("encrypt webhook secret: %w", err)+ }+ id := newWebhookID("whk_")+ r, err := scanDestination(s.pool.QueryRow(ctx,+ `INSERT INTO webhook_destinations+ (id, org_id, name, url, event_types, sandbox_id, secret_enc, enabled, created_after_event_seq)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)+ RETURNING `+destCols,+ id, p.OrgID, p.Name, p.URL, p.EventTypes, p.SandboxID, secretEnc, p.Enabled, p.CreatedAfterEventSeq))+ if err != nil {+ // Lost a race on the unique name index → fall back to get-or-create.+ if p.Name != nil && isUniqueViolation(err) {+ existing, found, ferr := s.getDestinationByName(ctx, p.OrgID, *p.Name)+ if ferr == nil && found {+ if existing.URL == p.URL && sameStrSlice(existing.EventTypes, p.EventTypes) && samePtrStr(existing.SandboxID, p.SandboxID) {+ return existing, true, nil+ }+ return nil, false, ErrWebhookNameConflict+ }+ }+ return nil, false, fmt.Errorf("create webhook destination: %w", err)+ }+ return r, false, nil+}++func (s *Store) getDestinationByName(ctx context.Context, orgID uuid.UUID, name string) (*WebhookDestinationRow, bool, error) {+ r, err := scanDestination(s.pool.QueryRow(ctx,+ `SELECT `+destCols+` FROM webhook_destinations+ WHERE org_id = $1 AND name = $2 AND deleted_at IS NULL`, orgID, name))+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return nil, false, nil+ }+ return nil, false, err+ }+ return r, true, nil+}++// ListWebhookDestinations returns an org's live (non-deleted) destinations.+func (s *Store) ListWebhookDestinations(ctx context.Context, orgID uuid.UUID) ([]*WebhookDestinationRow, error) {+ rows, err := s.pool.Query(ctx,+ `SELECT `+destCols+` FROM webhook_destinations+ WHERE org_id = $1 AND deleted_at IS NULL ORDER BY created_at DESC`, orgID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ out := []*WebhookDestinationRow{}+ for rows.Next() {+ d, err := scanDestination(rows)+ if err != nil {+ return nil, err+ }+ out = append(out, d)+ }+ return out, rows.Err()+}++// GetWebhookDestination fetches one live destination, org-scoped.+func (s *Store) GetWebhookDestination(ctx context.Context, orgID uuid.UUID, id string) (*WebhookDestinationRow, error) {+ r, err := scanDestination(s.pool.QueryRow(ctx,+ `SELECT `+destCols+` FROM webhook_destinations+ WHERE id = $1 AND org_id = $2 AND deleted_at IS NULL`, id, orgID))+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return nil, ErrWebhookNotFound+ }+ return nil, err+ }+ return r, nil+}++// GetWebhookDestinationSecret decrypts and returns the destination's secret.+func (s *Store) GetWebhookDestinationSecret(ctx context.Context, id string) (string, error) {+ if s.encryptor == nil {+ return "", ErrEncryptionNotConfigured+ }+ var enc []byte+ err := s.pool.QueryRow(ctx, `SELECT secret_enc FROM webhook_destinations WHERE id = $1`, id).Scan(&enc)+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return "", ErrWebhookNotFound+ }+ return "", err+ }+ plain, err := s.encryptor.Decrypt(enc)+ if err != nil {+ return "", fmt.Errorf("decrypt webhook secret: %w", err)+ }+ return string(plain), nil+}++// UpdateDestinationParams is a partial update. Nil fields are left unchanged.+// ClearEventTypes overrides EventTypes to set an empty allow-list (deliver all).+// RotateSecret/NewSecretPlain set a new secret (sandboxId scope is immutable).+type UpdateDestinationParams struct {+ URL *string+ EventTypes *[]string+ ClearEventTypes bool+ Enabled *bool+ Name *string+ NewSecretPlain *string // resolved by handler when secret set or rotateSecret=true+}++// UpdateWebhookDestination applies a partial update and returns the live row.+func (s *Store) UpdateWebhookDestination(ctx context.Context, orgID uuid.UUID, id string, p UpdateDestinationParams) (*WebhookDestinationRow, error) {+ sets := []string{"updated_at = now()"}+ args := []any{}+ add := func(expr string, val any) {+ args = append(args, val)+ sets = append(sets, fmt.Sprintf("%s = $%d", expr, len(args)))+ }+ if p.URL != nil {+ add("url", *p.URL)+ }+ if p.ClearEventTypes {+ add("event_types", []string{})+ } else if p.EventTypes != nil {+ add("event_types", *p.EventTypes)+ }+ if p.Enabled != nil {+ add("enabled", *p.Enabled)+ }+ if p.Name != nil {+ add("name", *p.Name)+ }+ if p.NewSecretPlain != nil {+ if s.encryptor == nil {+ return nil, ErrEncryptionNotConfigured+ }+ enc, err := s.encryptor.Encrypt([]byte(*p.NewSecretPlain))+ if err != nil {+ return nil, fmt.Errorf("encrypt webhook secret: %w", err)+ }+ add("secret_enc", enc)+ }+ args = append(args, id, orgID)+ q := fmt.Sprintf(`UPDATE webhook_destinations SET %s+ WHERE id = $%d AND org_id = $%d AND deleted_at IS NULL+ RETURNING %s`, strings.Join(sets, ", "), len(args)-1, len(args), destCols)+ r, err := scanDestination(s.pool.QueryRow(ctx, q, args...))+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return nil, ErrWebhookNotFound+ }+ if isUniqueViolation(err) {+ return nil, ErrWebhookNameConflict+ }+ return nil, err+ }+ return r, nil+}++// SoftDeleteWebhookDestination tombstones a destination, disables it, and+// cancels its non-terminal deliveries — all in one tx.+func (s *Store) SoftDeleteWebhookDestination(ctx context.Context, orgID uuid.UUID, id string) error {+ tx, err := s.pool.Begin(ctx)+ if err != nil {+ return err+ }+ defer tx.Rollback(ctx)++ tag, err := tx.Exec(ctx,+ `UPDATE webhook_destinations SET deleted_at = now(), enabled = false, updated_at = now()+ WHERE id = $1 AND org_id = $2 AND deleted_at IS NULL`, id, orgID)+ if err != nil {+ return err+ }+ if tag.RowsAffected() == 0 {+ return ErrWebhookNotFound+ }+ if _, err := tx.Exec(ctx,+ `UPDATE webhook_deliveries+ SET status = 'canceled', error = 'destination_deleted', locked_by = NULL,+ locked_until = NULL, updated_at = now()+ WHERE destination_id = $1 AND status IN ('pending','delivering','failed')`, id); err != nil {+ return err+ }+ return tx.Commit(ctx)+}++// ---------------------------------------------------------------------------+// Idempotency-Key storage+// ---------------------------------------------------------------------------++// GetWebhookIdempotentResponse looks up a stored create response by (org,key).+// found+matching hash → returns the decrypted response JSON. found+different+// hash → ErrWebhookIdempotencyConflict. not found → (nil, false, nil).+func (s *Store) GetWebhookIdempotentResponse(ctx context.Context, orgID uuid.UUID, key, requestHash string) ([]byte, bool, error) {+ if s.encryptor == nil {+ return nil, false, ErrEncryptionNotConfigured+ }+ var storedHash string+ var enc []byte+ err := s.pool.QueryRow(ctx,+ `SELECT request_hash, response_enc FROM webhook_idempotency_keys WHERE org_id = $1 AND key = $2`,+ orgID, key).Scan(&storedHash, &enc)+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return nil, false, nil+ }+ return nil, false, err+ }+ if storedHash != requestHash {+ return nil, false, ErrWebhookIdempotencyConflict+ }+ plain, err := s.encryptor.Decrypt(enc)+ if err != nil {+ return nil, false, fmt.Errorf("decrypt idempotent response: %w", err)+ }+ return plain, true, nil+}++// PutWebhookIdempotentResponse stores the encrypted original create response.+func (s *Store) PutWebhookIdempotentResponse(ctx context.Context, orgID uuid.UUID, key, requestHash, destinationID string, responseJSON []byte) error {+ if s.encryptor == nil {+ return ErrEncryptionNotConfigured+ }+ enc, err := s.encryptor.Encrypt(responseJSON)+ if err != nil {+ return fmt.Errorf("encrypt idempotent response: %w", err)+ }+ _, err = s.pool.Exec(ctx,+ `INSERT INTO webhook_idempotency_keys (org_id, key, request_hash, destination_id, response_enc)+ VALUES ($1, $2, $3, $4, $5)+ ON CONFLICT (org_id, key) DO NOTHING`,+ orgID, key, requestHash, destinationID, enc)+ return err+}++// ---------------------------------------------------------------------------+// Materializer: canonical events → delivery rows+// ---------------------------------------------------------------------------++type lifecycleEventRow struct {+ ID string+ Seq int64+ OrgID uuid.UUID+ SandboxID string+ Type string+ Data []byte+ Ts time.Time+}++// MaterializePendingLifecycleEvents claims up to `batch` unmaterialized events+// and, per event, matches live destinations (scope + watermark + type filter)+// and inserts pending delivery rows. This is the ONLY place delivery rows are+// created. Returns the number of events materialized.+func (s *Store) MaterializePendingLifecycleEvents(ctx context.Context, batch int) (int, error) {+ if batch <= 0 {+ batch = 100+ }+ tx, err := s.pool.Begin(ctx)+ if err != nil {+ return 0, err+ }+ defer tx.Rollback(ctx)++ rows, err := tx.Query(ctx,+ `SELECT id, seq, org_id, sandbox_id, type, data, ts+ FROM sandbox_lifecycle_events+ WHERE materialized_at IS NULL+ ORDER BY seq+ FOR UPDATE SKIP LOCKED+ LIMIT $1`, batch)+ if err != nil {+ return 0, err+ }+ events := []lifecycleEventRow{}+ for rows.Next() {+ var e lifecycleEventRow+ if err := rows.Scan(&e.ID, &e.Seq, &e.OrgID, &e.SandboxID, &e.Type, &e.Data, &e.Ts); err != nil {+ rows.Close()+ return 0, err+ }+ events = append(events, e)+ }+ rows.Close()+ if err := rows.Err(); err != nil {+ return 0, err+ }++ for _, e := range events {+ metadata, err := getSandboxMetadataTx(ctx, tx, e.SandboxID)+ if err != nil {+ return 0, err+ }+ dests, err := matchDestinationsTx(ctx, tx, e)+ if err != nil {+ return 0, err+ }+ for _, d := range dests {+ if !eventTypeMatches(d.eventTypes, e.Type) {+ continue+ }+ deliveryID := newWebhookID("whd_")+ payload, err := renderEnvelope(deliveryID, e, metadata)+ if err != nil {+ return 0, err+ }+ if _, err := tx.Exec(ctx,+ `INSERT INTO webhook_deliveries+ (id, org_id, destination_id, event_id, event_type, payload, status, next_attempt_at)+ VALUES ($1, $2, $3, $4, $5, $6, 'pending', now())+ ON CONFLICT (destination_id, event_id) DO NOTHING`,+ deliveryID, e.OrgID, d.id, e.ID, e.Type, string(payload)); err != nil {+ return 0, err+ }+ }+ if _, err := tx.Exec(ctx,+ `UPDATE sandbox_lifecycle_events SET materialized_at = now() WHERE id = $1`, e.ID); err != nil {+ return 0, err+ }+ }+ if err := tx.Commit(ctx); err != nil {+ return 0, err+ }+ return len(events), nil+}++type matchedDest struct {+ id string+ eventTypes []string+}++func matchDestinationsTx(ctx context.Context, tx pgx.Tx, e lifecycleEventRow) ([]matchedDest, error) {+ rows, err := tx.Query(ctx,+ `SELECT id, event_types FROM webhook_destinations+ WHERE org_id = $1 AND enabled AND deleted_at IS NULL+ AND (sandbox_id IS NULL OR sandbox_id = $2)+ AND created_after_event_seq < $3`,+ e.OrgID, e.SandboxID, e.Seq)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ out := []matchedDest{}+ for rows.Next() {+ var d matchedDest+ if err := rows.Scan(&d.id, &d.eventTypes); err != nil {+ return nil, err+ }+ out = append(out, d)+ }+ return out, rows.Err()+}++func getSandboxMetadataTx(ctx context.Context, tx pgx.Tx, sandboxID string) (map[string]string, error) {+ var raw []byte+ err := tx.QueryRow(ctx,+ `SELECT metadata FROM sandbox_sessions WHERE sandbox_id = $1 ORDER BY started_at DESC LIMIT 1`,+ sandboxID).Scan(&raw)+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return nil, nil+ }+ return nil, err+ }+ if len(raw) == 0 {+ return nil, nil+ }+ m := map[string]string{}+ if err := json.Unmarshal(raw, &m); err != nil {+ // Non-string metadata or malformed → treat as absent rather than fail.+ return nil, nil+ }+ if len(m) == 0 {+ return nil, nil+ }+ return m, nil+}++// renderEnvelope builds the camelCase delivery body. Keys MUST match+// pkg/types.SandboxWebhookEnvelope (the canonical contract). metadata nil →+// JSON null.+func renderEnvelope(deliveryID string, e lifecycleEventRow, metadata map[string]string) ([]byte, error) {+ data := json.RawMessage(e.Data)+ if len(data) == 0 {+ data = json.RawMessage("{}")+ }+ env := map[string]any{+ "type": e.Type,+ "sandboxId": e.SandboxID,+ "eventId": e.ID,+ "deliveryId": deliveryID,+ "metadata": metadata,+ "event": map[string]any{+ "id": e.ID,+ "ts": e.Ts.UTC().Format(time.RFC3339Nano),+ "orgId": e.OrgID.String(),+ "sandboxId": e.SandboxID,+ "type": e.Type,+ "data": data,+ },+ }+ return json.Marshal(env)+}++// eventTypeMatches: empty filter = all; exact match or a "prefix.*" wildcard.+func eventTypeMatches(filter []string, eventType string) bool {+ if len(filter) == 0 {+ return true+ }+ for _, f := range filter {+ if f == eventType {+ return true+ }+ if strings.HasSuffix(f, ".*") && strings.HasPrefix(eventType, strings.TrimSuffix(f, "*")) {+ return true+ }+ }+ return false+}++// ---------------------------------------------------------------------------+// Deliveries (the dispatcher's work queue)+// ---------------------------------------------------------------------------++// WebhookDeliveryRow is the stored delivery record.+type WebhookDeliveryRow struct {+ ID string+ OrgID uuid.UUID+ DestinationID string+ EventID string+ EventType string+ Status string+ Attempts int+ RetryCount int+ NextAttemptAt time.Time+ ResponseCode *int+ Error *string+ LastAttemptAt *time.Time+ CreatedAt time.Time+ UpdatedAt time.Time+ DeliveredAt *time.Time+}++const deliveryCols = `id, org_id, destination_id, event_id, event_type, status, attempts,+ retry_count, next_attempt_at, response_code, error, last_attempt_at, created_at, updated_at, delivered_at`++func scanDelivery(row pgx.Row) (*WebhookDeliveryRow, error) {+ d := &WebhookDeliveryRow{}+ err := row.Scan(&d.ID, &d.OrgID, &d.DestinationID, &d.EventID, &d.EventType, &d.Status,+ &d.Attempts, &d.RetryCount, &d.NextAttemptAt, &d.ResponseCode, &d.Error,+ &d.LastAttemptAt, &d.CreatedAt, &d.UpdatedAt, &d.DeliveredAt)+ if err != nil {+ return nil, err+ }+ return d, nil+}++// DueDelivery is a claimed delivery ready to send (live destination joined,+// secret decrypted in-process).+type DueDelivery struct {+ ID string+ URL string+ Secret string+ Payload []byte+ RetryCount int // post-claim value (already incremented)+}++// ClaimDueDeliveries atomically claims up to `batch` due deliveries for enabled,+// non-deleted destinations: marks them delivering (attempts+1, retry_count+1,+// lock held), and returns them with the live URL + decrypted secret. Safe for+// multiple dispatcher instances (FOR UPDATE … SKIP LOCKED).+func (s *Store) ClaimDueDeliveries(ctx context.Context, lockedBy string, batch int, lockFor time.Duration) ([]DueDelivery, error) {+ if s.encryptor == nil {+ return nil, ErrEncryptionNotConfigured+ }+ if batch <= 0 {+ batch = 20+ }+ tx, err := s.pool.Begin(ctx)+ if err != nil {+ return nil, err+ }+ defer tx.Rollback(ctx)++ rows, err := tx.Query(ctx,+ `SELECT d.id, d.retry_count, dst.url, dst.secret_enc, d.payload+ FROM webhook_deliveries d+ JOIN webhook_destinations dst ON dst.id = d.destination_id AND dst.enabled AND dst.deleted_at IS NULL+ WHERE d.status IN ('pending','failed') AND d.next_attempt_at <= now()+ ORDER BY d.next_attempt_at+ FOR UPDATE OF d SKIP LOCKED+ LIMIT $1`, batch)+ if err != nil {+ return nil, err+ }+ type claim struct {+ id string+ retry int+ url string+ secEnc []byte+ payload []byte+ }+ claims := []claim{}+ for rows.Next() {+ var c claim+ if err := rows.Scan(&c.id, &c.retry, &c.url, &c.secEnc, &c.payload); err != nil {+ rows.Close()+ return nil, err+ }+ claims = append(claims, c)+ }+ rows.Close()+ if err := rows.Err(); err != nil {+ return nil, err+ }+ if len(claims) == 0 {+ return nil, tx.Commit(ctx)+ }++ out := make([]DueDelivery, 0, len(claims))+ lockUntil := time.Now().Add(lockFor)+ for _, c := range claims {+ if _, err := tx.Exec(ctx,+ `UPDATE webhook_deliveries+ SET status = 'delivering', attempts = attempts + 1, retry_count = retry_count + 1,+ last_attempt_at = now(), locked_by = $2, locked_until = $3, updated_at = now()+ WHERE id = $1`, c.id, lockedBy, lockUntil); err != nil {+ return nil, err+ }+ secret, err := s.encryptor.Decrypt(c.secEnc)+ if err != nil {+ return nil, fmt.Errorf("decrypt secret for delivery %s: %w", c.id, err)+ }+ out = append(out, DueDelivery{+ ID: c.id,+ URL: c.url,+ Secret: string(secret),+ Payload: c.payload,+ RetryCount: c.retry + 1,+ })+ }+ if err := tx.Commit(ctx); err != nil {+ return nil, err+ }+ return out, nil+}++// DeliveryResult is the outcome the dispatcher records after a send attempt.+type DeliveryResult struct {+ Status string // delivered | failed | dead_letter+ ResponseCode *int+ Error *string+ NextAttemptAt *time.Time // for failed (retryable)+}++// RecordDeliveryResult writes the outcome of a send attempt and clears the lock.+func (s *Store) RecordDeliveryResult(ctx context.Context, id string, r DeliveryResult) error {+ var delivered *time.Time+ if r.Status == "delivered" {+ now := time.Now()+ delivered = &now+ }+ _, err := s.pool.Exec(ctx,+ `UPDATE webhook_deliveries+ SET status = $2, response_code = $3, error = $4,+ next_attempt_at = COALESCE($5, next_attempt_at),+ delivered_at = COALESCE($6, delivered_at),+ locked_by = NULL, locked_until = NULL, updated_at = now()+ WHERE id = $1`,+ id, r.Status, r.ResponseCode, r.Error, r.NextAttemptAt, delivered)+ return err+}++// ReclaimStaleDeliveries returns deliveries stuck in 'delivering' past their+// lock to 'failed' so the poll loop requeues them. Returns rows reclaimed.+func (s *Store) ReclaimStaleDeliveries(ctx context.Context) (int64, error) {+ tag, err := s.pool.Exec(ctx,+ `UPDATE webhook_deliveries+ SET status = 'failed', locked_by = NULL, locked_until = NULL, updated_at = now()+ WHERE status = 'delivering' AND locked_until < now() - interval '30 seconds'`)+ if err != nil {+ return 0, err+ }+ return tag.RowsAffected(), nil+}++// RedeliverDelivery re-enqueues any delivery with a fresh retry budget+// (retry_count=0), preserving lifetime attempts, and returns the updated row.+// Org+destination scoped.+func (s *Store) RedeliverDelivery(ctx context.Context, orgID uuid.UUID, destID, deliveryID string) (*WebhookDeliveryRow, error) {+ r, err := scanDelivery(s.pool.QueryRow(ctx,+ `UPDATE webhook_deliveries+ SET status = 'pending', next_attempt_at = now(), retry_count = 0,+ response_code = NULL, error = NULL, locked_by = NULL, locked_until = NULL, updated_at = now()+ WHERE id = $1 AND destination_id = $2 AND org_id = $3+ RETURNING `+deliveryCols, deliveryID, destID, orgID))+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return nil, ErrWebhookNotFound+ }+ return nil, err+ }+ return r, nil+}++// GetWebhookDelivery fetches one delivery, org+destination scoped.+func (s *Store) GetWebhookDelivery(ctx context.Context, orgID uuid.UUID, destID, deliveryID string) (*WebhookDeliveryRow, error) {+ r, err := scanDelivery(s.pool.QueryRow(ctx,+ `SELECT `+deliveryCols+` FROM webhook_deliveries+ WHERE id = $1 AND destination_id = $2 AND org_id = $3`, deliveryID, destID, orgID))+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return nil, ErrWebhookNotFound+ }+ return nil, err+ }+ return r, nil+}++// ListWebhookDeliveries returns a destination's deliveries, newest first,+// cursor-paginated on (created_at, id). An optional status filter narrows it.+func (s *Store) ListWebhookDeliveries(ctx context.Context, orgID uuid.UUID, destID, status, cursor string, limit int) ([]*WebhookDeliveryRow, *string, bool, error) {+ if limit <= 0 || limit > 200 {+ limit = 50+ }+ // Verify the destination belongs to the org (so an unknown id 404s, not empties).+ if _, err := s.GetWebhookDestination(ctx, orgID, destID); err != nil {+ return nil, nil, false, err+ }++ args := []any{destID, orgID}+ where := `destination_id = $1 AND org_id = $2`+ if status != "" {+ args = append(args, status)+ where += fmt.Sprintf(" AND status = $%d", len(args))+ }+ if cursor != "" {+ ts, id, ok := decodeDeliveryCursor(cursor)+ if ok {+ args = append(args, ts)+ tsIdx := len(args)+ args = append(args, id)+ idIdx := len(args)+ where += fmt.Sprintf(" AND (created_at, id) < ($%d::timestamptz, $%d::text)", tsIdx, idIdx)+ }+ }+ args = append(args, limit+1)+ q := fmt.Sprintf(`SELECT %s FROM webhook_deliveries WHERE %s+ ORDER BY created_at DESC, id DESC LIMIT $%d`, deliveryCols, where, len(args))+ rows, err := s.pool.Query(ctx, q, args...)+ if err != nil {+ return nil, nil, false, err+ }+ defer rows.Close()+ out := []*WebhookDeliveryRow{}+ for rows.Next() {+ d, err := scanDelivery(rows)+ if err != nil {+ return nil, nil, false, err+ }+ out = append(out, d)+ }+ if err := rows.Err(); err != nil {+ return nil, nil, false, err+ }+ hasMore := false+ if len(out) > limit {+ hasMore = true+ out = out[:limit]+ }+ var next *string+ if hasMore && len(out) > 0 {+ last := out[len(out)-1]+ c := encodeDeliveryCursor(last.CreatedAt, last.ID)+ next = &c+ }+ return out, next, hasMore, nil+}++func encodeDeliveryCursor(ts time.Time, id string) string {+ return base64.RawURLEncoding.EncodeToString([]byte(strconv.FormatInt(ts.UnixNano(), 10) + "," + id))+}++func decodeDeliveryCursor(c string) (time.Time, string, bool) {+ raw, err := base64.RawURLEncoding.DecodeString(c)+ if err != nil {+ return time.Time{}, "", false+ }+ parts := strings.SplitN(string(raw), ",", 2)+ if len(parts) != 2 {+ return time.Time{}, "", false+ }+ ns, err := strconv.ParseInt(parts[0], 10, 64)+ if err != nil {+ return time.Time{}, "", false+ }+ return time.Unix(0, ns), parts[1], true+}++// isUniqueViolation reports whether err is a Postgres unique-constraint error.+func isUniqueViolation(err error) bool {+ return err != nil && strings.Contains(err.Error(), "SQLSTATE 23505")+}diff --git a/internal/webhook/sign.go b/internal/webhook/sign.gonew file mode 100644index 00000000..479eca77--- /dev/null+++ b/internal/webhook/sign.go@@ -0,0 +1,90 @@+// Package webhook implements the signing and SSRF-defense primitives for+// outbound sandbox lifecycle webhooks. It mirrors the Standard Webhooks scheme+// (https://www.standardwebhooks.com) used by sessions-api so a recipient can+// verify deliveries from either product with one verifier.+//+// The one deliberate difference from sessions-api today: the `webhook-id`+// header is the *delivery* id (stable across retries and manual redelivery),+// not the event id — see .agents/work/sandbox-lifecycle-webhooks.md §7.+package webhook++import (+ "crypto/hmac"+ "crypto/rand"+ "crypto/sha256"+ "encoding/base64"+ "strconv"+ "strings"+)++// SecretPrefix is the conventional Standard Webhooks secret prefix.+const SecretPrefix = "whsec_"++// secretBytes is the number of random bytes behind a generated secret.+const secretBytes = 32++// GenerateSecret mints a new signing secret: "whsec_" + standard base64 of 32+// random bytes. Standard (not URL) base64 is deliberate (the shipped TS+// verifier decodes with atob, which doesn't reliably accept base64url).+func GenerateSecret() (string, error) {+ buf := make([]byte, secretBytes)+ if _, err := rand.Read(buf); err != nil {+ return "", err+ }+ return SecretPrefix + base64.StdEncoding.EncodeToString(buf), nil+}++// SecretKeyBytes decodes a Standard Webhooks secret to its raw HMAC key bytes:+// strip the "whsec_" prefix and base64-decode. If the remainder isn't valid+// base64, fall back to the raw UTF-8 bytes of the original secret (mirrors+// sessions-api egress.ts:secretKeyBytes, so caller-supplied non-base64 secrets+// still work identically across products).+func SecretKeyBytes(secret string) []byte {+ s := strings.TrimPrefix(secret, SecretPrefix)+ if b, err := base64.StdEncoding.DecodeString(s); err == nil && len(b) > 0 {+ // Round-trip guard: only treat it as base64 if re-encoding matches+ // (ignoring padding), so arbitrary strings that happen to decode don't+ // silently change the key bytes.+ if strings.TrimRight(base64.StdEncoding.EncodeToString(b), "=") == strings.TrimRight(s, "=") {+ return b+ }+ }+ return []byte(secret)+}++// Sign returns the `webhook-signature` header value for a delivery:+//+// v1,<base64(HMAC-SHA256(key, "{webhookID}.{timestamp}.{rawBody}"))>+//+// webhookID is the delivery id (our contract; §7); timestamp is unix seconds.+// rawBody MUST be the exact bytes that go on the wire — sign before any+// re-serialization.+func Sign(secret, webhookID string, timestamp int64, rawBody []byte) string {+ mac := hmac.New(sha256.New, SecretKeyBytes(secret))+ mac.Write([]byte(webhookID))+ mac.Write([]byte("."))+ mac.Write([]byte(strconv.FormatInt(timestamp, 10)))+ mac.Write([]byte("."))+ mac.Write(rawBody)+ return "v1," + base64.StdEncoding.EncodeToString(mac.Sum(nil))+}++// Headers builds the full set of HTTP headers for a signed delivery POST. The+// dispatcher and the synchronous /test endpoint both use this so the wire+// format is defined in exactly one place.+//+// - webhook-id = deliveryID (recipients dedupe on this)+// - webhook-timestamp = unix seconds (replay guard)+// - webhook-signature = Sign(...)+// - X-OC-Delivery-ID / X-OC-Sandbox-ID for correlation+func Headers(secret, deliveryID, sandboxID string, timestamp int64, rawBody []byte) map[string]string {+ return map[string]string{+ "Content-Type": "application/json",+ "User-Agent": "OpenComputer-Webhooks/1",+ "webhook-id": deliveryID,+ "webhook-timestamp": strconv.FormatInt(timestamp, 10),+ "webhook-signature": Sign(secret, deliveryID, timestamp, rawBody),+ "X-OC-Delivery-ID": deliveryID,+ "X-OC-Sandbox-ID": sandboxID,+ }+}diff --git a/internal/webhook/sign_test.go b/internal/webhook/sign_test.gonew file mode 100644index 00000000..41062486--- /dev/null+++ b/internal/webhook/sign_test.go@@ -0,0 +1,107 @@+package webhook++import (+ "crypto/hmac"+ "crypto/sha256"+ "encoding/base64"+ "strconv"+ "strings"+ "testing"+)++// TestSignMatchesStandardWebhooks proves Sign produces exactly+// v1,base64(HMAC-SHA256(key, "{id}.{ts}.{body}")) where key is recovered from+// the whsec_ secret — i.e. byte-for-byte what the shipped TS verifyWebhook+// computes. The expected value is derived from the RAW key (not via Sign), so+// this also exercises SecretKeyBytes' decode path, not a tautology.+func TestSignMatchesStandardWebhooks(t *testing.T) {+ key := []byte("0123456789abcdef0123456789abcdef") // 32 bytes+ secret := SecretPrefix + base64.StdEncoding.EncodeToString(key)+ id := "whd_abc123"+ ts := int64(1700000000)+ body := []byte(`{"type":"sandbox.stopped","event":{"data":{"reason":"user_requested"}}}`)++ mac := hmac.New(sha256.New, key)+ mac.Write([]byte(id + "." + strconv.FormatInt(ts, 10) + "."))+ mac.Write(body)+ want := "v1," + base64.StdEncoding.EncodeToString(mac.Sum(nil))++ got := Sign(secret, id, ts, body)+ if got != want {+ t.Fatalf("Sign mismatch:\n got=%s\nwant=%s", got, want)+ }+}++func TestSignDeterministicAndBodySensitive(t *testing.T) {+ secret, err := GenerateSecret()+ if err != nil {+ t.Fatal(err)+ }+ a := Sign(secret, "whd_1", 1700000000, []byte(`{"a":1}`))+ b := Sign(secret, "whd_1", 1700000000, []byte(`{"a":1}`))+ if a != b {+ t.Fatal("Sign is not deterministic")+ }+ if !strings.HasPrefix(a, "v1,") {+ t.Fatalf("missing v1 prefix: %s", a)+ }+ if Sign(secret, "whd_1", 1700000000, []byte(`{"a":2}`)) == a {+ t.Fatal("signature did not change with body")+ }+ if Sign(secret, "whd_2", 1700000000, []byte(`{"a":1}`)) == a {+ t.Fatal("signature did not change with webhook-id")+ }+}++func TestGenerateSecret(t *testing.T) {+ s, err := GenerateSecret()+ if err != nil {+ t.Fatal(err)+ }+ if !strings.HasPrefix(s, SecretPrefix) {+ t.Fatalf("missing whsec_ prefix: %s", s)+ }+ raw := strings.TrimPrefix(s, SecretPrefix)+ dec, err := base64.StdEncoding.DecodeString(raw)+ if err != nil {+ t.Fatalf("secret body is not standard base64: %v", err)+ }+ if len(dec) != secretBytes {+ t.Fatalf("want %d random bytes, got %d", secretBytes, len(dec))+ }+ // Two generated secrets must differ.+ s2, _ := GenerateSecret()+ if s == s2 {+ t.Fatal("GenerateSecret returned identical secrets")+ }+}++func TestSecretKeyBytes(t *testing.T) {+ key := []byte("an-arbitrary-32-byte-long-keyAAA")+ secret := SecretPrefix + base64.StdEncoding.EncodeToString(key)+ if got := SecretKeyBytes(secret); string(got) != string(key) {+ t.Fatalf("base64 secret not decoded to raw key bytes")+ }+ // A non-base64 secret falls back to its raw UTF-8 bytes (whole string).+ weird := "whsec_not valid base64!!!"+ if got := SecretKeyBytes(weird); string(got) != weird {+ t.Fatalf("non-base64 secret should fall back to raw bytes, got %q", got)+ }+}++func TestHeaders(t *testing.T) {+ secret, _ := GenerateSecret()+ h := Headers(secret, "whd_xyz", "sb-1", 1700000000, []byte(`{}`))+ if h["webhook-id"] != "whd_xyz" {+ t.Fatalf("webhook-id should be the delivery id, got %q", h["webhook-id"])+ }+ if h["X-OC-Delivery-ID"] != "whd_xyz" || h["X-OC-Sandbox-ID"] != "sb-1" {+ t.Fatal("correlation headers not set")+ }+ if !strings.HasPrefix(h["webhook-signature"], "v1,") {+ t.Fatal("signature header malformed")+ }+ if h["webhook-timestamp"] != "1700000000" {+ t.Fatalf("timestamp header wrong: %s", h["webhook-timestamp"])+ }+}diff --git a/internal/webhook/ssrf.go b/internal/webhook/ssrf.gonew file mode 100644index 00000000..581e9ad4--- /dev/null+++ b/internal/webhook/ssrf.go@@ -0,0 +1,167 @@+package webhook++import (+ "context"+ "errors"+ "fmt"+ "net"+ "net/http"+ "net/url"+ "time"+)++// SSRFError is returned when a webhook URL is refused for pointing at a+// disallowed address (at registration or at send time). The dispatcher+// classifies it as a permanent failure (dead-letter, never retried).+type SSRFError struct {+ Reason string // machine-readable: scheme_not_https, blocked_ip, unresolvable, ...+ Detail string+}++func (e *SSRFError) Error() string { return fmt.Sprintf("ssrf: %s (%s)", e.Reason, e.Detail) }++// IsSSRFError reports whether err is (or wraps) an *SSRFError.+func IsSSRFError(err error) bool {+ var e *SSRFError+ return errors.As(err, &e)+}++// blockedNets are CIDR ranges we refuse to deliver to, on top of the net.IP+// classification helpers used in isBlockedIP. Ported from sessions-api+// src/v3/delivery/ssrf.ts; we fail CLOSED — if any resolved address of a host+// falls in a blocked range, the whole host is refused.+var blockedNets = mustParseCIDRs(+ "0.0.0.0/8", // "this network"+ "169.254.0.0/16", // link-local + cloud metadata (169.254.169.254)+ "192.0.0.0/24", // IETF protocol assignments+ "192.0.2.0/24", // TEST-NET-1+ "198.18.0.0/15", // benchmarking+ "198.51.100.0/24", // TEST-NET-2+ "203.0.113.0/24", // TEST-NET-3+ "100.64.0.0/10", // CGNAT (RFC 6598)+ "240.0.0.0/4", // reserved+ "255.255.255.255/32", // limited broadcast+ "fec0::/10", // IPv6 site-local (deprecated)+)++func mustParseCIDRs(cidrs ...string) []*net.IPNet {+ out := make([]*net.IPNet, 0, len(cidrs))+ for _, c := range cidrs {+ _, n, err := net.ParseCIDR(c)+ if err != nil {+ panic("webhook: bad blocked CIDR " + c + ": " + err.Error())+ }+ out = append(out, n)+ }+ return out+}++// isBlockedIP reports whether ip is in a disallowed range. nil (unparseable)+// fails closed. IPv4-mapped IPv6 is normalized so a mapped loopback/private+// address can't slip through.+func isBlockedIP(ip net.IP) bool {+ if ip == nil {+ return true+ }+ if v4 := ip.To4(); v4 != nil {+ ip = v4+ }+ if ip.IsLoopback() || ip.IsUnspecified() ||+ ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() ||+ ip.IsMulticast() || ip.IsInterfaceLocalMulticast() ||+ ip.IsPrivate() { // 10/8, 172.16/12, 192.168/16, fc00::/7+ return true+ }+ for _, n := range blockedNets {+ if n.Contains(ip) {+ return true+ }+ }+ return false+}++// ValidateURL enforces the registration-time policy: https only, a non-empty+// host, and every resolved address allowed (fail closed). Use it on+// POST/PATCH /api/webhooks before persisting a destination.+func ValidateURL(ctx context.Context, raw string) error {+ u, err := url.Parse(raw)+ if err != nil {+ return &SSRFError{Reason: "invalid_url", Detail: err.Error()}+ }+ if u.Scheme != "https" {+ return &SSRFError{Reason: "scheme_not_https", Detail: u.Scheme}+ }+ host := u.Hostname()+ if host == "" {+ return &SSRFError{Reason: "empty_host", Detail: raw}+ }+ if lit := net.ParseIP(host); lit != nil {+ if isBlockedIP(lit) {+ return &SSRFError{Reason: "literal_ip_blocked", Detail: host}+ }+ return nil+ }+ resolved, err := net.DefaultResolver.LookupIPAddr(ctx, host)+ if err != nil || len(resolved) == 0 {+ return &SSRFError{Reason: "unresolvable", Detail: host}+ }+ for _, a := range resolved {+ if isBlockedIP(a.IP) {+ return &SSRFError{Reason: "blocked_ip", Detail: a.IP.String()}+ }+ }+ return nil+}++// SafeClient returns an *http.Client that, on every connection, re-resolves the+// host, refuses it if any address is blocked, and PINS the TCP connection to the+// vetted IP — defeating DNS-rebind between validation and send. It does not+// follow redirects (a 3xx is returned as-is so the dispatcher can dead-letter+// it). The URL hostname is still used for TLS SNI / certificate verification,+// because only the dial address is overridden.+func SafeClient(connectTimeout, totalTimeout time.Duration) *http.Client {+ dialer := &net.Dialer{Timeout: connectTimeout}+ tr := &http.Transport{+ DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {+ return safeDial(ctx, dialer, network, addr)+ },+ TLSHandshakeTimeout: connectTimeout,+ ResponseHeaderTimeout: totalTimeout,+ DisableKeepAlives: true,+ }+ return &http.Client{+ Transport: tr,+ Timeout: totalTimeout,+ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },+ }+}++// safeDial resolves addr, refuses it if any resolved IP is blocked (fail+// closed), and dials the first vetted IP.+func safeDial(ctx context.Context, dialer *net.Dialer, network, addr string) (net.Conn, error) {+ host, port, err := net.SplitHostPort(addr)+ if err != nil {+ return nil, err+ }+ var ips []net.IP+ if lit := net.ParseIP(host); lit != nil {+ ips = []net.IP{lit}+ } else {+ resolved, rerr := net.DefaultResolver.LookupIPAddr(ctx, host)+ if rerr != nil {+ return nil, &SSRFError{Reason: "unresolvable", Detail: host}+ }+ for _, a := range resolved {+ ips = append(ips, a.IP)+ }+ }+ if len(ips) == 0 {+ return nil, &SSRFError{Reason: "unresolvable", Detail: host}+ }+ for _, ip := range ips {+ if isBlockedIP(ip) {+ return nil, &SSRFError{Reason: "blocked_ip", Detail: ip.String()}+ }+ }+ return dialer.DialContext(ctx, network, net.JoinHostPort(ips[0].String(), port))+}diff --git a/internal/webhook/ssrf_test.go b/internal/webhook/ssrf_test.gonew file mode 100644index 00000000..cb36d19a--- /dev/null+++ b/internal/webhook/ssrf_test.go@@ -0,0 +1,101 @@+package webhook++import (+ "context"+ "net"+ "testing"+)++func TestIsBlockedIP(t *testing.T) {+ blocked := []string{+ "127.0.0.1", // loopback+ "::1", // v6 loopback+ "0.0.0.0", // unspecified+ "10.0.0.1", // RFC1918+ "172.16.5.4", // RFC1918+ "172.31.255.255", // RFC1918 edge+ "192.168.1.1", // RFC1918+ "169.254.169.254", // link-local / cloud metadata+ "100.64.0.1", // CGNAT+ "192.0.2.5", // TEST-NET-1+ "198.51.100.7", // TEST-NET-2+ "203.0.113.9", // TEST-NET-3+ "198.18.0.1", // benchmarking+ "224.0.0.1", // multicast+ "240.0.0.1", // reserved+ "255.255.255.255", // broadcast+ "fe80::1", // v6 link-local+ "fc00::1", // v6 ULA+ "::ffff:127.0.0.1", // v4-mapped loopback+ "::ffff:10.0.0.1", // v4-mapped private+ }+ for _, s := range blocked {+ ip := net.ParseIP(s)+ if ip == nil {+ t.Fatalf("test bug: unparseable %q", s)+ }+ if !isBlockedIP(ip) {+ t.Errorf("expected BLOCKED: %s", s)+ }+ }++ allowed := []string{+ "8.8.8.8",+ "1.1.1.1",+ "93.184.216.34", // example.com+ "2606:2800:220:1:248:1893:25c8:1946",+ }+ for _, s := range allowed {+ ip := net.ParseIP(s)+ if ip == nil {+ t.Fatalf("test bug: unparseable %q", s)+ }+ if isBlockedIP(ip) {+ t.Errorf("expected ALLOWED: %s", s)+ }+ }++ // nil fails closed.+ if !isBlockedIP(nil) {+ t.Error("nil IP must fail closed (blocked)")+ }+}++func TestValidateURL(t *testing.T) {+ ctx := context.Background()+ // These never hit DNS (scheme/host/literal-IP checks short-circuit).+ cases := []struct {+ url string+ wantErr bool+ reason string // expected SSRFError.Reason when wantErr+ }{+ {"http://example.com/hook", true, "scheme_not_https"},+ {"ftp://example.com", true, "scheme_not_https"},+ {"https://", true, "empty_host"},+ {"https://127.0.0.1/x", true, "literal_ip_blocked"},+ {"https://10.0.0.1", true, "literal_ip_blocked"},+ {"https://[::1]/x", true, "literal_ip_blocked"},+ {"https://169.254.169.254/latest/meta-data", true, "literal_ip_blocked"},+ {"https://8.8.8.8/ok", false, ""},+ }+ for _, c := range cases {+ err := ValidateURL(ctx, c.url)+ if c.wantErr {+ if err == nil {+ t.Errorf("%s: expected error", c.url)+ continue+ }+ var se *SSRFError+ if !IsSSRFError(err) {+ t.Errorf("%s: expected *SSRFError, got %T", c.url, err)+ continue+ }+ se, _ = err.(*SSRFError)+ if se.Reason != c.reason {+ t.Errorf("%s: reason = %q, want %q", c.url, se.Reason, c.reason)+ }+ } else if err != nil {+ t.Errorf("%s: unexpected error %v", c.url, err)+ }+ }+}diff --git a/pkg/types/sandbox.go b/pkg/types/sandbox.goindex 07da0415..e90fb975 100644--- a/pkg/types/sandbox.go+++ b/pkg/types/sandbox.go@@ -39,6 +39,10 @@ type Sandbox struct {// preview URL, returned exactly once on create when previewAuth was// requested. Empty otherwise. Mirrors the SDK field by the same name.PreviewAuthToken string `json:"previewAuthToken,omitempty"`+ // Webhooks echoes inline webhooks registered on create (see+ // SandboxConfig.Webhooks). Each entry's signing secret is present once,+ // only when OpenComputer generated it. Empty unless webhooks were requested.+ Webhooks []SandboxWebhookResult `json:"webhooks,omitempty"`}// SandboxPreviewAuth controls the per-sandbox bearer-token gate that the CP@@ -65,6 +69,11 @@ type SandboxConfig struct {DiskMB int `json:"diskMB,omitempty"` // workspace disk in MB (default 20480)Envs map[string]string `json:"envs,omitempty"`PreviewAuth *SandboxPreviewAuth `json:"previewAuth,omitempty"`+ // Webhooks registers sandbox lifecycle webhooks atomically with the+ // sandbox, pinned to it — so they catch created/ready (which fire before a+ // separate webhooks.create could know the sandbox id). See+ // .agents/work/sandbox-lifecycle-webhooks.md.+ Webhooks []SandboxWebhookSpec `json:"webhooks,omitempty"`Port int `json:"port,omitempty"` // container port to expose via subdomain (default 80)// NetworkEnabled is a pointer so we can distinguish "unset" from// "explicitly false". Unset defaults to true (see IsNetworkEnabled).diff --git a/pkg/types/webhook.go b/pkg/types/webhook.gonew file mode 100644index 00000000..97d65446--- /dev/null+++ b/pkg/types/webhook.go@@ -0,0 +1,132 @@+package types++import (+ "encoding/json"+ "time"+)++// Sandbox lifecycle webhook event types (the public taxonomy). Wire values are+// the camelCase/namespaced public names; internal worker strings ("created",+// "running", "migrated") are mapped to these at the ingress.+const (+ WebhookEventCreated = "sandbox.created"+ WebhookEventReady = "sandbox.ready"+ WebhookEventHibernated = "sandbox.hibernated"+ WebhookEventResumed = "sandbox.resumed"+ WebhookEventStopped = "sandbox.stopped"+ WebhookEventMigrated = "sandbox.migrated"+ WebhookEventCheckpointCreated = "sandbox.checkpoint.created"+ WebhookEventForked = "sandbox.forked"+ WebhookEventScaled = "sandbox.scaled"+ WebhookEventPreviewURLChanged = "sandbox.preview_url.changed"+ WebhookEventTest = "sandbox.test"+)++// Delivery statuses. failed = retryable (future next_attempt_at); dead_letter &+// canceled are terminal.+const (+ WebhookDeliveryPending = "pending"+ WebhookDeliveryDelivering = "delivering"+ WebhookDeliveryDelivered = "delivered"+ WebhookDeliveryFailed = "failed"+ WebhookDeliveryDeadLetter = "dead_letter"+ WebhookDeliveryCanceled = "canceled"+)++// WebhookDestination is the public (camelCase) representation of a subscription.+// Name and SandboxID are pointers so an unset value serializes as JSON null+// (matching the documented contract). Secret is present ONLY on the create+// response or a generated rotation — never on reads.+type WebhookDestination struct {+ ID string `json:"id"`+ Name *string `json:"name"`+ URL string `json:"url"`+ EventTypes []string `json:"eventTypes"`+ SandboxID *string `json:"sandboxId"`+ Enabled bool `json:"enabled"`+ HasSecret bool `json:"hasSecret"`+ CreatedAt time.Time `json:"createdAt"`+ UpdatedAt time.Time `json:"updatedAt"`+ Secret string `json:"secret,omitempty"`+}++// CreateWebhookRequest is the POST /api/webhooks body.+type CreateWebhookRequest struct {+ URL string `json:"url"`+ Name *string `json:"name,omitempty"`+ Secret string `json:"secret,omitempty"`+ EventTypes []string `json:"eventTypes,omitempty"`+ SandboxID *string `json:"sandboxId,omitempty"`+ Enabled *bool `json:"enabled,omitempty"`+}++// WebhookDelivery is the public (camelCase) delivery record. Nullable fields are+// pointers so they serialize as JSON null rather than being omitted.+type WebhookDelivery struct {+ ID string `json:"id"`+ Destination string `json:"destination"`+ EventID string `json:"eventId"`+ EventType string `json:"eventType"`+ Status string `json:"status"`+ Attempts int `json:"attempts"`+ RetryCount int `json:"retryCount"`+ LastAttemptAt *time.Time `json:"lastAttemptAt"`+ ResponseCode *int `json:"responseCode"`+ Error *string `json:"error"`+ CreatedAt time.Time `json:"createdAt"`+ UpdatedAt time.Time `json:"updatedAt"`+ DeliveredAt *time.Time `json:"deliveredAt"`+}++// WebhookDeliveryPage is a cursor-paginated list of deliveries.+type WebhookDeliveryPage struct {+ Data []WebhookDelivery `json:"data"`+ NextCursor *string `json:"nextCursor"`+ HasMore bool `json:"hasMore"`+}++// WebhookTestResult is the synchronous POST /api/webhooks/:id/test response.+type WebhookTestResult struct {+ Delivered bool `json:"delivered"`+ ResponseCode *int `json:"responseCode"`+ Error string `json:"error,omitempty"`+}++// SandboxLifecycleEvent is the lifecycle event nested under `event` in a+// delivery envelope.+type SandboxLifecycleEvent struct {+ ID string `json:"id"`+ Ts time.Time `json:"ts"`+ OrgID string `json:"orgId"`+ SandboxID string `json:"sandboxId"`+ Type string `json:"type"`+ Data json.RawMessage `json:"data"`+}++// SandboxWebhookEnvelope is the JSON body POSTed to a destination. webhook-id+// header == DeliveryID. Metadata is the sandbox's user-set metadata (verbatim,+// for routing without a second lookup); null if unset.+type SandboxWebhookEnvelope struct {+ Type string `json:"type"`+ SandboxID string `json:"sandboxId"`+ EventID string `json:"eventId"`+ DeliveryID string `json:"deliveryId"`+ Metadata map[string]string `json:"metadata"`+ Event SandboxLifecycleEvent `json:"event"`+}++// SandboxWebhookSpec is an inline webhook on POST /api/sandboxes — registered+// atomically with the sandbox and pinned to it, so it catches created/ready.+type SandboxWebhookSpec struct {+ URL string `json:"url"`+ Secret string `json:"secret,omitempty"`+ EventTypes []string `json:"eventTypes,omitempty"`+}++// SandboxWebhookResult echoes an inline-registered webhook on the create+// response. Secret is present once iff generated.+type SandboxWebhookResult struct {+ ID string `json:"id"`+ URL string `json:"url"`+ Secret string `json:"secret,omitempty"`+}