Skip to content

An open-source, faster Devin alternative

TypeScript

refactor(webhooks): delete shipped CP delivery/management stack (#33/#39)

Igor Zalutskid660487fab29
diff --git a/deploy/gcp/deploy-qemu-dev.sh b/deploy/gcp/deploy-qemu-dev.sh
index 6fec9ae3..b9c86037 100755
--- a/deploy/gcp/deploy-qemu-dev.sh
+++ b/deploy/gcp/deploy-qemu-dev.sh
@@ -338,7 +338,12 @@ OPENSANDBOX_S3_REGION=${s3_region}
OPENSANDBOX_S3_ACCESS_KEY_ID=${s3_ak}
OPENSANDBOX_S3_SECRET_ACCESS_KEY=${s3_sk}
OPENSANDBOX_MIN_WORKERS=1
-SVIX_API_TOKEN=${SVIX_API_TOKEN:-}
+# Webhooks (all-Svix-at-edge): forward lifecycle events to the edge events-ingest
+# Worker and reach the edge for inline-on-create registration. Set these to the
+# igor-dev edge stack to exercise webhooks end-to-end (sandbox-webhooks-rearchitecture.md §8).
+OPENSANDBOX_CF_EVENT_ENDPOINT=${OPENSANDBOX_CF_EVENT_ENDPOINT:-}
+OPENSANDBOX_CF_EVENT_SECRET=${OPENSANDBOX_CF_EVENT_SECRET:-}
+OPENSANDBOX_CF_EDGE_BASE_URL=${OPENSANDBOX_CF_EDGE_BASE_URL:-}
WORKOS_API_KEY=${workos_api_key}
WORKOS_CLIENT_ID=${workos_client_id}
WORKOS_REDIRECT_URI=${workos_redirect_uri}
diff --git a/internal/api/router.go b/internal/api/router.go
index 76a902f9..47dd4aa7 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -430,16 +430,11 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
api.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)
+ // Sandbox lifecycle webhooks are served by the api-edge Worker (all-Svix-at-edge):
+ // the edge handles /api/webhooks* before its proxy catch-all, so the CP no longer
+ // mounts these routes. The CP only sources lifecycle events (the outbox + relay)
+ // and registers inline webhooks via the edge internal API.
+ // (.agents/work/sandbox-webhooks-rearchitecture.md)
// Hibernation
api.POST("/sandboxes/:id/hibernate", s.hibernateSandbox)
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 2f2a88b0..0700418f 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -698,11 +698,11 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
if s.store != nil {
errMsg := err.Error()
_ = s.store.UpdateSandboxSessionStatus(ctx, sandboxID, "failed", &errMsg)
- // Clean up inline webhooks registered for a sandbox that never started.
- for _, w := range inlineWebhooks {
- _ = s.store.SoftDeleteWebhookDestination(ctx, orgID, w.ID)
- }
}
+ // Inline webhooks were registered at the edge (Svix); a sandbox that never
+ // started simply emits no events, so the endpoints sit idle. Edge-side
+ // orphan cleanup is a future nicety, not worth a synchronous edge call on
+ // the create-failure path.
// A worker that is restarting/unreachable is transient — return a
// retryable 503 (with Retry-After) instead of a raw 500 so callers retry
// and the edge can reselect a worker.
diff --git a/internal/api/webhooks.go b/internal/api/webhooks.go
index 0b1ad980..3cafb0af 100644
--- a/internal/api/webhooks.go
+++ b/internal/api/webhooks.go
@@ -1,128 +1,24 @@
package api
import (
- "bytes"
"context"
- "crypto/sha256"
- "encoding/hex"
"encoding/json"
- "errors"
"fmt"
- "io"
"log"
- "net/http"
- "strconv"
+ "net/url"
"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)
- // Include enabled + secret so the same key with a different paused state or
- // signing secret is a different request (→ 409), not a silent reuse.
- en := "unset"
- if req.Enabled != nil {
- en = fmt.Sprintf("%t", *req.Enabled)
- }
- fmt.Fprintf(h, "enabled=%s\n", en)
- fmt.Fprintf(h, "secret=%s\n", req.Secret)
- return hex.EncodeToString(h.Sum(nil))
-}
+// CP-origin sandbox-webhook source layer. All-Svix-at-edge: webhook management +
+// delivery live at the edge (api-edge → Svix, events-ingest → Svix). The CP only
+// (1) captures CP-origin lifecycle events into the outbox (recordLifecycle*) and
+// (2) forwards inline-on-create specs to the edge (registerInlineWebhooksEdge).
+// See .agents/work/sandbox-webhooks-rearchitecture.md.
// recordLifecycleID records a CP-origin lifecycle event with an explicit,
// caller-supplied event id (use a deterministic id for once-per-entity events so
@@ -156,9 +52,9 @@ func (s *Server) recordLifecycle(ctx context.Context, orgID uuid.UUID, sandboxID
}
// registerInlineWebhooksEdge registers inline webhooks via the edge (Svix) at
-// create time — the all-Svix-at-edge replacement for registerInlineWebhooks.
-// Nil-safe + best-effort: returns nil (logging) if there's no edge client or the
-// edge call fails, so a webhook hiccup never fails the sandbox create.
+// create time. Nil-safe + best-effort: returns nil (logging) if there's no edge
+// client or the edge call fails, so a webhook hiccup never fails the sandbox
+// create. The CP never talks to Svix directly.
func (s *Server) registerInlineWebhooksEdge(ctx context.Context, orgID uuid.UUID, sandboxID string, specs []types.SandboxWebhookSpec) []types.SandboxWebhookResult {
if s.edge == nil || len(specs) == 0 {
return nil
@@ -171,460 +67,20 @@ func (s *Server) registerInlineWebhooksEdge(ctx context.Context, orgID uuid.UUID
return res
}
-// 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))
+// validateInlineWebhooks validates inline webhook specs up-front so a bad URL or
+// event-type fails the create with a 400 (rather than being silently skipped at
+// the edge). Returns the first error found.
+func validateInlineWebhooks(_ context.Context, specs []types.SandboxWebhookSpec) error {
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
+ u, err := url.Parse(spec.URL)
+ if err != nil || u.Scheme != "https" || u.Host == "" {
+ return fmt.Errorf("webhook url must be a valid https URL: %q", spec.URL)
}
- 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
+ for _, et := range spec.EventTypes {
+ if !types.ValidWebhookEventFilter(et) {
+ return fmt.Errorf("invalid webhook event type filter: %q", et)
}
- 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()})
- }
- if bad := firstInvalidEventType(req.EventTypes); bad != "" {
- return c.JSON(http.StatusBadRequest, map[string]string{"error": "unknown event type: " + bad})
- }
- if req.SandboxID != nil {
- owned, err := store.SandboxBelongsToOrg(ctx, orgID, *req.SandboxID)
- if err != nil {
- return webhookStoreError(c, err)
- }
- if !owned {
- return c.JSON(http.StatusBadRequest, map[string]string{"error": "sandboxId not found for this org"})
- }
- }
-
- idemKey := c.Request().Header.Get("Idempotency-Key")
- claimed := false
- if idemKey != "" {
- outcome, stored, err := store.ReserveIdempotencyKey(ctx, orgID, idemKey, webhookRequestHash(req))
- if err != nil {
- return webhookStoreError(c, err)
- }
- switch outcome {
- case db.WebhookIdemReplay:
- return c.JSONBlob(http.StatusCreated, stored)
- case db.WebhookIdemConflict:
- return c.JSON(http.StatusConflict, map[string]string{"error": "Idempotency-Key reused with a different request"})
- case db.WebhookIdemInProgress:
- // Transient: another request holds the claim. Signal retryability so
- // clients/agents don't treat it as fatal.
- c.Response().Header().Set("Retry-After", "1")
- return c.JSON(http.StatusConflict, map[string]string{
- "error": "a request with this Idempotency-Key is already in progress; retry shortly",
- "code": "idempotency_in_progress",
- })
- case db.WebhookIdemClaimed:
- claimed = true
- }
- }
- // From here on, any early return must release the claim so a retry can proceed.
- release := func() {
- if claimed {
- _ = store.ReleaseIdempotencyKey(ctx, orgID, idemKey)
- }
- }
-
- secret := req.Secret
- generated := false
- if secret == "" {
- gen, err := webhook.GenerateSecret()
- if err != nil {
- release()
- 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 {
- release()
- 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 {
- release()
- return webhookStoreError(c, err)
- }
-
- echoSecret := ""
- status := http.StatusCreated
- if reused {
- status = http.StatusOK // existing destination matched by name — no secret echo
- } else if generated {
- echoSecret = secret
- }
- resp := toWireDestination(row, echoSecret)
-
- if claimed {
- body, _ := json.Marshal(resp)
- if ferr := store.FinalizeIdempotencyKey(ctx, orgID, idemKey, row.ID, body); ferr != nil {
- // The one-time secret would otherwise be unrecoverable — fail the
- // request and clean up so the client can safely retry.
- if !reused {
- _ = store.SoftDeleteWebhookDestination(ctx, orgID, row.ID)
- }
- _ = store.ReleaseIdempotencyKey(ctx, orgID, idemKey)
- return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to persist idempotent response; please retry"})
- }
- }
- return c.JSON(status, resp)
-}
-
-// validateInlineWebhooks checks inline webhook specs up-front (URL + event
-// types) so a bad spec fails sandbox creation rather than being silently skipped
-// (P2 review). Returns nil if all are valid (or none supplied).
-func validateInlineWebhooks(ctx context.Context, specs []types.SandboxWebhookSpec) error {
- for _, w := range specs {
- if w.URL == "" {
- return fmt.Errorf("webhooks[].url is required")
- }
- if err := webhook.ValidateURL(ctx, w.URL); err != nil {
- return fmt.Errorf("invalid webhook url: %w", err)
- }
- if bad := firstInvalidEventType(w.EventTypes); bad != "" {
- return fmt.Errorf("unknown event type: %s", bad)
}
}
return nil
}
-
-// firstInvalidEventType returns the first eventTypes entry that isn't a valid
-// exact type or "prefix.*" wildcard, or "" if all are valid.
-func firstInvalidEventType(ets []string) string {
- for _, e := range ets {
- if !types.ValidWebhookEventFilter(e) {
- return e
- }
- }
- return ""
-}
-
-// 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, ""))
- }
- // Canonical shape: { "data": [...] } (matches the docs + deliveries list).
- return c.JSON(http.StatusOK, map[string][]types.WebhookDestination{"data": 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 bad := firstInvalidEventType(et); bad != "" {
- return c.JSON(http.StatusBadRequest, map[string]string{"error": "unknown event type: " + bad})
- }
- 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/config/config.go b/internal/config/config.go
index 0b9463d9..81a9a86c 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -203,13 +203,6 @@ type Config struct {
CFEventEndpoint string
CFEventSecret string // HMAC secret shared with events-ingest Worker
- // SVIXAPIToken authenticates calls to Svix (managed webhook delivery). The
- // /api/webhooks proxy uses it to create the org's Svix app + endpoints; the
- // edge events-ingest Worker uses the same token to send messages. The Svix
- // region is encoded in the token suffix (e.g. "….us").
- // (.agents/work/sandbox-webhooks-rearchitecture.md)
- SVIXAPIToken string
-
// CF admin callback secret. Verifies HMAC signatures on /admin/halt-org and
// /admin/resume-org webhooks dispatched from the CreditAccount DO.
CFAdminSecret string
@@ -401,7 +394,6 @@ func Load() (*Config, error) {
CellID: os.Getenv("OPENSANDBOX_CELL_ID"),
CFEventEndpoint: os.Getenv("OPENSANDBOX_CF_EVENT_ENDPOINT"),
CFEventSecret: os.Getenv("OPENSANDBOX_CF_EVENT_SECRET"),
- SVIXAPIToken: os.Getenv("SVIX_API_TOKEN"),
CFAdminSecret: os.Getenv("OPENSANDBOX_CF_ADMIN_SECRET"),
SessionJWTSecret: os.Getenv("OPENSANDBOX_SESSION_JWT_SECRET"),
HaltListURL: os.Getenv("OPENSANDBOX_HALT_LIST_URL"),
diff --git a/internal/controlplane/webhook_dispatcher.go b/internal/controlplane/webhook_dispatcher.go
deleted file mode 100644
index a4ad7628..00000000
--- a/internal/controlplane/webhook_dispatcher.go
+++ /dev/null
@@ -1,275 +0,0 @@
-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, dd.LockedBy, 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, dd.LockedBy, 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, dd.LockedBy, 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/db/webhooks.go b/internal/db/webhooks.go
index c1bc2212..9b6656b3 100644
--- a/internal/db/webhooks.go
+++ b/internal/db/webhooks.go
@@ -2,48 +2,27 @@ 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[:])
-}
+// Sandbox lifecycle webhooks — CP source layer. All-Svix-at-edge: the CP only
+// CAPTURES lifecycle events into the outbox (sandbox_lifecycle_events); the relay
+// publishes them to the cell stream and the edge delivers via Svix. Destination
+// management + delivery state live at the edge (Svix + D1), not here.
+// See .agents/work/sandbox-webhooks-rearchitecture.md.
// ---------------------------------------------------------------------------
-// Canonical lifecycle events (the single recordLifecycleEvent primitive)
+// Lifecycle events (the in-tx outbox capture)
// ---------------------------------------------------------------------------
// LifecycleEvent is one canonical sandbox lifecycle moment.
type LifecycleEvent struct {
- ID string // deterministic event id (dedup key)
+ ID string // deterministic (once-only) or unique (recurring) event id
OrgID uuid.UUID
SandboxID string
Type string // public type, e.g. "sandbox.stopped"
@@ -51,18 +30,16 @@ type LifecycleEvent struct {
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).
+// recordLifecycleEvent inserts a lifecycle event into the outbox within the given
+// tx. ON CONFLICT (id) DO NOTHING makes re-records idempotent. CP-origin callers
+// use this inside their existing transaction for in-tx durability.
func recordLifecycleEvent(ctx context.Context, tx pgx.Tx, ev LifecycleEvent) error {
// All-Svix-at-edge: the CP records every CP-origin lifecycle event to the
// outbox unconditionally; the relay publishes them to the cell stream and the
// EDGE applies the dormancy gate (orgs.has_webhooks in D1) before calling
- // Svix. There is no CP-side gate — the CP no longer knows which orgs have
- // webhooks; that index lives at the edge. The outbox is a transient queue
- // (the relay deletes rows after publishing), so it stays bounded.
- // (sandbox-webhooks-rearchitecture.md)
+ // Svix. No CP-side gate — the CP no longer knows which orgs have webhooks; that
+ // index lives at the edge. The outbox is a transient queue (the relay deletes
+ // rows after publishing), so it stays bounded.
if len(ev.Data) == 0 {
ev.Data = json.RawMessage("{}")
}
@@ -81,9 +58,8 @@ func recordLifecycleEvent(ctx context.Context, tx pgx.Tx, ev LifecycleEvent) 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.
+// RecordLifecycleEvent records a lifecycle event in its own transaction (used by
+// CP-origin callers that don't already hold one).
func (s *Store) RecordLifecycleEvent(ctx context.Context, ev LifecycleEvent) error {
tx, err := s.pool.Begin(ctx)
if err != nil {
@@ -98,7 +74,7 @@ func (s *Store) RecordLifecycleEvent(ctx context.Context, ev LifecycleEvent) err
// recordOrphanStoppedTx records sandbox.stopped (reason crash) for sandboxes
// moved to a terminal failure state OUTSIDE UpdateSandboxSessionStatus (migration
-// failure, orphan/dead-worker sweeps), within the caller's tx so the webhook is
+// failure, orphan/dead-worker sweeps), within the caller's tx so the event is
// durable with the state change. The id matches the normal stopped id so a
// sandbox can never get two stopped events.
func recordOrphanStoppedTx(ctx context.Context, tx pgx.Tx, orphans []OrphanedSandbox) error {
@@ -119,16 +95,12 @@ func recordOrphanStoppedTx(ctx context.Context, tx pgx.Tx, orphans []OrphanedSan
return nil
}
-// 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
-}
+// ---------------------------------------------------------------------------
+// Outbox drain (CP relay → cell stream)
+// ---------------------------------------------------------------------------
-// LifecycleOutboxRow is an unrelayed lifecycle event drained from the in-tx
-// outbox (sandbox_lifecycle_events) for publishing to the cell stream.
+// LifecycleOutboxRow is a lifecycle event drained from the outbox for publishing
+// to the cell stream.
type LifecycleOutboxRow struct {
ID string
OrgID uuid.UUID
@@ -142,7 +114,7 @@ type LifecycleOutboxRow struct {
// seq). The relay publishes these to the events:{cell} stream, then deletes them
// via DeleteLifecycleOutbox. The outbox is a transient queue — the stream + edge
// + Svix are the durable downstream (and dedupe on the stable event id), so rows
-// don't need to be retained. See .agents/work/sandbox-webhooks-rearchitecture.md.
+// don't need to be retained.
func (s *Store) DrainLifecycleOutbox(ctx context.Context, batch int) ([]LifecycleOutboxRow, error) {
rows, err := s.pool.Query(ctx,
`SELECT id, org_id, sandbox_id, type, data, ts
@@ -177,891 +149,3 @@ func (s *Store) DeleteLifecycleOutbox(ctx context.Context, ids []string) error {
`DELETE FROM sandbox_lifecycle_events WHERE id = ANY($1)`, ids)
return 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) && existing.Enabled == p.Enabled {
- 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
-// ---------------------------------------------------------------------------
-
-// WebhookIdemOutcome is the result of reserving an Idempotency-Key.
-type WebhookIdemOutcome int
-
-const (
- WebhookIdemClaimed WebhookIdemOutcome = iota // we own a fresh claim; proceed to create + finalize
- WebhookIdemReplay // a finalized response exists (same request) → return it
- WebhookIdemInProgress // same key+request, claim held by a concurrent request, not finalized yet
- WebhookIdemConflict // same key, different request body
-)
-
-// ReserveIdempotencyKey atomically claims (org_id, key) for this create request
-// BEFORE any destination is created, so two concurrent same-key requests can't
-// both create. The unique PK makes the claim INSERT the single arbiter:
-// - we win the INSERT → WebhookIdemClaimed (caller must Finalize or Release)
-// - row exists, different hash → WebhookIdemConflict
-// - row exists, same hash, response stored → WebhookIdemReplay (+ decrypted body)
-// - row exists, same hash, not finalized → WebhookIdemInProgress
-func (s *Store) ReserveIdempotencyKey(ctx context.Context, orgID uuid.UUID, key, requestHash string) (WebhookIdemOutcome, []byte, error) {
- if s.encryptor == nil {
- return 0, nil, ErrEncryptionNotConfigured
- }
- tag, err := s.pool.Exec(ctx,
- `INSERT INTO webhook_idempotency_keys (org_id, key, request_hash)
- VALUES ($1, $2, $3) ON CONFLICT (org_id, key) DO NOTHING`,
- orgID, key, requestHash)
- if err != nil {
- return 0, nil, err
- }
- if tag.RowsAffected() == 1 {
- return WebhookIdemClaimed, nil, nil
- }
- var storedHash string
- var enc []byte // nullable until finalized
- 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 WebhookIdemInProgress, nil, nil // raced with a release; ask the client to retry
- }
- return 0, nil, err
- }
- if storedHash != requestHash {
- return WebhookIdemConflict, nil, nil
- }
- if enc == nil {
- return WebhookIdemInProgress, nil, nil
- }
- plain, err := s.encryptor.Decrypt(enc)
- if err != nil {
- return 0, nil, fmt.Errorf("decrypt idempotent response: %w", err)
- }
- return WebhookIdemReplay, plain, nil
-}
-
-// FinalizeIdempotencyKey attaches the destination + encrypted response to a claim
-// we own. Returns an error if the claim is missing or already finalized — the
-// caller MUST treat a finalize failure as fatal (the one-time secret would
-// otherwise be unrecoverable).
-func (s *Store) FinalizeIdempotencyKey(ctx context.Context, orgID uuid.UUID, key, 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)
- }
- tag, err := s.pool.Exec(ctx,
- `UPDATE webhook_idempotency_keys SET destination_id = $3, response_enc = $4
- WHERE org_id = $1 AND key = $2 AND response_enc IS NULL`,
- orgID, key, destinationID, enc)
- if err != nil {
- return err
- }
- if tag.RowsAffected() == 0 {
- return fmt.Errorf("idempotency claim missing or already finalized")
- }
- return nil
-}
-
-// ReleaseIdempotencyKey drops an unfinalized claim so a later retry can proceed
-// (used when create or finalize fails).
-func (s *Store) ReleaseIdempotencyKey(ctx context.Context, orgID uuid.UUID, key string) error {
- _, err := s.pool.Exec(ctx,
- `DELETE FROM webhook_idempotency_keys WHERE org_id = $1 AND key = $2 AND response_enc IS NULL`,
- orgID, key)
- 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.OrgID, 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) {
- // Match disabled destinations too: enabled=false means PAUSE, not drop, so we
- // create the delivery rows now and let them queue. The dispatcher's claim
- // (ClaimDueDeliveries) is what skips disabled destinations, so paused rows
- // simply wait and deliver on re-enable.
- rows, err := tx.Query(ctx,
- `SELECT id, event_types FROM webhook_destinations
- WHERE org_id = $1 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, orgID uuid.UUID, sandboxID string) (map[string]string, error) {
- var raw []byte
- // Scope by org too: sandbox ids are NOT globally unique, so a sandbox_id-only
- // lookup could pull another org's metadata into this org's webhook payload.
- err := tx.QueryRow(ctx,
- `SELECT metadata FROM sandbox_sessions WHERE org_id = $1 AND sandbox_id = $2 ORDER BY started_at DESC LIMIT 1`,
- orgID, 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)
- LockedBy string // this dispatcher's lock token; used to record results safely
-}
-
-// 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,
- LockedBy: lockedBy,
- })
- }
- 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.
-// It only updates a row THIS dispatcher still owns (status='delivering' AND
-// locked_by=lockedBy), so a stale sender can't revive a row that was meanwhile
-// canceled (destination deleted) or redelivered (reset to pending by a manual
-// redeliver or the reconciler). Returns whether the row was updated.
-func (s *Store) RecordDeliveryResult(ctx context.Context, id, lockedBy string, r DeliveryResult) (bool, error) {
- var delivered *time.Time
- if r.Status == "delivered" {
- now := time.Now()
- delivered = &now
- }
- tag, err := s.pool.Exec(ctx,
- `UPDATE webhook_deliveries
- SET status = $3, response_code = $4, error = $5,
- next_attempt_at = COALESCE($6, next_attempt_at),
- delivered_at = COALESCE($7, delivered_at),
- locked_by = NULL, locked_until = NULL, updated_at = now()
- WHERE id = $1 AND status = 'delivering' AND locked_by = $2`,
- id, lockedBy, r.Status, r.ResponseCode, r.Error, r.NextAttemptAt, delivered)
- if err != nil {
- return false, err
- }
- return tag.RowsAffected() > 0, nil
-}
-
-// 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. Refuses a soft-deleted destination — the dispatcher
-// would never claim it (its claim filters deleted), so re-enqueuing would just
-// strand the row in pending; callers should treat this as 404.
-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 d
- 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 d.id = $1 AND d.destination_id = $2 AND d.org_id = $3
- AND EXISTS (SELECT 1 FROM webhook_destinations dst
- WHERE dst.id = d.destination_id AND dst.deleted_at IS NULL)
- 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
-}
-
-// destinationOwnedByOrg verifies a destination belongs to the org, INCLUDING
-// soft-deleted ones (for delivery-history access after deletion). Returns
-// ErrWebhookNotFound if no such row exists for the org.
-func (s *Store) destinationOwnedByOrg(ctx context.Context, orgID uuid.UUID, id string) error {
- var exists bool
- err := s.pool.QueryRow(ctx,
- `SELECT true FROM webhook_destinations WHERE id = $1 AND org_id = $2`, id, orgID).Scan(&exists)
- if err != nil {
- if errors.Is(err, pgx.ErrNoRows) {
- return ErrWebhookNotFound
- }
- return err
- }
- return nil
-}
-
-// SandboxBelongsToOrg reports whether sandboxID is owned by orgID — used to
-// validate a webhook's sandbox scope at registration.
-func (s *Store) SandboxBelongsToOrg(ctx context.Context, orgID uuid.UUID, sandboxID string) (bool, error) {
- var exists bool
- err := s.pool.QueryRow(ctx,
- `SELECT EXISTS(SELECT 1 FROM sandbox_sessions WHERE sandbox_id = $1 AND org_id = $2)`,
- sandboxID, orgID).Scan(&exists)
- return exists, err
-}
-
-// 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). Soft-deleted destinations are allowed here — their delivery
- // history is retained and remains queryable.
- if err := s.destinationOwnedByOrg(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/svix/client.go b/internal/svix/client.go
deleted file mode 100644
index f61ddc62..00000000
--- a/internal/svix/client.go
+++ /dev/null
@@ -1,304 +0,0 @@
-// Package svix is a thin REST client for the Svix managed-webhook API. OC uses
-// Svix for webhook delivery (retries, signing, SSRF, logs); this client lets the
-// /api/webhooks proxy manage the org's Svix Application + Endpoints and read its
-// delivery (attempt) logs. The edge events-ingest Worker sends messages via its
-// own (TS) client. See .agents/work/sandbox-webhooks-rearchitecture.md.
-//
-// Region is encoded in the token suffix (e.g. "sk_….us" → api.us.svix.com).
-package svix
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "net/http"
- "strings"
- "time"
-)
-
-// Client talks to one Svix region (derived from the token suffix).
-type Client struct {
- token string
- baseURL string
- hc *http.Client
-}
-
-// NewClient builds a Svix client. token is "sk_<base>.<region>"; the region after
-// the final '.' selects the API host (us/eu/in → api.<region>.svix.com). A token
-// with no region suffix falls back to api.svix.com.
-func NewClient(token string) *Client {
- return &Client{
- token: token,
- baseURL: baseURLForToken(token),
- hc: &http.Client{Timeout: 15 * time.Second},
- }
-}
-
-func baseURLForToken(token string) string {
- if i := strings.LastIndex(token, "."); i >= 0 && i < len(token)-1 {
- region := token[i+1:]
- // Region codes are short alphanumerics (us, eu, in); guard against a
- // token that simply contains a '.' in its body.
- if region != "" && len(region) <= 4 {
- return "https://api." + region + ".svix.com"
- }
- }
- return "https://api.svix.com"
-}
-
-// Enabled reports whether the client has a token (webhooks are off otherwise).
-func (c *Client) Enabled() bool { return c != nil && c.token != "" }
-
-// Error is a classified Svix API error. Transient (5xx / 429 / network) callers
-// should retry; permanent (4xx) callers should not.
-type Error struct {
- StatusCode int
- Op string
- Body string
-}
-
-func (e *Error) Error() string {
- return fmt.Sprintf("svix %s: HTTP %d: %s", e.Op, e.StatusCode, e.Body)
-}
-
-// Transient reports whether the error is worth retrying (5xx, 429, or a
-// transport error represented as StatusCode 0).
-func (e *Error) Transient() bool {
- return e.StatusCode == 0 || e.StatusCode == http.StatusTooManyRequests || e.StatusCode >= 500
-}
-
-// IsTransient classifies any error (including a wrapped *Error) for retry.
-func IsTransient(err error) bool {
- var se *Error
- if errors.As(err, &se) {
- return se.Transient()
- }
- return err != nil // unknown errors: treat as transient/retryable
-}
-
-// do performs one request. body (if non-nil) is JSON-encoded; out (if non-nil)
-// is JSON-decoded from a 2xx response. extraHeaders are applied last (e.g.
-// idempotency-key). Non-2xx returns a classified *Error.
-func (c *Client) do(ctx context.Context, op, method, path string, body, out any, extraHeaders map[string]string) error {
- var rdr io.Reader
- if body != nil {
- b, err := json.Marshal(body)
- if err != nil {
- return fmt.Errorf("svix %s: marshal: %w", op, err)
- }
- rdr = bytes.NewReader(b)
- }
- req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, rdr)
- if err != nil {
- return fmt.Errorf("svix %s: new request: %w", op, err)
- }
- req.Header.Set("Authorization", "Bearer "+c.token)
- req.Header.Set("Accept", "application/json")
- if body != nil {
- req.Header.Set("Content-Type", "application/json")
- }
- for k, v := range extraHeaders {
- req.Header.Set(k, v)
- }
- resp, err := c.hc.Do(req)
- if err != nil {
- return &Error{StatusCode: 0, Op: op, Body: err.Error()}
- }
- defer resp.Body.Close()
- respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
- if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- return &Error{StatusCode: resp.StatusCode, Op: op, Body: string(respBody)}
- }
- if out != nil && len(respBody) > 0 {
- if err := json.Unmarshal(respBody, out); err != nil {
- return fmt.Errorf("svix %s: decode response: %w", op, err)
- }
- }
- return nil
-}
-
-// ---------------------------------------------------------------------------
-// Applications (one per org, keyed by uid = org id)
-// ---------------------------------------------------------------------------
-
-// Application is the subset of a Svix app we use.
-type Application struct {
- ID string `json:"id"`
- UID string `json:"uid"`
-}
-
-// EnsureApplication creates (or returns, via get_if_exists) the org's app keyed
-// by uid. Idempotent: safe to call on every webhook create.
-func (c *Client) EnsureApplication(ctx context.Context, uid, name string) (*Application, error) {
- var app Application
- err := c.do(ctx, "ensure_application", http.MethodPost,
- "/api/v1/app/?get_if_exists=true",
- map[string]any{"uid": uid, "name": name}, &app, nil)
- if err != nil {
- return nil, err
- }
- return &app, nil
-}
-
-// ---------------------------------------------------------------------------
-// Endpoints (destinations under an app)
-// ---------------------------------------------------------------------------
-
-// Endpoint is the subset of a Svix endpoint we surface.
-type Endpoint struct {
- ID string `json:"id"`
- URL string `json:"url"`
- Description string `json:"description"`
- Disabled bool `json:"disabled"`
- FilterTypes []string `json:"filterTypes,omitempty"`
- Channels []string `json:"channels,omitempty"`
- Metadata map[string]string `json:"metadata,omitempty"`
- CreatedAt string `json:"createdAt,omitempty"`
-}
-
-// EndpointParams is the create/update payload (fields left zero are omitted).
-type EndpointParams struct {
- URL string `json:"url"`
- Description string `json:"description,omitempty"`
- FilterTypes []string `json:"filterTypes,omitempty"`
- Channels []string `json:"channels,omitempty"`
- Metadata map[string]string `json:"metadata,omitempty"`
- Disabled *bool `json:"disabled,omitempty"`
-}
-
-// CreateEndpoint registers a destination under the org's app. The signing secret
-// is generated by Svix; fetch it with GetEndpointSecret.
-func (c *Client) CreateEndpoint(ctx context.Context, appID string, p EndpointParams) (*Endpoint, error) {
- var ep Endpoint
- if err := c.do(ctx, "create_endpoint", http.MethodPost,
- "/api/v1/app/"+appID+"/endpoint/", p, &ep, nil); err != nil {
- return nil, err
- }
- return &ep, nil
-}
-
-// UpdateEndpoint replaces an endpoint's config (PUT).
-func (c *Client) UpdateEndpoint(ctx context.Context, appID, epID string, p EndpointParams) (*Endpoint, error) {
- var ep Endpoint
- if err := c.do(ctx, "update_endpoint", http.MethodPut,
- "/api/v1/app/"+appID+"/endpoint/"+epID+"/", p, &ep, nil); err != nil {
- return nil, err
- }
- return &ep, nil
-}
-
-// GetEndpoint fetches a single endpoint.
-func (c *Client) GetEndpoint(ctx context.Context, appID, epID string) (*Endpoint, error) {
- var ep Endpoint
- if err := c.do(ctx, "get_endpoint", http.MethodGet,
- "/api/v1/app/"+appID+"/endpoint/"+epID+"/", nil, &ep, nil); err != nil {
- return nil, err
- }
- return &ep, nil
-}
-
-// ListEndpoints lists endpoints under an app (first page; iterate=false default).
-func (c *Client) ListEndpoints(ctx context.Context, appID string) ([]Endpoint, error) {
- var out struct {
- Data []Endpoint `json:"data"`
- }
- if err := c.do(ctx, "list_endpoints", http.MethodGet,
- "/api/v1/app/"+appID+"/endpoint/?limit=250", nil, &out, nil); err != nil {
- return nil, err
- }
- return out.Data, nil
-}
-
-// DeleteEndpoint removes an endpoint (idempotent enough; 404 surfaces as *Error).
-func (c *Client) DeleteEndpoint(ctx context.Context, appID, epID string) error {
- return c.do(ctx, "delete_endpoint", http.MethodDelete,
- "/api/v1/app/"+appID+"/endpoint/"+epID+"/", nil, nil, nil)
-}
-
-// GetEndpointSecret returns the endpoint's signing secret (whsec_…).
-func (c *Client) GetEndpointSecret(ctx context.Context, appID, epID string) (string, error) {
- var out struct {
- Key string `json:"key"`
- }
- if err := c.do(ctx, "get_endpoint_secret", http.MethodGet,
- "/api/v1/app/"+appID+"/endpoint/"+epID+"/secret/", nil, &out, nil); err != nil {
- return "", err
- }
- return out.Key, nil
-}
-
-// SetEndpointHeaders sets custom HTTP headers delivered on every request to the
-// endpoint — how per-destination registration metadata rides each delivery.
-func (c *Client) SetEndpointHeaders(ctx context.Context, appID, epID string, headers map[string]string) error {
- return c.do(ctx, "set_endpoint_headers", http.MethodPut,
- "/api/v1/app/"+appID+"/endpoint/"+epID+"/headers/",
- map[string]any{"headers": headers}, nil, nil)
-}
-
-// SendExample sends Svix's example event of the given type to an endpoint. NOTE:
-// Svix requires the event type to have a registered schema with examples, else it
-// 400s (missing_schema). For POST /api/webhooks/:id/test we instead send a real
-// CreateMessage with a synthetic payload, which has no schema dependency.
-func (c *Client) SendExample(ctx context.Context, appID, epID, eventType string) error {
- return c.do(ctx, "send_example", http.MethodPost,
- "/api/v1/app/"+appID+"/endpoint/"+epID+"/send-example/",
- map[string]any{"eventType": eventType}, nil, nil)
-}
-
-// ---------------------------------------------------------------------------
-// Messages (events sent to an app; Svix fans out to matching endpoints)
-// ---------------------------------------------------------------------------
-
-// Message is the subset of a created message we surface.
-type Message struct {
- ID string `json:"id"`
- EventID string `json:"eventId,omitempty"`
-}
-
-// MessageParams is the create-message payload.
-type MessageParams struct {
- EventType string // public type, e.g. "sandbox.created"
- EventID string // optional business id; sanitized to Svix's charset
- Payload any // the event envelope (camelCase)
- Channels []string
- // IdempotencyKey dedupes retries (the raw OC event id — colons allowed in
- // the header). Distinct from EventID, which Svix restricts to [A-Za-z0-9-_.].
- IdempotencyKey string
-}
-
-// SanitizeEventID maps an OC event id (which uses ':', e.g.
-// "sb-x:sandbox.stopped") into Svix's eventId charset [a-zA-Z0-9-_.] by
-// replacing ':' with '.'. The raw id should still be passed as the
-// Idempotency-Key (header, unrestricted) for dedup.
-func SanitizeEventID(id string) string {
- return strings.ReplaceAll(id, ":", ".")
-}
-
-// CreateMessage sends an event to the org's app. Svix fans it out to endpoints
-// whose filterTypes/channels match. IdempotencyKey makes retries safe (same key
-// → same message, no duplicate).
-func (c *Client) CreateMessage(ctx context.Context, appID string, m MessageParams) (*Message, error) {
- body := map[string]any{
- "eventType": m.EventType,
- "payload": m.Payload,
- }
- if m.EventID != "" {
- body["eventId"] = SanitizeEventID(m.EventID)
- }
- if len(m.Channels) > 0 {
- body["channels"] = m.Channels
- }
- var hdrs map[string]string
- if m.IdempotencyKey != "" {
- hdrs = map[string]string{"idempotency-key": m.IdempotencyKey}
- }
- var out Message
- if err := c.do(ctx, "create_message", http.MethodPost,
- "/api/v1/app/"+appID+"/msg/", body, &out, hdrs); err != nil {
- return nil, err
- }
- return &out, nil
-}
diff --git a/internal/svix/client_live_test.go b/internal/svix/client_live_test.go
deleted file mode 100644
index 4257b203..00000000
--- a/internal/svix/client_live_test.go
+++ /dev/null
@@ -1,122 +0,0 @@
-package svix
-
-import (
- "context"
- "net/http"
- "os"
- "strings"
- "testing"
- "time"
-)
-
-// TestLive exercises the client against the real Svix API. It is skipped unless
-// SVIX_API_TOKEN is set, so normal `go test` is unaffected:
-//
-// SVIX_API_TOKEN=$(cat /tmp/svix_token) go test ./internal/svix/ -run TestLive -v
-func TestLive(t *testing.T) {
- token := os.Getenv("SVIX_API_TOKEN")
- if token == "" {
- t.Skip("SVIX_API_TOKEN not set; skipping live Svix test")
- }
- c := NewClient(token)
- ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
- defer cancel()
-
- // Region resolution from the token suffix.
- t.Logf("baseURL=%s", c.baseURL)
-
- // Ensure the example event type exists (idempotent).
- _ = c.do(ctx, "register_event_type", http.MethodPost, "/api/v1/event-type/",
- map[string]any{"name": "sandbox.created", "description": "OC live test"}, nil, nil)
-
- uid := "oc-livetest-" + strings.ReplaceAll(time.Now().UTC().Format("20060102T150405.000"), ".", "-")
-
- // EnsureApplication is idempotent on uid.
- app1, err := c.EnsureApplication(ctx, uid, "OC live test")
- if err != nil {
- t.Fatalf("EnsureApplication #1: %v", err)
- }
- app2, err := c.EnsureApplication(ctx, uid, "OC live test")
- if err != nil {
- t.Fatalf("EnsureApplication #2: %v", err)
- }
- if app1.ID != app2.ID {
- t.Fatalf("EnsureApplication not idempotent: %s != %s", app1.ID, app2.ID)
- }
- t.Logf("app=%s (idempotent)", app1.ID)
-
- // Cleanup the whole app (and its endpoints) at the end.
- defer func() {
- if err := c.do(context.Background(), "delete_app", http.MethodDelete,
- "/api/v1/app/"+app1.ID+"/", nil, nil, nil); err != nil {
- t.Logf("cleanup delete app: %v", err)
- }
- }()
-
- // Create an endpoint scoped to one event type.
- ep, err := c.CreateEndpoint(ctx, app1.ID, EndpointParams{
- URL: "https://httpbingo.org/post",
- Description: "oc live test",
- FilterTypes: []string{"sandbox.created"},
- })
- if err != nil {
- t.Fatalf("CreateEndpoint: %v", err)
- }
- t.Logf("endpoint=%s", ep.ID)
-
- // Secret should be a whsec_ key.
- secret, err := c.GetEndpointSecret(ctx, app1.ID, ep.ID)
- if err != nil {
- t.Fatalf("GetEndpointSecret: %v", err)
- }
- if !strings.HasPrefix(secret, "whsec_") {
- t.Fatalf("unexpected secret prefix: %q", firstN(secret, 8))
- }
- t.Logf("secret prefix ok (whsec_…)")
-
- // Per-destination metadata as custom headers (delivered on every event).
- if err := c.SetEndpointHeaders(ctx, app1.ID, ep.ID, map[string]string{"X-OC-Tenant": "t1"}); err != nil {
- t.Fatalf("SetEndpointHeaders: %v", err)
- }
- t.Logf("custom headers set")
-
- // List shows the endpoint.
- eps, err := c.ListEndpoints(ctx, app1.ID)
- if err != nil {
- t.Fatalf("ListEndpoints: %v", err)
- }
- if len(eps) != 1 || eps[0].ID != ep.ID {
- t.Fatalf("ListEndpoints = %d eps, want our 1", len(eps))
- }
- t.Logf("list ok (%d endpoint)", len(eps))
-
- // Test send (backs /api/webhooks/:id/test) — a real message with a synthetic
- // payload (no event-type schema dependency). Colon id sanitized; raw id is
- // the idempotency key.
- msg, err := c.CreateMessage(ctx, app1.ID, MessageParams{
- EventType: "sandbox.created",
- EventID: "sb-livetest:sandbox.created",
- Payload: map[string]any{"type": "sandbox.created", "sandboxId": "sb-livetest"},
- IdempotencyKey: "sb-livetest:sandbox.created",
- })
- if err != nil {
- t.Fatalf("CreateMessage: %v", err)
- }
- if msg.EventID != "sb-livetest.sandbox.created" {
- t.Fatalf("eventId not sanitized: %q", msg.EventID)
- }
- t.Logf("create-message ok (msg=%s eventId=%s)", msg.ID, msg.EventID)
-
- // Delete endpoint.
- if err := c.DeleteEndpoint(ctx, app1.ID, ep.ID); err != nil {
- t.Fatalf("DeleteEndpoint: %v", err)
- }
- t.Logf("endpoint deleted; live test passed")
-}
-
-func firstN(s string, n int) string {
- if len(s) < n {
- return s
- }
- return s[:n]
-}
diff --git a/internal/svix/client_test.go b/internal/svix/client_test.go
deleted file mode 100644
index dbdd5c17..00000000
--- a/internal/svix/client_test.go
+++ /dev/null
@@ -1,32 +0,0 @@
-package svix
-
-import "testing"
-
-func TestBaseURLForToken(t *testing.T) {
- cases := map[string]string{
- "sk_abc.us": "https://api.us.svix.com",
- "sk_abc.eu": "https://api.eu.svix.com",
- "sk_abc.in": "https://api.in.svix.com",
- "sk_no_region": "https://api.svix.com", // no '.' suffix
- "sk_has.dot.body.us": "https://api.us.svix.com", // region is after the LAST dot
- }
- for token, want := range cases {
- if got := baseURLForToken(token); got != want {
- t.Errorf("baseURLForToken(%q) = %q, want %q", token, got, want)
- }
- }
-}
-
-func TestSanitizeEventID(t *testing.T) {
- cases := map[string]string{
- "sb-x:sandbox.stopped": "sb-x.sandbox.stopped",
- "sb-y:sandbox.hibernated:2": "sb-y.sandbox.hibernated.2",
- "already-clean.id_1": "already-clean.id_1",
- "sb-z:sandbox.migrated:worker7": "sb-z.sandbox.migrated.worker7",
- }
- for in, want := range cases {
- if got := SanitizeEventID(in); got != want {
- t.Errorf("SanitizeEventID(%q) = %q, want %q", in, got, want)
- }
- }
-}
diff --git a/internal/webhook/sign.go b/internal/webhook/sign.go
deleted file mode 100644
index 479eca77..00000000
--- a/internal/webhook/sign.go
+++ /dev/null
@@ -1,90 +0,0 @@
-// 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.go
deleted file mode 100644
index 41062486..00000000
--- a/internal/webhook/sign_test.go
+++ /dev/null
@@ -1,107 +0,0 @@
-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.go
deleted file mode 100644
index 581e9ad4..00000000
--- a/internal/webhook/ssrf.go
+++ /dev/null
@@ -1,167 +0,0 @@
-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.go
deleted file mode 100644
index cb36d19a..00000000
--- a/internal/webhook/ssrf_test.go
+++ /dev/null
@@ -1,101 +0,0 @@
-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)
- }
- }
-}