From 03f264f7c7138a378cd18df1bd845767ae756b60 Mon Sep 17 00:00:00 2001 From: Dominik Myszkowski Date: Thu, 26 Nov 2026 18:16:03 +0100 Subject: [PATCH] feat(webhooks): WEBHOOK_ALLOWED_CIDRS for operator-approved private receivers (#261) Webhook targets go through the SSRF guard, which refuses every private, loopback, CGNAT and ULA address, so a receiver in a sibling container (http://sms-sender:8080/hook) was unreachable without a hairpin through the public proxy. WEBHOOK_ALLOWED_CIDRS (env only, empty by default) lists private networks that are exempt. netutil.ResolveSafeAllowing applies one rule at save time (validateWebhookURL) and at dial time (SafeTransportAllowing), so DNS rebinding between the two gains nothing. Link-local / cloud metadata and the unspecified address are refused before the list is consulted, so listing 169.254.0.0/16 or 0.0.0.0/0 cannot reach 169.254.169.254. It is deliberately not an in-app setting: workspace admins create webhooks and must not be able to widen where they can reach. Documented in DEPLOY.md beside TRUSTED_PROXY_CIDRS, including that listing a range extends the trust boundary for attendee data to that network. --- DEPLOY.md | 1 + docs/ARCHITECTURE.md | 8 ++ internal/config/config.go | 10 ++ internal/handler/handler.go | 11 +++ internal/handler/webhook_handler.go | 16 ++-- internal/handler/webhook_test.go | 34 +++++++ internal/netutil/allowlist_test.go | 96 +++++++++++++++++++ internal/netutil/netutil.go | 45 ++++++++- internal/server/server.go | 33 ++++++- .../server/webhook_cidrs_internal_test.go | 37 +++++++ internal/worker/allowed_cidrs_test.go | 61 ++++++++++++ internal/worker/worker.go | 17 ++++ 12 files changed, 359 insertions(+), 10 deletions(-) create mode 100644 internal/netutil/allowlist_test.go create mode 100644 internal/server/webhook_cidrs_internal_test.go create mode 100644 internal/worker/allowed_cidrs_test.go diff --git a/DEPLOY.md b/DEPLOY.md index 35cfa98d..9cd7ff2f 100644 --- a/DEPLOY.md +++ b/DEPLOY.md @@ -77,6 +77,7 @@ backup method. The email, calendar and other integration settings below still ap | `LITESTREAM_REPLICA_URL` | recommended | — | Enables continuous SQLite backup (see §6). | | `COOKIE_SECURE` | no | https→true | Override cookie Secure flag; defaults from `BASE_URL` scheme. | | `TRUSTED_PROXY_CIDRS` | no | — | Comma-separated CIDRs (a bare address = one host) whose `X-Forwarded-For` is believed when keying per-IP rate limits, e.g. `10.0.0.0/8`. Include a fronting CDN's own ranges so the walk steps over its edge and lands on the visitor. Unset ⇒ the header is ignored and the limit keys on the TCP peer, so behind a CDN every visitor shares one bucket. **Only list networks you control**: anything in the list can name any client IP it likes. Single-value vendor headers (`CF-Connecting-IP`, `X-Real-IP`) are never read, from any peer. | +| `WEBHOOK_ALLOWED_CIDRS` | no | — | Comma-separated CIDRs (a bare address = one host) of **private** networks webhooks may be delivered to, e.g. `172.20.0.0/16` for a receiver in a sibling container (`http://sms-sender:8080/hook`). Unset ⇒ every private, loopback, CGNAT and ULA target is refused, both when the URL is saved and when it is dialled. Operator-only on purpose: workspace admins can create webhooks, so this is not an in-app setting. Link-local / cloud metadata (`169.254.0.0/16`, `fe80::/10`, `fd00:ec2::254`) **stays blocked whatever is listed**. **Only list networks you control**, and note what you are trusting: webhook payloads carry attendee details (names, emails, intake answers), so listing a range extends the trust boundary for that data to everything on that network, not just reachability. On Docker, give the network a fixed `--subnet` so the range can't change under you. | | `FRAME_ANCESTORS` | no | — | **Space**-separated origins allowed to embed the **admin UI** in a frame, e.g. `https://console.example.com 'self'`. Each entry must be `https://host[:port]` or `'self'` — anything else and **the app refuses to start**, because browsers drop a policy they cannot parse. Does not affect the public booking pages, which always deny framing. ⛔ **Same-site only in practice**: `calnode_session` is `SameSite=Lax`, so a cross-site parent can frame `/admin/` and still never be sent the cookie — it gets the login screen inside the frame. Use `'self'` or a host sharing `BASE_URL`'s registrable domain. | | `LOG_LEVEL` | no | `info` | `debug`/`info`/`warn`/`error`. | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 0856972d..616514c0 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -805,6 +805,14 @@ as the desired state: secret stored encrypted. The worker's HTTP client is **SSRF-guarded** (resolves DNS, blocks private/loopback/CGNAT/ULA IPs, dials the resolved IP to avoid re-resolution) since webhook URLs are user-supplied. +- **`WEBHOOK_ALLOWED_CIDRS`** (operator env, empty by default) exempts listed private + networks from that guard, for a receiver in a sibling container. One rule, + `netutil.ResolveSafeAllowing`, is applied at save time (`validateWebhookURL`) and at + dial time (`SafeTransportAllowing`), so DNS rebinding between the two gains nothing. + Link-local / metadata and the unspecified address are refused **before** the list is + consulted (`blockedWebhookIP`), so listing `169.254.0.0/16` or `0.0.0.0/0` can't + reach `169.254.169.254`. Env-only, never an in-app setting: workspace admins create + webhooks, and must not be able to widen where those can reach. - **Per-webhook payload fields:** each webhook chooses which fields land in the `data` object (`webhooks.fields` JSON, migration 00027) — incl. attendee PII + intake answers. NULL ⇒ the original default set (so existing webhooks are unchanged and diff --git a/internal/config/config.go b/internal/config/config.go index 6cb178e3..7d5417e7 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -71,6 +71,15 @@ type Config struct { // walk steps over its edge address and lands on the visitor. TrustedProxyCIDRs []string + // WebhookAllowedCIDRs lists private networks webhooks may be delivered to, as an + // exception to the SSRF guard that otherwise refuses every private, loopback, + // CGNAT and ULA address - for a receiver in a sibling container. Empty (the + // default) keeps the guard whole. Operator-only by design: a workspace admin can + // create webhooks, so an in-app setting would let them widen their own reach. + // Link-local / cloud metadata stays blocked whatever is listed. Comma-separated + // CIDRs; a bare address is taken as a single host. + WebhookAllowedCIDRs []string + // FrameAncestors lists the origins allowed to embed the admin SPA in a frame, as a // Content-Security-Policy frame-ancestors source list. Space-separated, matching the // CSP syntax it becomes. Empty (the default) ⇒ nothing is sent and /admin/ behaves @@ -134,6 +143,7 @@ func Load() *Config { EmbedAllowedOrigins: splitCSV(getEnv("EMBED_ALLOWED_ORIGINS", "")), DataDir: getEnv("DATA_DIR", "data"), TrustedProxyCIDRs: splitCSV(getEnv("TRUSTED_PROXY_CIDRS", "")), + WebhookAllowedCIDRs: splitCSV(getEnv("WEBHOOK_ALLOWED_CIDRS", "")), // Space-separated, not comma: the value goes into a CSP source list verbatim, so // it reads the same in the env var as it does in the header. FrameAncestors: strings.Fields(getEnv("FRAME_ANCESTORS", "")), diff --git a/internal/handler/handler.go b/internal/handler/handler.go index 863d03c3..aba0ba77 100644 --- a/internal/handler/handler.go +++ b/internal/handler/handler.go @@ -4,6 +4,7 @@ import ( "database/sql" "encoding/hex" "log/slog" + "net" "net/http" "sync" "time" @@ -52,6 +53,9 @@ type Handler struct { demoResetInterval time.Duration demoMu sync.RWMutex demoNextResetAt time.Time + + // webhookAllowedCIDRs: private networks webhooks may target (WEBHOOK_ALLOWED_CIDRS). + webhookAllowedCIDRs []*net.IPNet } // SetLiveKit swaps the active LiveKit client (nil disables built-in video rooms). @@ -243,6 +247,13 @@ func (h *Handler) SetWebhookSvc(svc *webhook.Service) { h.webhookSvc = svc } +// SetWebhookAllowedCIDRs sets the private networks a webhook URL may resolve to +// (WEBHOOK_ALLOWED_CIDRS). The worker gets the same list, so a URL accepted here is +// judged by the same rule when it is delivered to. +func (h *Handler) SetWebhookAllowedCIDRs(allowed []*net.IPNet) { + h.webhookAllowedCIDRs = allowed +} + // isEmailEnabled reports whether a real SMTP sender is configured. func (h *Handler) isEmailEnabled() bool { if h.live != nil { diff --git a/internal/handler/webhook_handler.go b/internal/handler/webhook_handler.go index 829cbaeb..b910905b 100644 --- a/internal/handler/webhook_handler.go +++ b/internal/handler/webhook_handler.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "net" "net/http" "net/url" "slices" @@ -41,7 +42,7 @@ func (h *Handler) CreateWebhook(w http.ResponseWriter, r *http.Request) { h.writeError(w, http.StatusBadRequest, "url must be a valid http or https URL") return } - if err := validateWebhookURL(r.Context(), u); err != nil { + if err := validateWebhookURL(r.Context(), u, h.webhookAllowedCIDRs); err != nil { h.writeError(w, http.StatusBadRequest, err.Error()) return } @@ -200,14 +201,13 @@ func (h *Handler) ListWebhookDeliveries(w http.ResponseWriter, r *http.Request) h.writeJSON(w, http.StatusOK, map[string]any{"items": items}) } -// validateWebhookURL resolves the URL host and rejects any address in a -// loopback, link-local, or private range to prevent SSRF. // validateWebhookURL rejects a webhook URL whose host resolves (now) to a private/ -// loopback address — the same SSRF check the worker re-applies at actual delivery -// time (netutil.ResolveSafe), since DNS can change between saving a URL and -// delivering to it. -func validateWebhookURL(ctx context.Context, u *url.URL) error { - if _, err := netutil.ResolveSafe(ctx, u.Hostname()); err != nil { +// loopback address, unless the address is inside an operator-approved network +// (allowed, from WEBHOOK_ALLOWED_CIDRS) - the same SSRF check the worker re-applies +// at actual delivery time (netutil.ResolveSafeAllowing), since DNS can change between +// saving a URL and delivering to it. +func validateWebhookURL(ctx context.Context, u *url.URL, allowed []*net.IPNet) error { + if _, err := netutil.ResolveSafeAllowing(ctx, u.Hostname(), allowed); err != nil { return fmt.Errorf("webhook URL must not resolve to a private or loopback address: %w", err) } return nil diff --git a/internal/handler/webhook_test.go b/internal/handler/webhook_test.go index 9e1f3ce3..2e586b90 100644 --- a/internal/handler/webhook_test.go +++ b/internal/handler/webhook_test.go @@ -3,6 +3,7 @@ package handler_test import ( "encoding/json" "fmt" + "net" "net/http" "net/http/httptest" "strings" @@ -334,3 +335,36 @@ func TestCreateWebhook_ssrf_cgnat_returns400(t *testing.T) { t.Errorf("status = %d; want 400 for CGNAT URL", rec.Code) } } + +// --------------------------------------------------------------------------- +// WEBHOOK_ALLOWED_CIDRS at save time +// --------------------------------------------------------------------------- + +func TestCreateWebhook_allowedCIDRs(t *testing.T) { + _, dockerNet, _ := net.ParseCIDR("10.200.50.0/24") + _, linkLocal, _ := net.ParseCIDR("169.254.0.0/16") + + for _, tc := range []struct { + name string + allowed []*net.IPNet + url string + want int + }{ + {"private refused by default", nil, "http://10.200.50.7:8080/hook", http.StatusBadRequest}, + {"listed network accepted", []*net.IPNet{dockerNet}, "http://10.200.50.7:8080/hook", http.StatusCreated}, + {"unlisted private still refused", []*net.IPNet{dockerNet}, "http://10.0.0.1/hook", http.StatusBadRequest}, + {"metadata refused even when listed", []*net.IPNet{linkLocal}, "http://169.254.169.254/latest/meta-data", http.StatusBadRequest}, + } { + t.Run(tc.name, func(t *testing.T) { + h, apiKey, _ := setupWorkspace(t) + h.SetWebhookAllowedCIDRs(tc.allowed) + req := authReq(http.MethodPost, "/v1/webhooks", + fmt.Sprintf(`{"url":%q,"events":["booking.created"]}`, tc.url), apiKey) + rec := httptest.NewRecorder() + h.RequireAuth(h.CreateWebhook)(rec, req) + if rec.Code != tc.want { + t.Errorf("status = %d; want %d — %s", rec.Code, tc.want, rec.Body.String()) + } + }) + } +} diff --git a/internal/netutil/allowlist_test.go b/internal/netutil/allowlist_test.go new file mode 100644 index 00000000..3a260208 --- /dev/null +++ b/internal/netutil/allowlist_test.go @@ -0,0 +1,96 @@ +package netutil_test + +import ( + "context" + "io" + "log/slog" + "net" + "net/http" + "net/http/httptest" + "testing" + + "github.com/calnode/calnode/internal/netutil" +) + +func mustCIDRs(t *testing.T, ss ...string) []*net.IPNet { + t.Helper() + var out []*net.IPNet + for _, s := range ss { + _, n, err := net.ParseCIDR(s) + if err != nil { + t.Fatalf("parse %q: %v", s, err) + } + out = append(out, n) + } + return out +} + +func TestResolveSafeAllowing(t *testing.T) { + ctx := context.Background() + // Deliberately over-broad: an operator listing the metadata range, or everything, + // must still not reach the metadata service. + allowed := mustCIDRs(t, "10.200.50.0/24", "127.0.0.0/8", "169.254.0.0/16", "fe80::/10", "fd00::/8", "0.0.0.0/0") + cases := []struct { + host string + ok bool + }{ + {"10.200.50.7", true}, // the listed Docker network + {"127.0.0.1", true}, // listed loopback + {"10.0.0.1", true}, // covered by 0.0.0.0/0 + {"8.8.8.8", true}, // public, always allowed + {"169.254.169.254", false}, // metadata: listed, still refused + {"169.254.1.1", false}, // link-local + {"fe80::1", false}, // IPv6 link-local + {"fd00:ec2::254", false}, // AWS IPv6 metadata, inside listed fd00::/8 + {"0.0.0.0", false}, // unspecified + } + for _, tc := range cases { + _, err := netutil.ResolveSafeAllowing(ctx, tc.host, allowed) + if (err == nil) != tc.ok { + t.Errorf("ResolveSafeAllowing(%q) err = %v; want ok=%v", tc.host, err, tc.ok) + } + } +} + +// With no list, the behaviour is exactly ResolveSafe's: every private range refused. +func TestResolveSafeAllowing_emptyIsResolveSafe(t *testing.T) { + ctx := context.Background() + for _, host := range []string{"10.200.50.7", "127.0.0.1", "192.168.1.1", "169.254.169.254", "fd00::1", "8.8.8.8"} { + _, errA := netutil.ResolveSafeAllowing(ctx, host, nil) + _, errB := netutil.ResolveSafe(ctx, host) + if (errA == nil) != (errB == nil) { + t.Errorf("%s: ResolveSafeAllowing(nil) err = %v, ResolveSafe err = %v; want the same verdict", host, errA, errB) + } + } + // A list that doesn't cover the address changes nothing for it. + if _, err := netutil.ResolveSafeAllowing(ctx, "10.0.0.1", mustCIDRs(t, "10.200.50.0/24")); err == nil { + t.Error("10.0.0.1 allowed by 10.200.50.0/24; want refused") + } +} + +// The dial-time guard applies the same list: a listed private target is reached, an +// unlisted one is refused before any connection is made. +func TestSafeTransportAllowing(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + io.WriteString(w, "ok") //nolint:errcheck + })) + defer srv.Close() + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + + allowed := &http.Client{Transport: netutil.SafeTransportAllowing(logger, "test", mustCIDRs(t, "127.0.0.0/8"))} + resp, err := allowed.Get(srv.URL) + if err != nil { + t.Fatalf("listed loopback: %v", err) + } + resp.Body.Close() + + for name, tr := range map[string]http.RoundTripper{ + "no list": netutil.SafeTransport(logger, "test"), + "other network": netutil.SafeTransportAllowing(logger, "test", mustCIDRs(t, "10.200.50.0/24")), + } { + if resp, err := (&http.Client{Transport: tr}).Get(srv.URL); err == nil { + resp.Body.Close() + t.Errorf("%s: loopback target reached; want refused", name) + } + } +} diff --git a/internal/netutil/netutil.go b/internal/netutil/netutil.go index b3157f76..d65d6ee4 100644 --- a/internal/netutil/netutil.go +++ b/internal/netutil/netutil.go @@ -16,6 +16,16 @@ import ( // addresses directly (not re-resolve the hostname) to avoid a DNS-rebinding gap // between this check and the connection. func ResolveSafe(ctx context.Context, host string) ([]net.IPAddr, error) { + return ResolveSafeAllowing(ctx, host, nil) +} + +// ResolveSafeAllowing is ResolveSafe with an operator-approved exception list +// (WEBHOOK_ALLOWED_CIDRS): a private address inside one of allowed passes, so a +// webhook can reach a sibling container on the operator's own network. Every address +// host resolves to must pass, as in ResolveSafe. A nil list is exactly ResolveSafe. +// +// The list can never unblock the cloud metadata service: see blockedWebhookIP. +func ResolveSafeAllowing(ctx context.Context, host string, allowed []*net.IPNet) ([]net.IPAddr, error) { addrs, err := net.DefaultResolver.LookupIPAddr(ctx, host) if err != nil { return nil, fmt.Errorf("resolve %q: %w", host, err) @@ -24,13 +34,36 @@ func ResolveSafe(ctx context.Context, host string) ([]net.IPAddr, error) { return nil, fmt.Errorf("%q resolved to no addresses", host) } for _, a := range addrs { - if IsPrivateIP(a.IP) { + if blockedWebhookIP(a.IP, allowed) { return nil, fmt.Errorf("%q resolved to a private or loopback address", host) } } return addrs, nil } +// blockedWebhookIP reports whether a webhook may not be delivered to ip. +// +// The link-local range (169.254.0.0/16, fe80::/10, where cloud metadata services +// hand out instance credentials), AWS's IPv6 metadata address and the unspecified +// address are refused FIRST and unconditionally, before the allowlist is consulted. +// That order is the security property, not a detail: an operator listing +// 169.254.0.0/16, or 0.0.0.0/0, must still not unblock 169.254.169.254. Keep it if +// this is ever refactored. +func blockedWebhookIP(ip net.IP, allowed []*net.IPNet) bool { + if IsLinkLocal(ip) || ip.IsUnspecified() { + return true + } + if !IsPrivateIP(ip) { + return false + } + for _, n := range allowed { + if n.Contains(ip) { + return false + } + } + return true +} + // ResolveNotMetadata resolves host and rejects it only if it maps to a link-local // address (169.254.0.0/16 / fe80::/10) — the range every major cloud provider (AWS, // GCP, Azure, DigitalOcean, Oracle) uses for its instance-metadata service, and which @@ -108,6 +141,16 @@ func SafeTransport(logger *slog.Logger, logMsg string) http.RoundTripper { return dialGuardTransport(ResolveSafe, logger, logMsg) } +// SafeTransportAllowing is SafeTransport with ResolveSafeAllowing's exception list, +// for webhook delivery when the operator set WEBHOOK_ALLOWED_CIDRS. The dial-time +// check is the same as the save-time one, so a hostname that re-resolves elsewhere +// after the URL was saved is judged again on the address actually dialled. +func SafeTransportAllowing(logger *slog.Logger, logMsg string, allowed []*net.IPNet) http.RoundTripper { + return dialGuardTransport(func(ctx context.Context, host string) ([]net.IPAddr, error) { + return ResolveSafeAllowing(ctx, host, allowed) + }, logger, logMsg) +} + // MetadataSafeTransport is SafeTransport's narrower sibling: it blocks only cloud // metadata / link-local addresses (see ResolveNotMetadata), for admin-configured // "bring your own server" targets (CalDAV, the BYO-LLM endpoint, LiveKit) where diff --git a/internal/server/server.go b/internal/server/server.go index 8190241c..e9182d5f 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -4,6 +4,7 @@ import ( "context" "database/sql" "log/slog" + "net" "net/http" "time" @@ -175,6 +176,8 @@ func BuildHandler(ctx context.Context, cfg *config.Config, db *sql.DB, logger *s h.SetMailer(live, cfg.BaseURL) drain := func() {} + webhookAllowed := parseWebhookAllowedCIDRs(cfg.WebhookAllowedCIDRs, logger) + h.SetWebhookAllowedCIDRs(webhookAllowed) whs, err := webhook.New(db, cfg.EncryptionKey) if err != nil { logger.Error("webhook: init failed", "error", err) @@ -187,7 +190,8 @@ func BuildHandler(ctx context.Context, cfg *config.Config, db *sql.DB, logger *s if publicURL == "" { publicURL = cfg.BaseURL } - wrk := worker.New(db, whs, logger, worker.WithMailer(live), worker.WithPublicURL(publicURL)) + wrk := worker.New(db, whs, logger, worker.WithMailer(live), worker.WithPublicURL(publicURL), + worker.WithWebhookAllowedCIDRs(webhookAllowed)) // Notetaker jobs live in the handler package (they need LLM/S3/encKey). wrk.RegisterHandler("notetaker.transcribe", h.JobNotetakerTranscribe) wrk.RegisterHandler("notetaker.summarize", h.JobNotetakerSummarize) @@ -683,3 +687,30 @@ func seedSMTPToDB(db *sql.DB, cfg *config.Config, encKey [32]byte, logger *slog. logger.Info("mailer: seeded SMTP settings from env vars into database (env vars can now be removed)") } } + +// parseWebhookAllowedCIDRs parses WEBHOOK_ALLOWED_CIDRS with the same rules as +// TRUSTED_PROXY_CIDRS (a bare address is one host). A bad entry is logged and dropped, +// which fails closed: that network simply stays blocked. An entry covering the cloud +// metadata address gets a warning, because it reads as if it unblocked it and it does +// not (netutil.ResolveSafeAllowing refuses link-local first). +func parseWebhookAllowedCIDRs(entries []string, logger *slog.Logger) []*net.IPNet { + allowed, err := ParseTrustedProxies(entries) + if err != nil { + logger.Error("WEBHOOK_ALLOWED_CIDRS: ignoring unparseable entries", "error", err) + } + metadata := net.ParseIP("169.254.169.254") + for _, n := range allowed { + if n.Contains(metadata) { + logger.Warn("WEBHOOK_ALLOWED_CIDRS: link-local / cloud metadata addresses stay blocked whatever is listed", "cidr", n.String()) + } + } + if len(allowed) > 0 { + // Log what was parsed, not what was written: a dropped entry must not read as allowed. + cidrs := make([]string, len(allowed)) + for i, n := range allowed { + cidrs[i] = n.String() + } + logger.Info("webhooks may be delivered to these private networks", "cidrs", cidrs) + } + return allowed +} diff --git a/internal/server/webhook_cidrs_internal_test.go b/internal/server/webhook_cidrs_internal_test.go new file mode 100644 index 00000000..a885a962 --- /dev/null +++ b/internal/server/webhook_cidrs_internal_test.go @@ -0,0 +1,37 @@ +package server + +import ( + "bytes" + "log/slog" + "net" + "strings" + "testing" +) + +func TestParseWebhookAllowedCIDRs(t *testing.T) { + var logs bytes.Buffer + logger := slog.New(slog.NewTextHandler(&logs, nil)) + + got := parseWebhookAllowedCIDRs([]string{"10.200.50.0/24", " 172.20.0.5 ", "not-a-cidr", "169.254.0.0/16", ""}, logger) + + // The bad entry is dropped (that network stays blocked), the rest are kept. + if len(got) != 3 { + t.Fatalf("parsed %d networks %v; want 3", len(got), got) + } + if !got[1].Contains(net.ParseIP("172.20.0.5")) || got[1].Contains(net.ParseIP("172.20.0.6")) { + t.Errorf("bare address parsed as %v; want a single host", got[1]) + } + out := logs.String() + if !strings.Contains(out, `cidrs="[10.200.50.0/24 172.20.0.5/32 169.254.0.0/16]"`) { + t.Errorf("allowed-networks log should list the parsed networks only:\n%s", out) + } + for _, want := range []string{"ignoring unparseable entries", "not-a-cidr", "stay blocked whatever is listed"} { + if !strings.Contains(out, want) { + t.Errorf("logs missing %q:\n%s", want, out) + } + } + + if got := parseWebhookAllowedCIDRs(nil, logger); len(got) != 0 { + t.Errorf("empty env parsed as %v; want none", got) + } +} diff --git a/internal/worker/allowed_cidrs_test.go b/internal/worker/allowed_cidrs_test.go new file mode 100644 index 00000000..ad0cdb05 --- /dev/null +++ b/internal/worker/allowed_cidrs_test.go @@ -0,0 +1,61 @@ +package worker_test + +import ( + "context" + "log/slog" + "net" + "net/http" + "net/http/httptest" + "testing" + + "github.com/calnode/calnode/internal/webhook" + "github.com/calnode/calnode/internal/worker" +) + +// The production transport (no WithHTTPClient bypass) refuses a private receiver, +// and delivers to it once its network is in WEBHOOK_ALLOWED_CIDRS. +func TestWorker_webhookAllowedCIDRs(t *testing.T) { + _, loopback, _ := net.ParseCIDR("127.0.0.0/8") + _, other, _ := net.ParseCIDR("10.200.50.0/24") + + for _, tc := range []struct { + name string + allowed []*net.IPNet + want string + }{ + {"default guard", nil, "failed"}, + {"other network listed", []*net.IPNet{other}, "failed"}, + {"receiver's network listed", []*net.IPNet{loopback}, "success"}, + } { + t.Run(tc.name, func(t *testing.T) { + database, svc := setup(t) + ctx := context.Background() + + hits := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + hits++ + w.WriteHeader(http.StatusOK) + })) + defer srv.Close() + + wh, _, err := svc.Create(ctx, "host-01", srv.URL, []string{"booking.created"}) + if err != nil { + t.Fatalf("create webhook: %v", err) + } + svc.Enqueue(ctx, "booking.created", webhook.BookingPayload{HostID: "host-01", Status: "confirmed"}) + + w := worker.New(database, svc, slog.Default(), worker.WithWebhookAllowedCIDRs(tc.allowed)) + w.Poll(ctx) + + var status string + database.QueryRowContext(ctx, + `SELECT status FROM webhook_deliveries WHERE webhook_id = ?`, wh.ID).Scan(&status) + if tc.want == "success" && (status != "success" || hits != 1) { + t.Errorf("delivery status = %q, receiver hits = %d; want success, 1", status, hits) + } + if tc.want == "failed" && (status == "success" || hits != 0) { + t.Errorf("delivery status = %q, receiver hits = %d; want refused before connecting", status, hits) + } + }) + } +} diff --git a/internal/worker/worker.go b/internal/worker/worker.go index 68bedbb2..abf87e0c 100644 --- a/internal/worker/worker.go +++ b/internal/worker/worker.go @@ -8,6 +8,7 @@ import ( "fmt" "io" "log/slog" + "net" "net/http" "time" @@ -48,6 +49,22 @@ func WithHTTPClient(c *http.Client) func(*Worker) { return func(w *Worker) { w.httpClient = c } } +// WithWebhookAllowedCIDRs lets webhook delivery reach these private networks +// (WEBHOOK_ALLOWED_CIDRS). The dial-time guard stays on for everything else; see +// netutil.SafeTransportAllowing. +func WithWebhookAllowedCIDRs(allowed []*net.IPNet) func(*Worker) { + return func(w *Worker) { + if len(allowed) > 0 { + // A new client rather than a mutated one, so a client handed in through + // WithHTTPClient is never altered behind its owner's back. + w.httpClient = &http.Client{ + Timeout: w.httpClient.Timeout, + Transport: netutil.SafeTransportAllowing(w.logger, "worker: webhook SSRF block", allowed), + } + } + } +} + // WithMailer configures the mailer used to send reminder emails. func WithMailer(m mailer.Mailer) func(*Worker) { return func(w *Worker) { w.mailer = m }