Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DEPLOY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The example receiver here is http://, but the admin webhooks page rejects any URL that does not start with https:// (frontend/src/routes/webhooks/+page.svelte:108), so this exact setup can only be created through POST /v1/webhooks with an API key. Either say that in this row or relax the UI check for receivers the operator has allowlisted.

Technical details
# Private HTTP receivers are API-only today

## Affected sites
- `DEPLOY.md:80` — example uses `http://sms-sender:8080/hook`.
- `frontend/src/routes/webhooks/+page.svelte:108` — `!form.url.startsWith('https://')` blocks creation in the admin UI, while `CreateWebhook` accepts `http`.

## Required outcome
- An operator following this row can actually create the receiver it describes.

## Suggested approach (optional)
- The UI cannot know `WEBHOOK_ALLOWED_CIDRS` (env-only, and it should stay that way), so documenting the API path is the low-risk fix.

## Open questions for the human
- Was the UI's `https://` rule meant to be absolute for all webhooks, or should it be narrowed when private receivers are allowlisted?

| `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`. |

Expand Down
8 changes: 8 additions & 0 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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", "")),
Expand Down
11 changes: 11 additions & 0 deletions internal/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"database/sql"
"encoding/hex"
"log/slog"
"net"
"net/http"
"sync"
"time"
Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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 {
Expand Down
16 changes: 8 additions & 8 deletions internal/handler/webhook_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"slices"
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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
Expand Down
34 changes: 34 additions & 0 deletions internal/handler/webhook_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package handler_test
import (
"encoding/json"
"fmt"
"net"
"net/http"
"net/http/httptest"
"strings"
Expand Down Expand Up @@ -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())
}
})
}
}
96 changes: 96 additions & 0 deletions internal/netutil/allowlist_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
45 changes: 44 additions & 1 deletion internal/netutil/netutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
33 changes: 32 additions & 1 deletion internal/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"log/slog"
"net"
"net/http"
"time"

Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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
}
Loading
Loading