Self-hosted email delivery platform that enables applications to send emails via HTTP APIs while handling SMTP delivery, templates, storage, security, and analytics. Fully self-hostable alternative to services like SendGrid or Mailgun.
Go email-relayemail-routinghttp-to-smtpmail-deliverymailchimp-alternativemailgun-alternativemailsendermailservermailtemplatemailtestpostmark-alternativesend-emailsendgrid-alternativesendmailtransactional-emailtransactional-outbox
Merge pull request #315 from goposta/dev
Jonas Kanindafbb7f98df11a
diff --git a/.env.example b/.env.exampleindex fd9def1..bc11397 100644--- a/.env.example+++ b/.env.example@@ -94,6 +94,12 @@ POSTA_WEBHOOK_MAX_RETRIES=3POSTA_WEBHOOK_TIMEOUT_SECS=10# Webhook HTTP proxy URL (optional)# POSTA_WEBHOOK_PROXY_URL=+# Let webhooks reach private addresses (loopback, 10/8, 192.168/16, ...). Off by default.+# POSTA_WEBHOOK_ALLOW_PRIVATE_NETWORKS=false+# Private networks webhooks may still reach, comma-separated (e.g. 10.0.5.0/24)+# POSTA_WEBHOOK_ALLOWED_NETWORKS=+# Let workspace SMTP servers reach private addresses. On by default.+# POSTA_SMTP_ALLOW_PRIVATE_NETWORKS=true# Google OAuth client ID for SSO login# POSTA_GOOGLE_OAUTH_CLIENT_ID=your-client-iddiff --git a/cmd/posta/server.go b/cmd/posta/server.goindex 5e7fa61..f843c3a 100644--- a/cmd/posta/server.go+++ b/cmd/posta/server.go@@ -77,6 +77,7 @@ type serverResources struct {func runServer(cli *okapicli.CLI) {cfg := config.New()+ email.SetWorkspaceSMTPNetwork(cfg.SMTPNetwork)app := cli.Okapi()if err := cfg.Initialize(app); err != nil {logger.Fatal("Failed to initialize Posta", "error", err)@@ -739,5 +740,6 @@ func webhookConfig(cfg *config.Config) webhook.Config {MaxRetries: cfg.WebhookMaxRetries,Timeout: time.Duration(cfg.WebhookTimeoutSecs) * time.Second,ProxyURL: cfg.WebhookProxyURL,+ Network: cfg.WebhookNetwork,}}diff --git a/cmd/posta/worker.go b/cmd/posta/worker.goindex c9b8a3e..330b76e 100644--- a/cmd/posta/worker.go+++ b/cmd/posta/worker.go@@ -44,6 +44,7 @@ import (func runWorker() error {cfg := config.New()+ email.SetWorkspaceSMTPNetwork(cfg.SMTPNetwork)if err := cfg.InitWorker(); err != nil {logger.Fatal("worker configuration is not usable", "error", err)}diff --git a/docs/docs/getting-started/configuration.md b/docs/docs/getting-started/configuration.mdindex 6963f39..1881496 100644--- a/docs/docs/getting-started/configuration.md+++ b/docs/docs/getting-started/configuration.md@@ -91,6 +91,19 @@ New-user registration is toggled at runtime from **Admin → Settings** (the `re| `POSTA_WEBHOOK_MAX_RETRIES` | `3` | Maximum webhook delivery retries || `POSTA_WEBHOOK_TIMEOUT_SECS` | `10` | Webhook HTTP request timeout (seconds) || `POSTA_WEBHOOK_PROXY_URL` | — | Optional HTTP/HTTPS/SOCKS5 proxy for outbound webhook delivery |+| `POSTA_WEBHOOK_ALLOW_PRIVATE_NETWORKS` | `false` | Let webhooks reach private and reserved addresses: loopback, `10/8`, `172.16/12`, `192.168/16`, link-local (including cloud metadata at `169.254.169.254`) and their IPv6 counterparts. Off by default, so a workspace member cannot use webhooks to reach your internal network |+| `POSTA_WEBHOOK_ALLOWED_NETWORKS` | — | Comma-separated networks or addresses webhooks may reach although they are private, e.g. `10.0.5.0/24,192.168.1.20` for an internal automation service |++Webhook URLs are checked when they are saved and again on each connection, after DNS resolution, so a hostname that resolves to an internal address is refused too. Redirects are not followed: a `3xx` answer counts as a failed delivery. Failed deliveries record the reason (refused, timed out, blocked…) without the address or port.++## Workspace SMTP servers++| Variable | Default | Description |+|----------|---------|-------------|+| `POSTA_SMTP_ALLOW_PRIVATE_NETWORKS` | `true` | Let SMTP servers that workspace members add reach private and reserved addresses. On by default, since a relay on the same host or network is common. Set it to `false` to keep workspace SMTP servers on the public internet; the system SMTP server and platform servers are never restricted |+| `POSTA_SMTP_ALLOWED_NETWORKS` | — | With the above off, comma-separated networks or addresses workspace SMTP servers may still reach |++A failed connection test shows the SMTP server's reply when it answered, and only the cause (refused, timed out…) when it did not.## Deliverydiff --git a/examples/compose/.env.example b/examples/compose/.env.exampleindex b62328c..6ead931 100644--- a/examples/compose/.env.example+++ b/examples/compose/.env.example@@ -87,6 +87,12 @@ POSTA_WEBHOOK_MAX_RETRIES=3POSTA_WEBHOOK_TIMEOUT_SECS=10# Webhook HTTP proxy URL (optional)# POSTA_WEBHOOK_PROXY_URL=+# Let webhooks reach private addresses (loopback, 10/8, 192.168/16, ...). Off by default.+# POSTA_WEBHOOK_ALLOW_PRIVATE_NETWORKS=false+# Private networks webhooks may still reach, comma-separated (e.g. 10.0.5.0/24)+# POSTA_WEBHOOK_ALLOWED_NETWORKS=+# Let workspace SMTP servers reach private addresses. On by default.+# POSTA_SMTP_ALLOW_PRIVATE_NETWORKS=true# Google OAuth client ID for SSO login# POSTA_GOOGLE_OAUTH_CLIENT_ID=your-client-iddiff --git a/internal/config/config.go b/internal/config/config.goindex 62d1abc..d2d2b05 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -29,6 +29,7 @@ import ("strings"errorhandlers "github.com/goposta/posta/internal/error_handlers"+ "github.com/goposta/posta/internal/netguard""github.com/goposta/posta/internal/storage""github.com/hibiken/asynq"goutils "github.com/jkaninda/go-utils"@@ -114,6 +115,14 @@ type Config struct {WebhookMaxRetries intWebhookTimeoutSecs intWebhookProxyURL string+ // WebhookNetwork decides which addresses webhook URLs may reach: by+ // default not private or reserved ones (POSTA_WEBHOOK_ALLOW_PRIVATE_NETWORKS,+ // POSTA_WEBHOOK_ALLOWED_NETWORKS).+ WebhookNetwork netguard.Policy+ // SMTPNetwork does the same for workspace SMTP servers, which may reach+ // private addresses by default, a relay on the same host being common+ // (POSTA_SMTP_ALLOW_PRIVATE_NETWORKS, POSTA_SMTP_ALLOWED_NETWORKS).+ SMTPNetwork netguard.Policy// OAuth settingsGoogleOAuthClientID string@@ -328,6 +337,8 @@ func New() *Config {WebhookMaxRetries: goutils.EnvInt("POSTA_WEBHOOK_MAX_RETRIES", 3),WebhookTimeoutSecs: goutils.EnvInt("POSTA_WEBHOOK_TIMEOUT_SECS", 10),WebhookProxyURL: goutils.Env("POSTA_WEBHOOK_PROXY_URL", ""),+ WebhookNetwork: networkPolicy("POSTA_WEBHOOK", false),+ SMTPNetwork: networkPolicy("POSTA_SMTP", true),GoogleOAuthClientID: goutils.Env("POSTA_GOOGLE_OAUTH_CLIENT_ID", ""),GoogleOAuthClientSecret: goutils.Env("POSTA_GOOGLE_OAUTH_CLIENT_SECRET", ""),@@ -531,6 +542,18 @@ func (c *Config) InitWorker() error {c.WarnInsecureWorkerConfig()return c.validateWorker()}++// networkPolicy reads a netguard policy from the environment, stopping on an+// allowed network that does not parse rather than running with a policy+// other than the one configured.+func networkPolicy(prefix string, allowPrivate bool) netguard.Policy {+ p, err := netguard.FromEnv(prefix, allowPrivate)+ if err != nil {+ logger.Fatal("invalid network setting", "error", err)+ }+ return p+}+func (c *Config) initLogger() *logger.Logger {if c.DevMode {return logger.New(logger.WithDebugLevel())diff --git a/internal/handlers/smtp_handler.go b/internal/handlers/smtp_handler.goindex c7a65e2..67bef91 100644--- a/internal/handlers/smtp_handler.go+++ b/internal/handlers/smtp_handler.go@@ -157,7 +157,7 @@ func (h *SMTPHandler) Create(c *okapi.Context, req *CreateSMTPRequest) error {server.ValidatedAt = &nowif err := h.sender.TestConnection(server); err != nil {server.Status = models.SMTPStatusInvalid- server.ValidationError = err.Error()+ server.ValidationError = email.DescribeSMTPError(err)} else {server.Status = models.SMTPStatusEnabledserver.ValidationError = ""@@ -235,7 +235,7 @@ func (h *SMTPHandler) Update(c *okapi.Context, req *UpdateSMTPRequest) error {server.ValidatedAt = &nowif err := h.sender.TestConnection(server); err != nil {server.Status = models.SMTPStatusInvalid- server.ValidationError = err.Error()+ server.ValidationError = email.DescribeSMTPError(err)} else {server.Status = models.SMTPStatusEnabledserver.ValidationError = ""@@ -247,7 +247,7 @@ func (h *SMTPHandler) Update(c *okapi.Context, req *UpdateSMTPRequest) error {server.ValidatedAt = &nowif err := h.sender.TestConnection(server); err != nil {server.Status = models.SMTPStatusInvalid- server.ValidationError = err.Error()+ server.ValidationError = email.DescribeSMTPError(err)} else {server.Status = models.SMTPStatusEnabledserver.ValidationError = ""@@ -309,10 +309,12 @@ func (h *SMTPHandler) Test(c *okapi.Context, req *TestSMTPRequest) error {now := time.Now()if err := h.sender.TestConnection(server); err != nil {// Update validation state on test failure- _ = h.repo.SetStatus(server.ID, models.SMTPStatusInvalid, err.Error())+ // Workspace members read this: the reason, not the network details.+ reason := email.DescribeSMTPError(err)+ _ = h.repo.SetStatus(server.ID, models.SMTPStatusInvalid, reason)return ok(c, okapi.M{"success": false,- "message": err.Error(),+ "message": reason,"status": models.SMTPStatusInvalid,"validated_at": now,})diff --git a/internal/handlers/webhook_handler.go b/internal/handlers/webhook_handler.goindex b4691cf..789edff 100644--- a/internal/handlers/webhook_handler.go+++ b/internal/handlers/webhook_handler.go@@ -24,14 +24,16 @@ import ("encoding/hex""github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/netguard""github.com/goposta/posta/internal/services/audit""github.com/goposta/posta/internal/storage/repositories""github.com/jkaninda/okapi")type WebhookHandler struct {- repo *repositories.WebhookRepository- audit *audit.Logger+ repo *repositories.WebhookRepository+ audit *audit.Logger+ network netguard.Policy}type CreateWebhookRequest struct {Body struct {@@ -45,8 +47,10 @@ type DeleteWebhookRequest struct {ID int `param:"id"`}-func NewWebhookHandler(repo *repositories.WebhookRepository, audit *audit.Logger) *WebhookHandler {- return &WebhookHandler{repo: repo, audit: audit}+// NewWebhookHandler takes the policy deliveries are sent under, so a URL that+// could never be delivered to is refused when it is saved.+func NewWebhookHandler(repo *repositories.WebhookRepository, audit *audit.Logger, network netguard.Policy) *WebhookHandler {+ return &WebhookHandler{repo: repo, audit: audit, network: network}}func (h *WebhookHandler) Create(c *okapi.Context, req *CreateWebhookRequest) error {@@ -55,6 +59,12 @@ func (h *WebhookHandler) Create(c *okapi.Context, req *CreateWebhookRequest) err}scope := getScope(c)+ // Deliveries are checked again as they connect; this gives the error at+ // once instead of a failed delivery later.+ if err := h.network.CheckURL(c.Request().Context(), req.Body.URL); err != nil {+ return c.AbortBadRequest("webhook URL not allowed: " + err.Error())+ }+// Generate a random signing secret for HMAC webhook signaturessecretBytes := make([]byte, 32)if _, err := rand.Read(secretBytes); err != nil {diff --git a/internal/netguard/netguard.go b/internal/netguard/netguard.gonew file mode 100644index 0000000..7879fe5--- /dev/null+++ b/internal/netguard/netguard.go@@ -0,0 +1,237 @@+// Copyright (c) 2026 Jonas Kaninda.+//+// This file is part of Posta.+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.+//+// SPDX-License-Identifier: AGPL-3.0-or-later+// Package netguard keeps connections that a workspace member configures, such+// as a webhook URL or an SMTP host, from reaching the server's own network:+// loopback, private ranges, link-local addresses (cloud metadata endpoints+// among them) and the like.+//+// The check runs on the address actually dialled, after DNS resolution, so a+// hostname that resolves to a private address, a DNS answer that changes+// between saving and sending, and a redirect to an internal URL are all+// caught the same way.+package netguard++import (+ "context"+ "errors"+ "fmt"+ "net"+ "net/netip"+ "net/url"+ "os"+ "strings"+ "syscall"+ "time"+)++// ErrBlocked is returned for a destination that is not on the public internet.+var ErrBlocked = errors.New("destination is a private or reserved address")++// Policy decides which addresses outbound connections may reach.+type Policy struct {+ // AllowPrivate turns the guard off: any address may be reached.+ AllowPrivate bool+ // Allowed are networks reachable even though they are not public, such+ // as the subnet of an internal automation service.+ Allowed []netip.Prefix+}++// nonPublic are the ranges a connection must not reach unless allowed. The+// unspecified address and the other special-purpose ranges are blocked too:+// 0.0.0.0 reaches the local host on most systems.+var nonPublic = mustPrefixes(+ "0.0.0.0/8", // "this network"; 0.0.0.0 is the local host+ "10.0.0.0/8", // private+ "100.64.0.0/10", // carrier-grade NAT+ "127.0.0.0/8", // loopback+ "169.254.0.0/16", // link-local, cloud metadata+ "172.16.0.0/12", // private+ "192.0.0.0/24", // IETF protocol assignments+ "192.0.2.0/24", // documentation+ "192.168.0.0/16", // private+ "198.18.0.0/15", // benchmarking+ "198.51.100.0/24", // documentation+ "203.0.113.0/24", // documentation+ "224.0.0.0/4", // multicast+ "240.0.0.0/4", // reserved, broadcast+ "::/128", // unspecified+ "::1/128", // loopback+ "64:ff9b:1::/48", // local-use NAT64+ "100::/64", // discard+ "2001:db8::/32", // documentation+ "fc00::/7", // unique local+ "fe80::/10", // link-local+ "ff00::/8", // multicast+)++func mustPrefixes(cidrs ...string) []netip.Prefix {+ out := make([]netip.Prefix, len(cidrs))+ for i, c := range cidrs {+ out[i] = netip.MustParsePrefix(c)+ }+ return out+}++// Check reports whether ip may be reached.+func (p Policy) Check(ip netip.Addr) error {+ if p.AllowPrivate {+ return nil+ }+ // An IPv4 address written as IPv6 (::ffff:10.0.0.1) is judged as IPv4.+ ip = ip.Unmap()+ for _, allowed := range p.Allowed {+ if allowed.Contains(ip) {+ return nil+ }+ }+ for _, blocked := range nonPublic {+ if blocked.Contains(ip) {+ return ErrBlocked+ }+ }+ return nil+}++// control is a net.Dialer Control function: it runs once the address has been+// resolved, just before connecting, for every address the dialer tries.+func (p Policy) control(_, address string, _ syscall.RawConn) error {+ ap, err := netip.ParseAddrPort(address)+ if err != nil {+ return ErrBlocked+ }+ return p.Check(ap.Addr())+}++// Dialer returns a dialer that refuses addresses the policy blocks.+func (p Policy) Dialer(timeout time.Duration) *net.Dialer {+ return &net.Dialer{Timeout: timeout, KeepAlive: 30 * time.Second, Control: p.control}+}++// DialContext is the policy's dialer as an http.Transport DialContext.+func (p Policy) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {+ return p.Dialer(30*time.Second).DialContext(ctx, network, addr)+}++// CheckURL checks a URL before it is saved: http or https, a host, and a host+// that does not resolve to a blocked address. It gives a clear error early;+// the dialer still decides at send time, when DNS may answer differently.+func (p Policy) CheckURL(ctx context.Context, raw string) error {+ u, err := url.Parse(strings.TrimSpace(raw))+ if err != nil {+ return fmt.Errorf("invalid URL")+ }+ if u.Scheme != "http" && u.Scheme != "https" {+ return fmt.Errorf("the URL must start with http:// or https://")+ }+ host := u.Hostname()+ if host == "" {+ return fmt.Errorf("the URL has no host")+ }+ if u.User != nil {+ return fmt.Errorf("the URL must not contain credentials")+ }+ return p.CheckHost(ctx, host)+}++// CheckHost resolves host and refuses it when any of its addresses is+// blocked. A host that does not resolve is accepted: it may exist later, and+// the dialer checks again then.+func (p Policy) CheckHost(ctx context.Context, host string) error {+ if p.AllowPrivate {+ return nil+ }+ if ip, err := netip.ParseAddr(strings.Trim(host, "[]")); err == nil {+ if p.Check(ip) != nil {+ return fmt.Errorf("%q is a private or reserved address", host)+ }+ return nil+ }+ addrs, err := net.DefaultResolver.LookupNetIP(ctx, "ip", host)+ if err != nil {+ return nil+ }+ for _, ip := range addrs {+ if p.Check(ip) != nil {+ return fmt.Errorf("%q resolves to a private or reserved address", host)+ }+ }+ return nil+}++// FromEnv reads a policy from <prefix>_ALLOW_PRIVATE_NETWORKS (a boolean) and+// <prefix>_ALLOWED_NETWORKS (comma-separated CIDRs or single addresses).+// Entries that do not parse are returned as an error alongside the rest.+func FromEnv(prefix string, defaultAllowPrivate bool) (Policy, error) {+ p := Policy{AllowPrivate: defaultAllowPrivate}+ switch strings.ToLower(strings.TrimSpace(os.Getenv(prefix + "_ALLOW_PRIVATE_NETWORKS"))) {+ case "1", "true", "yes", "on":+ p.AllowPrivate = true+ case "0", "false", "no", "off":+ p.AllowPrivate = false+ }+ var bad []string+ for _, entry := range strings.Split(os.Getenv(prefix+"_ALLOWED_NETWORKS"), ",") {+ entry = strings.TrimSpace(entry)+ if entry == "" {+ continue+ }+ if prefixVal, err := netip.ParsePrefix(entry); err == nil {+ p.Allowed = append(p.Allowed, prefixVal.Masked())+ continue+ }+ if ip, err := netip.ParseAddr(entry); err == nil {+ p.Allowed = append(p.Allowed, netip.PrefixFrom(ip.Unmap(), ip.Unmap().BitLen()))+ continue+ }+ bad = append(bad, entry)+ }+ if len(bad) > 0 {+ return p, fmt.Errorf("%s_ALLOWED_NETWORKS: not a network or address: %s", prefix, strings.Join(bad, ", "))+ }+ return p, nil+}++// Describe turns a connection error into a short reason fit to show a+// workspace member: what went wrong, without the addresses and ports a raw+// network error carries, which would map the server's network.+func Describe(err error) string {+ if err == nil {+ return ""+ }+ var dnsErr *net.DNSError+ var netErr net.Error+ msg := strings.ToLower(err.Error())+ switch {+ case errors.Is(err, ErrBlocked):+ return "blocked: the destination is a private or reserved address"+ case errors.As(err, &dnsErr):+ return "the host name could not be resolved"+ case errors.Is(err, context.DeadlineExceeded), errors.As(err, &netErr) && netErr.Timeout():+ return "the connection timed out"+ case errors.Is(err, syscall.ECONNREFUSED), strings.Contains(msg, "connection refused"):+ return "the connection was refused"+ case errors.Is(err, syscall.ECONNRESET), strings.Contains(msg, "connection reset"), errors.Is(err, net.ErrClosed), strings.Contains(msg, "eof"):+ return "the connection was closed unexpectedly"+ case strings.Contains(msg, "certificate"), strings.Contains(msg, "tls"), strings.Contains(msg, "x509"):+ return "the TLS handshake failed"+ case strings.Contains(msg, "no route"), strings.Contains(msg, "unreachable"):+ return "the destination is unreachable"+ }+ return "the connection failed"+}diff --git a/internal/netguard/netguard_test.go b/internal/netguard/netguard_test.gonew file mode 100644index 0000000..77ec838--- /dev/null+++ b/internal/netguard/netguard_test.go@@ -0,0 +1,154 @@+// Copyright (c) 2026 Jonas Kaninda.+//+// This file is part of Posta.+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.+//+// SPDX-License-Identifier: AGPL-3.0-or-later+package netguard++import (+ "context"+ "net"+ "net/netip"+ "strings"+ "testing"+ "time"+)++func TestCheck(t *testing.T) {+ blocked := []string{+ "127.0.0.1", "127.8.9.10", "10.1.2.3", "172.16.0.1", "172.31.255.255", "192.168.1.1",+ "169.254.169.254", "100.64.0.1", "0.0.0.0", "224.0.0.1", "255.255.255.255",+ "::1", "::", "fe80::1", "fd00::1", "ff02::1",+ "::ffff:127.0.0.1", "::ffff:10.0.0.1", "::ffff:169.254.169.254",+ }+ public := []string{"8.8.8.8", "1.1.1.1", "172.32.0.1", "100.128.0.1", "2001:4860:4860::8888", "::ffff:8.8.8.8"}++ var p Policy+ for _, s := range blocked {+ if p.Check(netip.MustParseAddr(s)) == nil {+ t.Errorf("%s: not blocked", s)+ }+ }+ for _, s := range public {+ if err := p.Check(netip.MustParseAddr(s)); err != nil {+ t.Errorf("%s: blocked: %v", s, err)+ }+ }++ if (Policy{AllowPrivate: true}).Check(netip.MustParseAddr("127.0.0.1")) != nil {+ t.Error("AllowPrivate still blocks loopback")+ }+ allowed := Policy{Allowed: []netip.Prefix{netip.MustParsePrefix("10.0.5.0/24")}}+ if allowed.Check(netip.MustParseAddr("10.0.5.7")) != nil {+ t.Error("an allowed network is blocked")+ }+ if allowed.Check(netip.MustParseAddr("10.0.6.7")) == nil {+ t.Error("allowing one network allowed another")+ }+}++func TestCheckURL(t *testing.T) {+ ctx := context.Background()+ var p Policy+ for _, u := range []string{+ "ftp://example.com/hook", "file:///etc/passwd", "gopher://example.com", "http://", "not a url",+ "http://user:[email protected]/", "http://127.0.0.1:8080/", "http://[::1]/", "http://169.254.169.254/",+ "http://localhost:9000/",+ } {+ if p.CheckURL(ctx, u) == nil {+ t.Errorf("%s: accepted", u)+ }+ }+ if err := p.CheckURL(ctx, "https://203.0.114.1/hook"); err != nil {+ t.Errorf("public address refused: %v", err)+ }+ // A name that does not resolve is left to the dialer.+ if err := p.CheckURL(ctx, "https://does-not-exist.invalid/hook"); err != nil {+ t.Errorf("unresolvable host refused: %v", err)+ }+ if err := (Policy{AllowPrivate: true}).CheckURL(ctx, "http://localhost:5678/webhook"); err != nil {+ t.Errorf("AllowPrivate refused localhost: %v", err)+ }+}++// The dialer checks the resolved address, so a name pointing at loopback is+// refused when it connects, whatever it resolved to when it was saved.+func TestDialerBlocksResolvedAddress(t *testing.T) {+ ln, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatal(err)+ }+ defer func() { _ = ln.Close() }()+ _, port, _ := net.SplitHostPort(ln.Addr().String())++ _, err = Policy{}.Dialer(2*time.Second).Dial("tcp", net.JoinHostPort("localhost", port))+ if err == nil || !strings.Contains(err.Error(), ErrBlocked.Error()) {+ t.Fatalf("want a blocked dial, got %v", err)+ }+ conn, err := Policy{AllowPrivate: true}.Dialer(2*time.Second).Dial("tcp", net.JoinHostPort("localhost", port))+ if err != nil {+ t.Fatalf("allowed dial: %v", err)+ }+ _ = conn.Close()+}++func TestFromEnv(t *testing.T) {+ t.Setenv("X_ALLOW_PRIVATE_NETWORKS", "")+ t.Setenv("X_ALLOWED_NETWORKS", "10.0.5.0/24, 192.168.1.10 ,fd00::/8")+ p, err := FromEnv("X", false)+ if err != nil || p.AllowPrivate || len(p.Allowed) != 3 {+ t.Fatalf("policy %+v, err %v", p, err)+ }+ if p.Check(netip.MustParseAddr("192.168.1.10")) != nil || p.Check(netip.MustParseAddr("192.168.1.11")) == nil {+ t.Error("a single address did not allow exactly itself")+ }++ t.Setenv("X_ALLOW_PRIVATE_NETWORKS", "true")+ t.Setenv("X_ALLOWED_NETWORKS", "nonsense")+ p, err = FromEnv("X", false)+ if err == nil || !p.AllowPrivate {+ t.Fatalf("want an error for a bad entry and AllowPrivate on, got %+v %v", p, err)+ }++ t.Setenv("X_ALLOW_PRIVATE_NETWORKS", "false")+ t.Setenv("X_ALLOWED_NETWORKS", "")+ if p, _ := FromEnv("X", true); p.AllowPrivate {+ t.Error("false did not override the default")+ }+}++// Describe names what went wrong without the address or port.+func TestDescribeHidesAddresses(t *testing.T) {+ ln, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatal(err)+ }+ addr := ln.Addr().String()+ _ = ln.Close() // now nothing listens: connection refused++ _, err = Policy{AllowPrivate: true}.Dialer(2*time.Second).Dial("tcp", addr)+ if err == nil {+ t.Skip("the closed port accepted a connection")+ }+ got := Describe(err)+ if got != "the connection was refused" {+ t.Errorf("Describe(%v) = %q", err, got)+ }+ _, err = Policy{}.Dialer(2*time.Second).Dial("tcp", addr)+ if got := Describe(err); got != "blocked: the destination is a private or reserved address" {+ t.Errorf("blocked: %q", got)+ }+}diff --git a/internal/routes/routes.go b/internal/routes/routes.goindex de601c9..111b78d 100644--- a/internal/routes/routes.go+++ b/internal/routes/routes.go@@ -199,6 +199,8 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *cdispatcher.SetConfig(webhook.Config{MaxRetries: cfg.WebhookMaxRetries,Timeout: time.Duration(cfg.WebhookTimeoutSecs) * time.Second,+ ProxyURL: cfg.WebhookProxyURL,+ Network: cfg.WebhookNetwork,})dispatcher.OnDeliverySuccess(func() { metrics.IncrementWebhookDelivery("success") })dispatcher.OnDeliveryFailed(func() { metrics.IncrementWebhookDelivery("failed") })@@ -296,7 +298,7 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *clanguage: handlers.NewLanguageHandler(languageRepo),stylesheet: handlers.NewStyleSheetHandler(stylesheetRepo),smtp: handlers.NewSMTPHandler(smtpRepo, domainRepo, auditLogger),- webhook: handlers.NewWebhookHandler(webhookRepo, auditLogger),+ webhook: handlers.NewWebhookHandler(webhookRepo, auditLogger, cfg.WebhookNetwork),webhookDelivery: handlers.NewWebhookDeliveryHandler(webhookDeliveryRepo),dashboard: handlers.NewDashboardHandler(db, statsCache, webhookDeliveryRepo),domain: handlers.NewDomainHandler(domainRepo),diff --git a/internal/services/email/smtp_sender.go b/internal/services/email/smtp_sender.goindex f8a6414..3a7cc3f 100644--- a/internal/services/email/smtp_sender.go+++ b/internal/services/email/smtp_sender.go@@ -28,6 +28,7 @@ import ("fmt""mime""mime/quotedprintable"+ "net""net/mail""net/smtp""net/textproto"@@ -38,6 +39,7 @@ import ("github.com/google/uuid""github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/netguard")// SendError carries structured information about an SMTP failure so callers can@@ -70,6 +72,62 @@ func smtpReply(err error) (int, string) {type SMTPSender struct{}+// workspaceNetwork decides which addresses a workspace's own SMTP servers may+// reach. Private ones are allowed unless the operator says otherwise, since a+// relay on the same host or network is a common setup.+var workspaceNetwork = netguard.Policy{AllowPrivate: true}++// SetWorkspaceSMTPNetwork sets the policy for workspace SMTP servers. Called+// once at startup, before any mail is sent.+func SetWorkspaceSMTPNetwork(p netguard.Policy) {+ workspaceNetwork = p+}++// dialerFor returns the dialer for a server: guarded for one a workspace+// member configured, plain for the operator's system server and for+// platform servers, which admins configure.+func dialerFor(server *models.SMTPServer) *net.Dialer {+ if server.WorkspaceID != nil && !server.IsSystem {+ return workspaceNetwork.Dialer(0)+ }+ return &net.Dialer{}+}++// dialSMTP connects in plain text and starts an SMTP session.+func dialSMTP(d *net.Dialer, addr, host string) (*smtp.Client, error) {+ conn, err := d.Dial("tcp", addr)+ if err != nil {+ return nil, err+ }+ client, err := smtp.NewClient(conn, host)+ if err != nil {+ _ = conn.Close()+ return nil, err+ }+ return client, nil+}++// DescribeSMTPError turns a connection or SMTP failure into a message fit to+// show a workspace member. A reply from the SMTP server, such as a refused+// login, is kept; a network error is reduced to what went wrong, without the+// addresses and ports that would map the server's network.+func DescribeSMTPError(err error) string {+ if err == nil {+ return ""+ }+ stage := err.Error()+ if i := strings.Index(stage, ":"); i > 0 {+ stage = stage[:i]+ } else {+ stage = "SMTP connection failed"+ }+ var reply *textproto.Error+ if errors.As(err, &reply) {+ return fmt.Sprintf("%s: %d %s", stage, reply.Code, reply.Msg)+ }+ return stage + ": " + netguard.Describe(err)+}+func NewSMTPSender() *SMTPSender {return &SMTPSender{}}@@ -79,13 +137,14 @@ func NewSMTPSender() *SMTPSender {func (s *SMTPSender) TestConnection(server *models.SMTPServer) error {addr := fmt.Sprintf("%s:%d", server.Host, server.Port)tlsConfig := &tls.Config{ServerName: server.Host}+ dialer := dialerFor(server)var client *smtp.Clientvar err errorswitch server.Encryption {case models.EncryptionSSL:- conn, dialErr := tls.Dial("tcp", addr, tlsConfig)+ conn, dialErr := tls.DialWithDialer(dialer, "tcp", addr, tlsConfig)if dialErr != nil {return fmt.Errorf("SSL dial failed: %w", dialErr)}@@ -96,7 +155,7 @@ func (s *SMTPSender) TestConnection(server *models.SMTPServer) error {}case models.EncryptionSTARTTLS:- client, err = smtp.Dial(addr)+ client, err = dialSMTP(dialer, addr, server.Host)if err != nil {return fmt.Errorf("SMTP dial failed: %w", err)}@@ -106,7 +165,7 @@ func (s *SMTPSender) TestConnection(server *models.SMTPServer) error {}default: // none- client, err = smtp.Dial(addr)+ client, err = dialSMTP(dialer, addr, server.Host)if err != nil {return fmt.Errorf("SMTP dial failed: %w", err)}@@ -181,11 +240,11 @@ func (s *SMTPSender) Send(server *models.SMTPServer, from string, to []string, sswitch server.Encryption {case models.EncryptionSSL:- return sendWithImplicitTLS(addr, auth, server.Host, envelopeFrom, to, msg)+ return sendWithImplicitTLS(dialerFor(server), addr, auth, server.Host, envelopeFrom, to, msg)case models.EncryptionSTARTTLS:- return sendWithSTARTTLS(addr, auth, server.Host, envelopeFrom, to, msg)+ return sendWithSTARTTLS(dialerFor(server), addr, auth, server.Host, envelopeFrom, to, msg)default:- return sendPlain(addr, auth, server.Host, envelopeFrom, to, msg)+ return sendPlain(dialerFor(server), addr, auth, server.Host, envelopeFrom, to, msg)}}@@ -200,10 +259,10 @@ func envelopeAddress(from string) string {return addr.Address}-func sendWithImplicitTLS(addr string, auth smtp.Auth, host string, from string, to []string, msg []byte) error {+func sendWithImplicitTLS(dialer *net.Dialer, addr string, auth smtp.Auth, host string, from string, to []string, msg []byte) error {tlsConfig := &tls.Config{ServerName: host}- conn, err := tls.Dial("tcp", addr, tlsConfig)+ conn, err := tls.DialWithDialer(dialer, "tcp", addr, tlsConfig)if err != nil {return fmt.Errorf("SSL dial failed: %w", err)}@@ -217,8 +276,8 @@ func sendWithImplicitTLS(addr string, auth smtp.Auth, host string, from string,return sendViaClient(client, auth, from, to, msg)}-func sendWithSTARTTLS(addr string, auth smtp.Auth, host string, from string, to []string, msg []byte) error {- client, err := smtp.Dial(addr)+func sendWithSTARTTLS(dialer *net.Dialer, addr string, auth smtp.Auth, host string, from string, to []string, msg []byte) error {+ client, err := dialSMTP(dialer, addr, host)if err != nil {return fmt.Errorf("SMTP dial failed: %w", err)}@@ -232,8 +291,8 @@ func sendWithSTARTTLS(addr string, auth smtp.Auth, host string, from string, toreturn sendViaClient(client, auth, from, to, msg)}-func sendPlain(addr string, auth smtp.Auth, host string, from string, to []string, msg []byte) error {- client, err := smtp.Dial(addr)+func sendPlain(dialer *net.Dialer, addr string, auth smtp.Auth, host string, from string, to []string, msg []byte) error {+ client, err := dialSMTP(dialer, addr, host)if err != nil {return fmt.Errorf("SMTP dial failed, host: %s, error: %w", host, err)}diff --git a/internal/services/email/smtp_sender_test.go b/internal/services/email/smtp_sender_test.goindex a99f86b..7b54849 100644--- a/internal/services/email/smtp_sender_test.go+++ b/internal/services/email/smtp_sender_test.go@@ -23,13 +23,18 @@ import ("errors""fmt""mime"+ "net""net/mail""net/smtp""net/textproto""regexp""strings"+ "syscall""testing""time"++ "github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/netguard")func TestSmtpReply(t *testing.T) {@@ -256,3 +261,56 @@ func TestBuildMessageGeneratesUniqueMessageIDsAndBoundaries(t *testing.T) {}}}++// A workspace member reads the SMTP test result: a server's reply is shown,+// but a network failure is reduced to its cause, without addresses or ports.+func TestDescribeSMTPError(t *testing.T) {+ reply := fmt.Errorf("SMTP auth failed: %w", &textproto.Error{Code: 535, Msg: "5.7.8 Authentication failed"})+ if got := DescribeSMTPError(reply); got != "SMTP auth failed: 535 5.7.8 Authentication failed" {+ t.Errorf("reply: %q", got)+ }++ dial := fmt.Errorf("SMTP dial failed: %w", &net.OpError{Op: "dial", Net: "tcp",+ Addr: &net.TCPAddr{IP: net.ParseIP("10.0.3.7"), Port: 6379}, Err: syscall.ECONNREFUSED})+ if got := DescribeSMTPError(dial); got != "SMTP dial failed: the connection was refused" {+ t.Errorf("dial: %q", got)+ }+}++// With the workspace policy blocking private addresses, a workspace server on+// loopback is refused, while the operator's system server is not.+func TestWorkspaceSMTPNetwork(t *testing.T) {+ ln, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatal(err)+ }+ defer func() { _ = ln.Close() }()+ go func() {+ for {+ c, err := ln.Accept()+ if err != nil {+ return+ }+ _, _ = c.Write([]byte("220 test ESMTP\r\n"))+ _ = c.Close()+ }+ }()+ port := ln.Addr().(*net.TCPAddr).Port++ SetWorkspaceSMTPNetwork(netguard.Policy{})+ t.Cleanup(func() { SetWorkspaceSMTPNetwork(netguard.Policy{AllowPrivate: true}) })++ ws := uint(1)+ err = NewSMTPSender().TestConnection(&models.SMTPServer{WorkspaceID: &ws, Host: "127.0.0.1", Port: port})+ if !errors.Is(err, netguard.ErrBlocked) {+ t.Fatalf("workspace server: want ErrBlocked, got %v", err)+ }+ if got := DescribeSMTPError(err); strings.ContainsAny(got, "0123456789") {+ t.Errorf("reason leaks the address: %q", got)+ }++ err = NewSMTPSender().TestConnection(&models.SMTPServer{WorkspaceID: &ws, IsSystem: true, Host: "127.0.0.1", Port: port})+ if errors.Is(err, netguard.ErrBlocked) {+ t.Errorf("system server blocked: %v", err)+ }+}diff --git a/internal/services/webhook/dispatcher.go b/internal/services/webhook/dispatcher.goindex d9a1943..6425763 100644--- a/internal/services/webhook/dispatcher.go+++ b/internal/services/webhook/dispatcher.go@@ -35,9 +35,11 @@ import ("time""github.com/jkaninda/logger"+ "golang.org/x/net/http/httpproxy""golang.org/x/net/proxy""github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/netguard""github.com/goposta/posta/internal/storage/repositories")@@ -55,12 +57,17 @@ type Config struct {// hiding the server's IP address from webhook endpoints.// Supports http://, https://, and socks5:// schemes.ProxyURL string+ // Network decides which addresses webhooks may reach. The zero value+ // blocks private and reserved addresses.+ Network netguard.Policy}type Dispatcher struct {repo *repositories.WebhookRepositorydeliveryRepo *repositories.WebhookDeliveryRepositoryclient *http.Client+ network netguard.Policy+ proxied bool // a proxy dials the target, so the dialer cannot check itmaxRetries intonDeliverySuccess func()onDeliveryFailed func()@@ -68,13 +75,67 @@ type Dispatcher struct {}func NewDispatcher(repo *repositories.WebhookRepository) *Dispatcher {- return &Dispatcher{+ d := &Dispatcher{repo: repo,maxRetries: defaultMaxRetries,client: &http.Client{Timeout: defaultTimeout,+ // A webhook URL is checked where it points; a redirect could+ // send the request somewhere else, so it is not followed.+ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },},}+ d.client.Transport = d.guardedTransport()+ return d+}++// guardedTransport dials only the addresses the network policy allows. It+// checks each address as it connects, so neither a hostname resolving to a+// private address nor a DNS answer that changed since the webhook was saved+// gets through.+//+// A proxy set in HTTP_PROXY or HTTPS_PROXY is still used, as Go's default+// transport would: the connection to it is allowed wherever it is, and the+// target, which only the proxy dials, is checked by name instead.+func (d *Dispatcher) guardedTransport() *http.Transport {+ env := httpproxy.FromEnvironment()+ proxyFor := env.ProxyFunc()+ proxies := map[string]bool{}+ for _, raw := range []string{env.HTTPProxy, env.HTTPSProxy} {+ if u, err := url.Parse(raw); err == nil && u.Host != "" {+ port := u.Port()+ if port == "" {+ port = map[string]string{"https": "443"}[u.Scheme]+ if port == "" {+ port = "80"+ }+ }+ proxies[net.JoinHostPort(u.Hostname(), port)] = true+ }+ }++ t := http.DefaultTransport.(*http.Transport).Clone()+ t.Proxy = func(req *http.Request) (*url.URL, error) {+ u, err := proxyFor(req.URL)+ if u != nil && err == nil {+ if cerr := d.network.CheckURL(req.Context(), req.URL.String()); cerr != nil {+ return nil, fmt.Errorf("%w: %v", netguard.ErrBlocked, cerr)+ }+ }+ return u, err+ }+ t.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {+ if proxies[addr] {+ return (&net.Dialer{Timeout: 30 * time.Second}).DialContext(ctx, network, addr)+ }+ return d.network.DialContext(ctx, network, addr)+ }+ return t+}++// Network returns the policy webhook URLs are checked against.+func (d *Dispatcher) Network() netguard.Policy {+ return d.network}// SetConfig applies configurable settings to the dispatcher.@@ -85,6 +146,8 @@ func (d *Dispatcher) SetConfig(cfg Config) {if cfg.Timeout > 0 {d.client.Timeout = cfg.Timeout}+ d.network = cfg.Network+ d.client.Transport = d.guardedTransport()if cfg.ProxyURL != "" {transport, err := proxyTransport(cfg.ProxyURL)if err != nil {@@ -92,6 +155,7 @@ func (d *Dispatcher) SetConfig(cfg Config) {return}d.client.Transport = transport+ d.proxied = truelogger.Info("webhook proxy configured", "proxy", cfg.ProxyURL)}}@@ -300,7 +364,7 @@ func (d *Dispatcher) deliverWithRetry(userID uint, wh models.Webhook, body []bytstatusCode, err := d.doRequest(wh.URL, wh.Secret, body)lastStatus = statusCode- if err == nil && statusCode < 400 {+ if err == nil && statusCode < 300 {d.recordDelivery(userID, wh.ID, wh.WorkspaceID, event, models.WebhookDeliverySuccess, statusCode, "", attempt)if d.onDeliverySuccess != nil {d.onDeliverySuccess()@@ -313,8 +377,14 @@ func (d *Dispatcher) deliverWithRetry(userID uint, wh models.Webhook, body []byt}if err != nil {- lastErr = err.Error()+ // The delivery log is read by workspace members: it says what went+ // wrong, not which address or port answered. The server log keeps+ // the full error.+ lastErr = netguard.Describe(err)logger.Warn("webhook delivery failed", "url", wh.URL, "attempt", attempt, "error", err)+ } else if statusCode < 400 {+ lastErr = fmt.Sprintf("HTTP %d: redirects are not followed", statusCode)+ logger.Warn("webhook redirected", "url", wh.URL, "attempt", attempt, "status", statusCode)} else {lastErr = fmt.Sprintf("HTTP %d", statusCode)logger.Warn("webhook returned error status", "url", wh.URL, "attempt", attempt, "status", statusCode)@@ -344,6 +414,13 @@ func signPayload(secret string, body []byte) string {// doRequest sends a single HTTP POST to the webhook URL with an HMAC signature.func (d *Dispatcher) doRequest(url string, secret string, body []byte) (int, error) {+ // Through a proxy the dialer only reaches the proxy, so the target's+ // host is checked here instead.+ if d.proxied {+ if err := d.network.CheckURL(context.Background(), url); err != nil {+ return 0, fmt.Errorf("%w: %v", netguard.ErrBlocked, err)+ }+ }req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body))if err != nil {return 0, fmt.Errorf("failed to create request: %w", err)@@ -381,19 +458,3 @@ func (d *Dispatcher) recordDelivery(userID, webhookID uint, workspaceID *uint, elogger.Error("failed to record webhook delivery", "error", err)}}--// Validate ensures the webhook URL is reachable.-func (d *Dispatcher) Validate(url string) error {- req, err := http.NewRequest(http.MethodHead, url, nil)- if err != nil {- return fmt.Errorf("invalid webhook URL: %w", err)- }-- resp, err := d.client.Do(req)- if err != nil {- return fmt.Errorf("webhook URL unreachable: %w", err)- }- _ = resp.Body.Close()-- return nil-}diff --git a/internal/services/webhook/dispatcher_test.go b/internal/services/webhook/dispatcher_test.goindex a75e889..b7a2972 100644--- a/internal/services/webhook/dispatcher_test.go+++ b/internal/services/webhook/dispatcher_test.go@@ -24,13 +24,17 @@ import ("crypto/sha256""encoding/hex""encoding/json"+ "errors""net/http""net/http/httptest"+ "net/netip"+ "strings""sync/atomic""testing""time""github.com/goposta/posta/internal/models"+ "github.com/goposta/posta/internal/netguard")func TestSignPayload(t *testing.T) {@@ -147,7 +151,7 @@ func TestDispatcher_SignatureHeader(t *testing.T) {Secret: secret,}- d := NewDispatcher(nil)+ d := localDispatcher()body := []byte(`{"event":"email.sent","email_id":"abc","timestamp":"2026-01-01T00:00:00Z"}`)statusCode, err := d.doRequest(wh.URL, wh.Secret, body)@@ -174,7 +178,7 @@ func TestDispatcher_NoSignatureWhenNoSecret(t *testing.T) {}))defer srv.Close()- d := NewDispatcher(nil)+ d := localDispatcher()_, err := d.doRequest(srv.URL, "", []byte(`{}`))if err != nil {t.Fatalf("doRequest error: %v", err)@@ -197,7 +201,7 @@ func TestDispatcher_RetryOnFailure(t *testing.T) {}))defer srv.Close()- d := NewDispatcher(nil)+ d := localDispatcher()d.maxRetries = 3wh := models.Webhook{@@ -234,3 +238,70 @@ func TestDispatcher_SetConfig(t *testing.T) {t.Errorf("after SetConfig timeout = %v, want 30s", d.client.Timeout)}}++// localDispatcher may reach the loopback test servers these tests start.+func localDispatcher() *Dispatcher {+ d := NewDispatcher(nil)+ d.SetConfig(Config{Network: netguard.Policy{AllowPrivate: true}})+ return d+}++// By default a webhook cannot reach the server's own network, and the reason+// recorded for the workspace does not name the address it tried.+func TestDispatcher_BlocksPrivateByDefault(t *testing.T) {+ var hit atomic.Bool+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { hit.Store(true) }))+ defer srv.Close()++ d := NewDispatcher(nil)+ for _, target := range []string{srv.URL, "http://169.254.169.254/latest/meta-data/", "http://[::1]:9/", "http://0.0.0.0:6379/"} {+ _, err := d.doRequest(target, "", []byte("{}"))+ if !errors.Is(err, netguard.ErrBlocked) {+ t.Errorf("%s: want ErrBlocked, got %v", target, err)+ continue+ }+ reason := netguard.Describe(err)+ if strings.ContainsAny(reason, "0123456789") {+ t.Errorf("%s: reason leaks the address: %q", target, reason)+ }+ }+ if hit.Load() {+ t.Error("the loopback server was reached")+ }+}++// A redirect is not followed: a public URL cannot send the request into the+// internal network, and a 3xx is not a successful delivery.+func TestDispatcher_DoesNotFollowRedirects(t *testing.T) {+ var internalHit atomic.Bool+ internal := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { internalHit.Store(true) }))+ defer internal.Close()+ redirector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ http.Redirect(w, r, internal.URL, http.StatusTemporaryRedirect)+ }))+ defer redirector.Close()++ d := localDispatcher()+ status, err := d.doRequest(redirector.URL, "", []byte("{}"))+ if err != nil || status != http.StatusTemporaryRedirect {+ t.Fatalf("status %d, err %v", status, err)+ }+ if internalHit.Load() {+ t.Error("the redirect was followed")+ }+}++// An allowed network is reachable while the rest stays blocked.+func TestDispatcher_AllowedNetworks(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))+ defer srv.Close()++ d := NewDispatcher(nil)+ d.SetConfig(Config{Network: netguard.Policy{Allowed: []netip.Prefix{netip.MustParsePrefix("127.0.0.0/8")}}})+ if status, err := d.doRequest(srv.URL, "", []byte("{}")); err != nil || status != http.StatusOK {+ t.Errorf("allowed network: status %d, err %v", status, err)+ }+ if _, err := d.doRequest("http://10.255.255.1:9/", "", []byte("{}")); !errors.Is(err, netguard.ErrBlocked) {+ t.Errorf("other private network: want ErrBlocked, got %v", err)+ }+}