Skip to content

armgit / posta

Public Imported from GitHub
0

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.

Upgrade okapi to v1.0.0; add trusted proxies and safer CORS defaults

Jonas Kaninda2e6b9c827a95
diff --git a/.env.example b/.env.example
index 466e0af..b22c5f7 100644
--- a/.env.example
+++ b/.env.example
@@ -65,8 +65,14 @@ POSTA_WEB_URL=https://posta.example.com
# Public API base URL (advertised in the OpenAPI "servers" list; optional if POSTA_WEB_URL is set)
# POSTA_API_URL=https://posta.example.com
-# Allowed CORS origins
-POSTA_CORS_ORIGINS=*
+# Comma-separated allowed CORS origins. Defaults to the origins of POSTA_WEB_URL
+# and POSTA_API_URL; only needed when the dashboard or API is called from elsewhere.
+# POSTA_CORS_ORIGINS=https://dashboard.example.com
+
+# Comma-separated CIDRs/IPs of reverse proxies allowed to set X-Forwarded-For
+# and X-Real-IP. Leave empty only when Posta is not behind a proxy you control:
+# otherwise clients can spoof the IP used for rate limits and API key allow-lists.
+# POSTA_TRUSTED_PROXIES=10.0.0.0/8,172.16.0.0/12
# Worker
# Run worker in server process
diff --git a/docs/docs/getting-started/configuration.md b/docs/docs/getting-started/configuration.md
index aee3c7a..6712403 100644
--- a/docs/docs/getting-started/configuration.md
+++ b/docs/docs/getting-started/configuration.md
@@ -48,7 +48,8 @@ Posta is configured via environment variables. All variables are prefixed with `
| `POSTA_JWT_SECRET` | — | **Required.** JWT signing key. Must be changed in production. |
| `POSTA_ADMIN_EMAIL` | `[email protected]` | Initial admin account email |
| `POSTA_ADMIN_PASSWORD` | `admin1234` | Initial admin account password |
-| `POSTA_CORS_ORIGINS` | `*` | Comma-separated allowed CORS origins |
+| `POSTA_CORS_ORIGINS` | origins of `POSTA_WEB_URL` / `POSTA_API_URL` | Comma-separated allowed CORS origins. When unset, the origins of `POSTA_WEB_URL` and `POSTA_API_URL` are allowed; with neither set, only same-origin requests are served. `*` allows every origin (without credentials) and is reported as insecure. |
+| `POSTA_TRUSTED_PROXIES` | — | Comma-separated CIDR blocks or IPs of the reverse proxies in front of Posta (e.g. `10.0.0.0/8,192.0.2.7`). `X-Forwarded-For` and `X-Real-IP` are only honoured on connections from these peers. When empty, the headers are trusted from any client, so the IP used for rate limiting, API key IP allow-lists and audit logs can be spoofed. An invalid entry stops the server from starting. |
| `POSTA_ENCRYPTION_KEY` | — | AES-256-GCM key used to encrypt stored SMTP passwords. Falls back to base64 encoding only when empty. |
| `POSTA_EMAIL_VERIFICATION_REQUIRED` | `false` | Require new users to confirm their email address before they can sign in |
@@ -207,6 +208,7 @@ POSTA_JWT_SECRET=your-very-long-random-secret-key
POSTA_ADMIN_PASSWORD=strong-admin-password
POSTA_CORS_ORIGINS=https://dashboard.yourdomain.com
+POSTA_TRUSTED_PROXIES=10.0.0.0/8
# Features
POSTA_METRICS_ENABLED=true
diff --git a/docs/docs/security/rate-limiting.md b/docs/docs/security/rate-limiting.md
index ed336da..627c973 100644
--- a/docs/docs/security/rate-limiting.md
+++ b/docs/docs/security/rate-limiting.md
@@ -33,6 +33,8 @@ When a rate limit is exceeded, the API returns `429 Too Many Requests`:
Login attempts are rate-limited per IP address to prevent brute force attacks. This is enabled by default and can be toggled via the `POSTA_AUTH_RATE_LIMIT_ENABLED` environment variable.
+The client IP is read from `X-Forwarded-For` / `X-Real-IP`. When Posta runs behind a reverse proxy, set `POSTA_TRUSTED_PROXIES` to the proxy's address or CIDR so those headers are only accepted from it; otherwise any client can pick its own IP and sidestep the limit.
+
## Batch Emails
Each recipient in a batch send counts toward the rate limit. A batch of 100 recipients counts as 100 emails.
diff --git a/examples/.env.example b/examples/.env.example
index 6ed8e8a..b62328c 100644
--- a/examples/.env.example
+++ b/examples/.env.example
@@ -63,8 +63,9 @@ POSTA_UPDATE_CHECK=true
# Public URL
POSTA_WEB_URL=https://posta.example.com
-# Allowed CORS origins
-POSTA_CORS_ORIGINS=*
+# Comma-separated allowed CORS origins. Defaults to the origins of POSTA_WEB_URL
+# and POSTA_API_URL; only needed when the dashboard or API is called from elsewhere.
+# POSTA_CORS_ORIGINS=https://dashboard.example.com
# Worker
# Run worker in server process
diff --git a/go.mod b/go.mod
index 837ac02..6d768b4 100644
--- a/go.mod
+++ b/go.mod
@@ -15,7 +15,7 @@ require (
github.com/jackc/pgx/v5 v5.11.0
github.com/jkaninda/go-utils v0.1.4
github.com/jkaninda/logger v0.0.5
- github.com/jkaninda/okapi v0.11.0
+ github.com/jkaninda/okapi v1.0.0
github.com/joho/godotenv v1.5.1
github.com/lib/pq v1.12.3
github.com/pquerna/otp v1.5.0
@@ -86,7 +86,7 @@ require (
golang.org/x/sync v0.23.0 // indirect
golang.org/x/sys v0.48.0 // indirect
golang.org/x/time v0.15.0 // indirect
- google.golang.org/protobuf v1.36.11 // indirect
+ google.golang.org/protobuf v1.36.12 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
diff --git a/go.sum b/go.sum
index 09e00e3..0a3557b 100644
--- a/go.sum
+++ b/go.sum
@@ -46,8 +46,6 @@ github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJ
github.com/coreos/go-oidc/v3 v3.21.0 h1:wZo4Q9Pum8dYEj0eMUPrqR+kvuGkeUplbLpNCkBqoWM=
github.com/coreos/go-oidc/v3 v3.21.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
-github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
-github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=
github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6 h1:oP4q0fw+fOSWn3DfFi4EXdT+B+gTtzx8GC9xsc26Znk=
@@ -101,8 +99,8 @@ github.com/jkaninda/logger v0.0.5 h1:fTHKgDsHtuN8rkSBvwe6QStfi8yIdm8O3r0g99dRDTY
github.com/jkaninda/logger v0.0.5/go.mod h1:ZUXJ2BdxDPG6e8t6mbKhc2ZFaFi2Iuy/4ukquFrPkFE=
github.com/jkaninda/njia v0.0.3 h1:7DBKbp/Y/r5DYTEZd7z7oWuNDfnxAzifs2EZ2ux5WNg=
github.com/jkaninda/njia v0.0.3/go.mod h1:YZe9FDA9bqnvKJ/PC3nT8LDOOa6a29KQtLF6XVSRODg=
-github.com/jkaninda/okapi v0.11.0 h1:73Ke2BJF5TTYG0DLKkFnSKrAP87bzErRQ6tOxF+DHF4=
-github.com/jkaninda/okapi v0.11.0/go.mod h1:/Bt3U6MpUaGdb7iPKjyRpqFhv9/AIj/SReNbRjGQ1mw=
+github.com/jkaninda/okapi v1.0.0 h1:dVSVkwxuVD44t76fZwpkNuVOm+XH9mZiiLSa6bCgi+g=
+github.com/jkaninda/okapi v1.0.0/go.mod h1:s4DJuYKRgtYzOUY5DwR/LVwkIo+mR4z5qmUwnrseQ9k=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=
@@ -139,7 +137,6 @@ github.com/olekukonko/ll v0.1.8 h1:ysHCJRGHYKzmBSdz9w5AySztx7lG8SQY+naTGYUbsz8=
github.com/olekukonko/ll v0.1.8/go.mod h1:RPRC6UcscfFZgjo1nulkfMH5IM0QAYim0LfnMvUuozw=
github.com/olekukonko/tablewriter v1.1.4 h1:ORUMI3dXbMnRlRggJX3+q7OzQFDdvgbN9nVWj1drm6I=
github.com/olekukonko/tablewriter v1.1.4/go.mod h1:+kedxuyTtgoZLwif3P1Em4hARJs+mVnzKxmsCL/C5RY=
-github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pquerna/otp v1.5.0 h1:NMMR+WrmaqXU4EzdGJEE1aUUI0AMRzsp96fFFWNPwxs=
github.com/pquerna/otp v1.5.0/go.mod h1:dkJfzwRKNiegxyNb54X/3fLwhCynbMspSyWKnvi1AEg=
@@ -168,8 +165,8 @@ github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf/go.mod h1:RJID2RhlZKId02n
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
-github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
-github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
+github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
+github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/vanng822/css v1.0.1 h1:10yiXc4e8NI8ldU6mSrWmSWMuyWgPr9DZ63RSlsgDw8=
github.com/vanng822/css v1.0.1/go.mod h1:tcnB1voG49QhCrwq1W0w5hhGasvOg+VQp9i9H1rCM1w=
github.com/vanng822/go-premailer v1.35.0 h1:MKjrmNV501RC7sIojfOSMT8o3f0eajzuwT7PZ5MUKZg=
@@ -183,6 +180,8 @@ go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
+go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
+go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
@@ -263,8 +262,8 @@ golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
-google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
-google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
+google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
+google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
diff --git a/internal/config/config.go b/internal/config/config.go
index fa3b634..ffca22e 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -6,7 +6,10 @@ package config
import (
"crypto/tls"
"fmt"
+ "net"
+ "net/url"
"os"
+ "slices"
"strings"
errorhandlers "github.com/goposta/posta/internal/error_handlers"
@@ -57,11 +60,20 @@ type Config struct {
// WebDir overrides where the dashboard is served from. The UI is normally
// embedded in the binary (internal/web); setting POSTA_WEB_DIR serves it from
// this directory instead, for frontend development or a customized build.
- WebDir string
- AppWebURL string
- ApiBaseURL string
+ WebDir string
+ AppWebURL string
+ ApiBaseURL string
+ // CORSOrigins is POSTA_CORS_ORIGINS as given. When empty, the allowed
+ // origins are derived from AppWebURL and ApiBaseURL; see AllowedCORSOrigins.
CORSOrigins string
+ // TrustedProxies lists the CIDR blocks or addresses of the reverse proxies
+ // in front of Posta. X-Forwarded-For and X-Real-IP are honoured only on
+ // connections from one of them. Left empty, the headers are trusted from
+ // any peer, so a client can choose the IP that rate limits, API key IP
+ // allow-lists and the audit log see.
+ TrustedProxies []string
+
// Worker settings
EmbeddedWorker bool
WorkerConcurrency int
@@ -279,7 +291,8 @@ func New() *Config {
AppWebURL: goutils.Env("POSTA_WEB_URL", ""),
ApiBaseURL: goutils.Env("POSTA_API_URL", ""),
- CORSOrigins: goutils.Env("POSTA_CORS_ORIGINS", "*"),
+ CORSOrigins: goutils.Env("POSTA_CORS_ORIGINS", ""),
+ TrustedProxies: splitList(goutils.Env("POSTA_TRUSTED_PROXIES", "")),
EmbeddedWorker: goutils.EnvBool("POSTA_EMBEDDED_WORKER", false),
WorkerConcurrency: goutils.EnvInt("POSTA_WORKER_CONCURRENCY", 10),
@@ -379,6 +392,13 @@ func (c *Config) validate() error {
return fmt.Errorf("POSTA_INBOUND_TLS_MODE=%s requires POSTA_INBOUND_TLS_CERT_FILE and POSTA_INBOUND_TLS_KEY_FILE", c.InboundTLSMode)
}
}
+ // okapi drops an invalid list and trusts no proxy, which would quietly
+ // collapse every client onto the proxy's address. Refuse to start instead.
+ for _, entry := range c.TrustedProxies {
+ if !validProxyEntry(entry) {
+ return fmt.Errorf("invalid POSTA_TRUSTED_PROXIES entry %q (expected a CIDR block or IP address)", entry)
+ }
+ }
return c.ValidateSecurity()
}
func (c *Config) validateWorker() error {
@@ -399,11 +419,9 @@ func (c *Config) Initialize(app *okapi.Okapi) error {
// Set Port
app.WithPort(c.Port)
app.WithLogger(l.Logger)
+ app.WithTrustedProxies(c.TrustedProxies...)
+ app.WithMaxRequestBody(maxRequestBody)
_ = goutils.SetEnv("ENV", c.Env)
- corsOrigins := strings.Split(c.CORSOrigins, ",")
- for i := range corsOrigins {
- corsOrigins[i] = strings.TrimSpace(corsOrigins[i])
- }
apiServers := okapi.Servers{}
if c.AppWebURL != "" {
apiServers = append(apiServers, okapi.Server{URL: c.AppWebURL})
@@ -412,7 +430,7 @@ func (c *Config) Initialize(app *okapi.Okapi) error {
apiServers = append(apiServers, okapi.Server{URL: c.ApiBaseURL})
}
app.WithCORS(okapi.Cors{
- AllowedOrigins: corsOrigins,
+ AllowedOrigins: c.AllowedCORSOrigins(),
AllowedHeaders: []string{"Content-Type", "Authorization", "X-Request-ID", "X-Posta-Workspace-Id"},
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowCredentials: true,
@@ -491,3 +509,48 @@ func (c *Config) InitStorage() {
c.Redis.Client = redisClient
}
+
+// AllowedCORSOrigins returns POSTA_CORS_ORIGINS when set, otherwise the origins
+// of POSTA_WEB_URL and POSTA_API_URL. With none of them set the list is empty
+// and only same-origin requests (the embedded dashboard) are served.
+func (c *Config) AllowedCORSOrigins() []string {
+ if origins := splitList(c.CORSOrigins); len(origins) > 0 {
+ return origins
+ }
+ var origins []string
+ for _, raw := range []string{c.AppWebURL, c.ApiBaseURL} {
+ u, err := url.Parse(strings.TrimSpace(raw))
+ if err != nil || u.Scheme == "" || u.Host == "" {
+ continue
+ }
+ origin := u.Scheme + "://" + u.Host
+ if !slices.Contains(origins, origin) {
+ origins = append(origins, origin)
+ }
+ }
+ return origins
+}
+
+// maxRequestBody caps JSON request bodies. okapi's 8 MB default is below what
+// the send API accepts: email.DefaultMaxTotalSize allows 25 MB of attachments,
+// which arrive base64-encoded (~33 MB), plus the message bodies themselves.
+const maxRequestBody = 40 << 20
+
+// splitList parses a comma-separated env value, dropping blank entries.
+func splitList(raw string) []string {
+ var out []string
+ for _, part := range strings.Split(raw, ",") {
+ if part = strings.TrimSpace(part); part != "" {
+ out = append(out, part)
+ }
+ }
+ return out
+}
+
+// validProxyEntry mirrors what okapi.WithTrustedProxies accepts.
+func validProxyEntry(entry string) bool {
+ if _, _, err := net.ParseCIDR(entry); err == nil {
+ return true
+ }
+ return net.ParseIP(entry) != nil
+}
diff --git a/internal/config/config_test.go b/internal/config/config_test.go
index da2922f..8ae526d 100644
--- a/internal/config/config_test.go
+++ b/internal/config/config_test.go
@@ -5,6 +5,7 @@ package config
import (
"os"
+ "slices"
"testing"
)
@@ -120,3 +121,23 @@ func TestNewRedisConfigTLS(t *testing.T) {
t.Fatal("AsynqRedisOpt().TLSConfig is nil")
}
}
+
+func TestAllowedCORSOrigins(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ cfg Config
+ want []string
+ }{
+ {"explicit wins", Config{CORSOrigins: " https://a.test , https://b.test", AppWebURL: "https://web.test"}, []string{"https://a.test", "https://b.test"}},
+ {"derived from urls", Config{AppWebURL: "https://web.test/app/", ApiBaseURL: "https://api.test:8443/v1"}, []string{"https://web.test", "https://api.test:8443"}},
+ {"duplicate origin once", Config{AppWebURL: "https://posta.test", ApiBaseURL: "https://posta.test/api"}, []string{"https://posta.test"}},
+ {"nothing configured", Config{}, nil},
+ {"unparseable url skipped", Config{AppWebURL: "posta.test"}, nil},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := tc.cfg.AllowedCORSOrigins(); !slices.Equal(got, tc.want) {
+ t.Fatalf("got %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
diff --git a/internal/config/security.go b/internal/config/security.go
index 3ced6ad..aed0e3b 100644
--- a/internal/config/security.go
+++ b/internal/config/security.go
@@ -5,6 +5,7 @@ package config
import (
"fmt"
+ "slices"
"strings"
"github.com/jkaninda/logger"
@@ -130,13 +131,20 @@ func (c *Config) securityProblems() []secretProblem {
if p := c.adminPasswordProblem(); p != nil {
problems = append(problems, *p)
}
- if strings.TrimSpace(c.CORSOrigins) == "*" {
+ if slices.Contains(splitList(c.CORSOrigins), "*") {
problems = append(problems, secretProblem{
"POSTA_CORS_ORIGINS",
"allows every origin",
false,
})
}
+ if len(c.TrustedProxies) == 0 {
+ problems = append(problems, secretProblem{
+ "POSTA_TRUSTED_PROXIES",
+ "is unset, so X-Forwarded-For is trusted from any client and the IP used for rate limiting, API key allow-lists and audit logs can be spoofed",
+ false,
+ })
+ }
if c.MessagesEnabled && c.MessagesIPRateLimit <= 0 {
problems = append(problems, secretProblem{
"POSTA_MESSAGES_IP_RATE_LIMIT",
diff --git a/internal/config/security_test.go b/internal/config/security_test.go
index d593558..daec619 100644
--- a/internal/config/security_test.go
+++ b/internal/config/security_test.go
@@ -330,3 +330,49 @@ func TestWorkerWarnsWhenMessagesHaveNoNotificationPath(t *testing.T) {
t.Fatalf("ValidateWorker should still pass: %v", err)
}
}
+
+// Without trusted proxies the forwarded headers are spoofable, which matters
+// for rate limiting and allow-lists but is a deployment decision, not a reason
+// to refuse to start.
+func TestTrustedProxiesAdvisory(t *testing.T) {
+ c := &Config{Env: "production", JWTSecret: strongSecret, AdminPassword: strongSecret}
+ if !hasProblem(c.securityProblems(), "POSTA_TRUSTED_PROXIES") {
+ t.Fatal("unset POSTA_TRUSTED_PROXIES not reported")
+ }
+ if err := c.ValidateSecurity(); err != nil {
+ t.Fatalf("advisory problem treated as fatal: %v", err)
+ }
+
+ c.TrustedProxies = []string{"10.0.0.0/8"}
+ if hasProblem(c.securityProblems(), "POSTA_TRUSTED_PROXIES") {
+ t.Fatal("configured POSTA_TRUSTED_PROXIES still reported")
+ }
+}
+
+// okapi trusts no proxy at all when one entry is invalid, so a typo must stop
+// the boot rather than collapse every client onto the proxy's address.
+func TestValidateRejectsInvalidTrustedProxy(t *testing.T) {
+ for _, tc := range []struct {
+ entries []string
+ wantErr bool
+ }{
+ {[]string{"10.0.0.0/8", "192.0.2.7", "::1", "fd00::/8"}, false},
+ {[]string{"10.0.0.0/33"}, true},
+ {[]string{"proxy.internal"}, true},
+ } {
+ c := &Config{Env: "dev", TrustedProxies: tc.entries}
+ if err := c.validate(); (err != nil) != tc.wantErr {
+ t.Errorf("%v: err = %v, wantErr %v", tc.entries, err, tc.wantErr)
+ }
+ }
+}
+
+func TestSplitList(t *testing.T) {
+ got := splitList(" 10.0.0.0/8 , ,192.0.2.7,")
+ if len(got) != 2 || got[0] != "10.0.0.0/8" || got[1] != "192.0.2.7" {
+ t.Fatalf("splitList = %q", got)
+ }
+ if splitList("") != nil {
+ t.Fatal("empty input should yield no entries")
+ }
+}
diff --git a/internal/handlers/server_handler.go b/internal/handlers/server_handler.go
index 4fd56b1..13e78a9 100644
--- a/internal/handlers/server_handler.go
+++ b/internal/handlers/server_handler.go
@@ -43,16 +43,16 @@ type CreateServerRequest struct {
type UpdateServerRequest struct {
ID int `param:"id"`
Body struct {
- Name string `json:"name"`
- Host string `json:"host"`
- Port int `json:"port"`
- Username string `json:"username"`
- Password string `json:"password"`
- Encryption string `json:"encryption"`
- MaxRetries *int `json:"max_retries"`
- Status string `json:"status"`
- AllowedDomains []string `json:"allowed_domains"`
- SecurityMode string `json:"security_mode" enum:"permissive,strict"`
+ Name string `json:"name"`
+ Host string `json:"host"`
+ Port int `json:"port"`
+ Username string `json:"username"`
+ Password string `json:"password"`
+ Encryption string `json:"encryption"`
+ MaxRetries *int `json:"max_retries"`
+ Status string `json:"status"`
+ AllowedDomains *[]string `json:"allowed_domains"`
+ SecurityMode string `json:"security_mode" enum:"permissive,strict"`
} `json:"body"`
}
@@ -173,7 +173,7 @@ func (h *ServerHandler) Update(c *okapi.Context, req *UpdateServerRequest) error
server.MaxRetries = *req.Body.MaxRetries
}
if req.Body.AllowedDomains != nil {
- server.AllowedDomains = req.Body.AllowedDomains
+ server.AllowedDomains = *req.Body.AllowedDomains
}
switch req.Body.SecurityMode {
case models.ServerSecurityModeStrict:
diff --git a/internal/handlers/smtp_handler.go b/internal/handlers/smtp_handler.go
index a7f4094..e4db04d 100644
--- a/internal/handlers/smtp_handler.go
+++ b/internal/handlers/smtp_handler.go
@@ -38,14 +38,14 @@ type CreateSMTPRequest struct {
type UpdateSMTPRequest struct {
ID int `param:"id"`
Body struct {
- Host string `json:"host"`
- Port int `json:"port"`
- Username string `json:"username"`
- Password string `json:"password"`
- Encryption string `json:"encryption"`
- MaxRetries *int `json:"max_retries"`
- AllowedEmails []string `json:"allowed_emails"`
- Status string `json:"status"`
+ Host string `json:"host"`
+ Port int `json:"port"`
+ Username string `json:"username"`
+ Password string `json:"password"`
+ Encryption string `json:"encryption"`
+ MaxRetries *int `json:"max_retries"`
+ AllowedEmails *[]string `json:"allowed_emails"`
+ Status string `json:"status"`
} `json:"body"`
}
type GetSMTPRequest struct {
@@ -201,10 +201,10 @@ func (h *SMTPHandler) Update(c *okapi.Context, req *UpdateSMTPRequest) error {
server.MaxRetries = *req.Body.MaxRetries
}
if req.Body.AllowedEmails != nil {
- if err := h.validateAllowedEmails(repositories.ResourceScope{UserID: server.UserID, WorkspaceID: server.WorkspaceID}, req.Body.AllowedEmails); err != nil {
+ if err := h.validateAllowedEmails(repositories.ResourceScope{UserID: server.UserID, WorkspaceID: server.WorkspaceID}, *req.Body.AllowedEmails); err != nil {
return c.AbortBadRequest(err.Error())
}
- server.AllowedEmails = req.Body.AllowedEmails
+ server.AllowedEmails = *req.Body.AllowedEmails
}
// Handle status changes
diff --git a/internal/routes/message_routes_test.go b/internal/routes/message_routes_test.go
index 77f1c9d..22db6f5 100644
--- a/internal/routes/message_routes_test.go
+++ b/internal/routes/message_routes_test.go
@@ -11,7 +11,13 @@ import (
"github.com/jkaninda/okapi"
)
-func TestOkapiAutoRegistersOptionsPerPath(t *testing.T) {
+// The global CORS preflight only answers for POSTA_CORS_ORIGINS. A customer
+// site embedding a form is never on that list, so its preflight gets no
+// Access-Control-Allow-Origin and ingest must stay reachable with simple
+// requests (see the test below). Since okapi v1.0.0 an explicit OPTIONS route
+// can be registered alongside CORS, so per-form preflight is possible if JSON
+// submissions from customer origins are ever needed.
+func TestGlobalPreflightIgnoresUnlistedOrigins(t *testing.T) {
app := okapi.New()
app.WithCORS(okapi.Cors{AllowedOrigins: []string{"https://dashboard.test"}})
@@ -23,23 +29,15 @@ func TestOkapiAutoRegistersOptionsPerPath(t *testing.T) {
Group: group,
})
- panicked := func() (p bool) {
- defer func() {
- if recover() != nil {
- p = true
- }
- }()
- app.Register(okapi.RouteDefinition{
- Method: http.MethodOptions,
- Path: "/{key}",
- Handler: func(c *okapi.Context) error { return nil },
- Group: group,
- })
- return false
- }()
+ req := httptest.NewRequest(http.MethodOptions, "/api/v1/f/abc", nil)
+ req.Header.Set("Origin", "https://customer.test")
+ req.Header.Set("Access-Control-Request-Method", http.MethodPost)
+ req.Header.Set("Access-Control-Request-Headers", "content-type")
+ rec := httptest.NewRecorder()
+ app.ServeHTTP(rec, req)
- if !panicked {
- t.Fatal("okapi no longer auto-registers OPTIONS per path; the ingest route may now own its own preflight handler")
+ if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "" {
+ t.Fatalf("preflight from an unlisted origin was allowed: %q", got)
}
}