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
fix(security): enforce workspace RBAC on administrative routes fix(config)validate production secrets at startup fix(security)require authentication for /api/v1/info
Jonas Kanindad8c98b526989
diff --git a/.env.example b/.env.exampleindex 7b51e75..9831c5e 100644--- a/.env.example+++ b/.env.example@@ -2,6 +2,9 @@# HTTP server portPOSTA_PORT=9000# Environment (dev, production)+# With POSTA_ENV=production the server refuses to start on a missing, placeholder,+# or too-short POSTA_JWT_SECRET, and refuses to seed the first admin account with+# a placeholder POSTA_ADMIN_PASSWORD. Use dev for a local quick start.POSTA_ENV=production# Database (PostgreSQL)@@ -22,7 +25,11 @@ POSTA_REDIS_USERNAME=POSTA_REDIS_PASSWORD=POSTA_REDIS_DB=0-# JWT signing secret — change this in production!+# JWT signing secret — REQUIRED in production, 32+ characters recommended.+# Signs dashboard sessions, tracking links, and the email stamper: anyone who+# knows it can forge a session. Production refuses to start if this is empty or+# left at the placeholder below, and warns if it is shorter than 32 characters.+# Generate one with: openssl rand -hex 32POSTA_JWT_SECRET=change-me-in-production# Store emails without sending (useful for development)@@ -34,7 +41,9 @@ POSTA_RATE_LIMIT_HOURLY=100# Daily email limit per userPOSTA_RATE_LIMIT_DAILY=1000-# Default admin credentials+# Default admin credentials, used only to create the first account on an empty+# database. In production the password must be at least 12 characters and not a+# known placeholder, or the initial seed is refused.POSTA_ADMIN_PASSWORD=admin1234diff --git a/cmd/posta/server.go b/cmd/posta/server.goindex 61a4934..ac7d36b 100644--- a/cmd/posta/server.go+++ b/cmd/posta/server.go@@ -97,7 +97,7 @@ func runServer(cli *okapicli.CLI) {// Initialize SMTP password encryptioncrypto.Init(cfg.EncryptionKey)- if err := storage.SeedAdmin(res.db, cfg.AdminEmail, cfg.AdminPassword); err != nil {+ if err := storage.SeedAdmin(res.db, cfg.AdminEmail, cfg.AdminPassword, cfg.ValidateAdminSeedPassword); err != nil {logger.Fatal("failed to seed admin user", "error", err)}diff --git a/compose.yml b/compose.ymlindex 5e8c583..cfd7a8f 100644--- a/compose.yml+++ b/compose.yml@@ -8,6 +8,10 @@ services:environment:POSTA_DB_URL: "host=posta-db user=posta password=posta dbname=posta port=5432 sslmode=disable"POSTA_REDIS_ADDR: "posta-redis:6379"+ # Local quick start only. Production rejects the placeholder credentials+ # below, so this file declares itself dev; see examples/ for a deployable+ # template that requires real secrets.+ POSTA_ENV: "dev"POSTA_JWT_SECRET: "change-me-in-production"POSTA_ADMIN_EMAIL: "[email protected]"POSTA_ADMIN_PASSWORD: "admin1234"diff --git a/docs/docs/analytics/health-checks.md b/docs/docs/analytics/health-checks.mdindex 430ef39..5e4ea70 100644--- a/docs/docs/analytics/health-checks.md+++ b/docs/docs/analytics/health-checks.md@@ -45,6 +45,9 @@ Returns `503 Service Unavailable` if any dependency is down.## Application Info+Requires authentication (a dashboard session or an API key), so it is not+suitable as a probe target — use `/healthz` and `/readyz` for that.+```GET /api/v1/info```diff --git a/docs/docs/security/authentication.md b/docs/docs/security/authentication.mdindex 585da69..fe130cf 100644--- a/docs/docs/security/authentication.md+++ b/docs/docs/security/authentication.md@@ -123,7 +123,6 @@ These endpoints do not require authentication:- `GET /healthz` — Liveness probe- `GET /readyz` — Readiness probe-- `GET /api/v1/info` — Application info- `POST /api/v1/auth/login` — Login- `POST /api/v1/auth/register` — Register- `GET /api/v1/auth/registration-status` — Check registrationdiff --git a/examples/.env.example b/examples/.env.exampleindex c83d193..e21e6d3 100644--- a/examples/.env.example+++ b/examples/.env.example@@ -2,6 +2,9 @@# HTTP server portPOSTA_PORT=9000# Environment (dev, production)+# With POSTA_ENV=production the server refuses to start on a missing, placeholder,+# or too-short POSTA_JWT_SECRET, and refuses to seed the first admin account with+# a placeholder POSTA_ADMIN_PASSWORD. Use dev for a local quick start.POSTA_ENV=production# Database (PostgreSQL)@@ -22,7 +25,11 @@ POSTA_REDIS_USERNAME=POSTA_REDIS_PASSWORD=POSTA_REDIS_DB=0-# JWT signing secret — change this in production!+# JWT signing secret — REQUIRED in production, 32+ characters recommended.+# Signs dashboard sessions, tracking links, and the email stamper: anyone who+# knows it can forge a session. Production refuses to start if this is empty or+# left at the placeholder below, and warns if it is shorter than 32 characters.+# Generate one with: openssl rand -hex 32POSTA_JWT_SECRET=change-me-in-production# Store emails without sending (useful for development)@@ -34,7 +41,9 @@ POSTA_RATE_LIMIT_HOURLY=100# Daily email limit per userPOSTA_RATE_LIMIT_DAILY=1000-# Default admin credentials+# Default admin credentials, used only to create the first account on an empty+# database. In production the password must be at least 12 characters and not a+# known placeholder, or the initial seed is refused.POSTA_ADMIN_PASSWORD=admin1234diff --git a/examples/compose.yml b/examples/compose.ymlindex b4fbd7a..84497cf 100644--- a/examples/compose.yml+++ b/examples/compose.yml@@ -18,9 +18,11 @@ services:POSTA_DB_PORT: 5432POSTA_DB_SSL_MODE: disablePOSTA_REDIS_ADDR: "posta-redis:6379"- POSTA_JWT_SECRET: "change-me-in-production"+ # Both are required: compose refuses to start until they are set, and the+ # server rejects placeholder or too-short values in production anyway.+ POSTA_JWT_SECRET: "${POSTA_JWT_SECRET:?required, min 32 chars, generate with openssl rand -hex 32}"POSTA_ADMIN_EMAIL: "[email protected]"- POSTA_ADMIN_PASSWORD: "admin1234"+ POSTA_ADMIN_PASSWORD: "${POSTA_ADMIN_PASSWORD:?required, min 12 chars, sets the initial admin password}"POSTA_EMBEDDED_WORKER: "true"healthcheck:test: ["CMD", "wget", "-qO-", "http://localhost:9000/healthz"]diff --git a/examples/docker-compose-full.yml b/examples/docker-compose-full.ymlindex a69c911..85e5513 100644--- a/examples/docker-compose-full.yml+++ b/examples/docker-compose-full.yml@@ -25,9 +25,11 @@ services:POSTA_DB_PORT: 5432POSTA_DB_SSL_MODE: disablePOSTA_REDIS_ADDR: "posta-redis:6379"- POSTA_JWT_SECRET: "change-me-in-production"+ # Both are required: compose refuses to start until they are set, and the+ # server rejects placeholder or too-short values in production anyway.+ POSTA_JWT_SECRET: "${POSTA_JWT_SECRET:?required, min 32 chars, generate with openssl rand -hex 32}"POSTA_ADMIN_EMAIL: "[email protected]"- POSTA_ADMIN_PASSWORD: "admin1234"+ POSTA_ADMIN_PASSWORD: "${POSTA_ADMIN_PASSWORD:?required, min 12 chars, sets the initial admin password}"healthcheck:test: ["CMD", "wget", "-qO-", "http://localhost:9000/healthz"]interval: 30sdiff --git a/internal/config/config.go b/internal/config/config.goindex c7af07d..c863259 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -240,7 +240,7 @@ func New() *Config {},Redis: newRedisConfig(),Port: goutils.EnvInt("POSTA_PORT", 9000),- Env: goutils.Env("POSTA_ENV", "dev"),+ Env: goutils.Env("POSTA_ENV", "production"),JWTSecret: goutils.Env("POSTA_JWT_SECRET", "change-me-in-production"),DevMode: goutils.EnvBool("POSTA_DEV_MODE", false),RateLimitHourly: goutils.EnvInt("POSTA_RATE_LIMIT_HOURLY", 100),@@ -333,11 +333,12 @@ 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)}}- return nil+ return c.ValidateSecurity()}func (c *Config) validateWorker() error {-- return nil+ // The worker verifies the same JWTs the server issues, so it needs the same+ // secret to be real.+ return c.ValidateSecurity()}func (c *Config) Initialize(app *okapi.Okapi) error {if err := c.validate(); err != nil {@@ -345,6 +346,7 @@ func (c *Config) Initialize(app *okapi.Okapi) error {}// Initialize global loggerl := c.initLogger()+ c.WarnInsecureConfig()// Dev modeif c.DevMode {app.WithDebug()@@ -414,6 +416,7 @@ func (c *Config) Initialize(app *okapi.Okapi) error {func (c *Config) InitWorker() error {// Initialize global loggerc.initLogger()+ c.WarnInsecureConfig()if err := c.validateWorker(); err != nil {return err}diff --git a/internal/config/security.go b/internal/config/security.gonew file mode 100644index 0000000..31ca46c--- /dev/null+++ b/internal/config/security.go@@ -0,0 +1,191 @@+/*+ * Copyright 2026 Jonas Kaninda+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ */++package config++import (+ "fmt"+ "strings"++ "github.com/jkaninda/logger"+)++const (+ // MinJWTSecretLength is the shortest signing secret considered sound. The+ // secret signs dashboard sessions, tracking-link HMACs, and the email+ // stamper, so a guessable value forges all three. Falling below this warns+ // rather than blocks; see jwtSecretProblem for why.+ MinJWTSecretLength = 32++ // MinAdminPasswordLength is the shortest seeded admin password accepted in+ // production. It only gates the initial seed, never an existing install.+ MinAdminPasswordLength = 12+)++// placeholderSecrets are values published in this repository's compose files,+// .env.example, and installation docs. They are not secrets in any deployment:+// anyone can read them, so a value matching one is treated as absent.+var placeholderSecrets = map[string]bool{+ "change-me-in-production": true,+ "change-me": true,+ "changeme": true,+ "admin1234": true,+ "password": true,+ "secret": true,+ "posta": true,+ "your-secret-key": true,+ "supersecret": true,+}++// isPlaceholder reports whether v is a known published placeholder. Comparison+// is case- and whitespace-insensitive so that "Change-Me-In-Production " does+// not slip through.+func isPlaceholder(v string) bool {+ return placeholderSecrets[strings.ToLower(strings.TrimSpace(v))]+}++// IsProduction reports whether the deployment declares itself production via+// POSTA_ENV. It defaults to dev, so this is opt-in: an operator who never sets+// POSTA_ENV keeps the previous quick-start behaviour and gets warnings instead+// of a refusal to boot.+func (c *Config) IsProduction() bool {+ switch strings.ToLower(strings.TrimSpace(c.Env)) {+ case "prod", "production":+ return true+ default:+ return false+ }+}++// secretProblem describes one unacceptable configuration value.+type secretProblem struct {+ envVar string+ reason string+ fatal bool+}++func (c *Config) jwtSecretProblem() *secretProblem {+ switch {+ case strings.TrimSpace(c.JWTSecret) == "":+ return &secretProblem{"POSTA_JWT_SECRET", "is empty", true}+ case isPlaceholder(c.JWTSecret):+ return &secretProblem{"POSTA_JWT_SECRET", "is the published placeholder value, so sessions can be forged by anyone", true}+ case len(c.JWTSecret) < MinJWTSecretLength:+ return &secretProblem{+ "POSTA_JWT_SECRET",+ fmt.Sprintf("is shorter than the recommended %d characters and may be brute-forced offline from a captured token", MinJWTSecretLength),+ false,+ }+ }+ return nil+}++// adminPasswordProblem checks the seed password. It is not fatal at config+// time: an upgraded install has long since changed the password in-app and may+// not set the variable at all. storage.SeedAdmin re-checks it at the point+// where it would actually be used, which is the only place it can matter.+func (c *Config) adminPasswordProblem() *secretProblem {+ switch {+ case isPlaceholder(c.AdminPassword):+ return &secretProblem{"POSTA_ADMIN_PASSWORD", "is the published placeholder value", false}+ case len(c.AdminPassword) < MinAdminPasswordLength:+ return &secretProblem{"POSTA_ADMIN_PASSWORD", fmt.Sprintf("is shorter than %d characters", MinAdminPasswordLength), false}+ }+ return nil+}++// securityProblems collects every unacceptable value in one pass so an operator+// fixing their configuration sees the whole list rather than one item per boot.+func (c *Config) securityProblems() []secretProblem {+ var problems []secretProblem++ if p := c.jwtSecretProblem(); p != nil {+ problems = append(problems, *p)+ }+ if p := c.adminPasswordProblem(); p != nil {+ problems = append(problems, *p)+ }+ if strings.TrimSpace(c.EncryptionKey) == "" {+ problems = append(problems, secretProblem{+ "POSTA_ENCRYPTION_KEY",+ "is unset, so stored SMTP credentials fall back to base64 encoding, which is reversible",+ false,+ })+ }+ if strings.TrimSpace(c.CORSOrigins) == "*" {+ problems = append(problems, secretProblem{+ "POSTA_CORS_ORIGINS",+ "allows every origin",+ false,+ })+ }++ return problems+}++// ValidateSecurity refuses to start a production deployment whose configuration+// contains a fatal problem. Non-production deployments never fail here; they are+// reported through WarnInsecureConfig instead.+func (c *Config) ValidateSecurity() error {+ if !c.IsProduction() {+ return nil+ }+ for _, p := range c.securityProblems() {+ if p.fatal {+ return fmt.Errorf(+ "%s %s; set it to a strong random value (for example: openssl rand -hex 32). "++ "Set POSTA_ENV=dev to run without this check outside production",+ p.envVar, p.reason)+ }+ }+ return nil+}++// WarnInsecureConfig logs every remaining problem after the logger exists. In+// production the fatal ones have already stopped the boot, so this reports the+// advisory remainder; outside production it reports everything, which is how an+// operator learns what to fix before setting POSTA_ENV=production.+func (c *Config) WarnInsecureConfig() {+ for _, p := range c.securityProblems() {+ if p.fatal && c.IsProduction() {+ continue+ }+ msg := p.envVar + " " + p.reason+ if p.fatal {+ logger.Warn("insecure configuration: "+msg+" — this will refuse to start when POSTA_ENV=production", "env", p.envVar)+ continue+ }+ logger.Warn("insecure configuration: "+msg, "env", p.envVar)+ }+}++// ValidateAdminSeedPassword reports whether the configured seed password is fit+// to create the first admin user on a production deployment. storage.SeedAdmin+// calls this only when it is about to create that user, so an existing install+// whose password was changed in-app is unaffected.+func (c *Config) ValidateAdminSeedPassword() error {+ if !c.IsProduction() {+ return nil+ }+ if p := c.adminPasswordProblem(); p != nil {+ return fmt.Errorf(+ "refusing to seed the initial admin account: %s %s; "++ "set POSTA_ADMIN_PASSWORD to a strong value before first start",+ p.envVar, p.reason)+ }+ return nil+}diff --git a/internal/config/security_test.go b/internal/config/security_test.gonew file mode 100644index 0000000..50062d2--- /dev/null+++ b/internal/config/security_test.go@@ -0,0 +1,234 @@+/*+ * Copyright 2026 Jonas Kaninda+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ */++package config++import (+ "strings"+ "testing"+)++// strongSecret is a stand-in for a real generated value. It is not a credential+// for anything: it exists only to be long enough and not a known placeholder.+const strongSecret = "b7f4c1a9e35d820647fbca1e9d7350af26bc4d1e8f09a3b5c7d2e4f60819a3bc"++func TestIsProduction(t *testing.T) {+ cases := map[string]bool{+ "production": true,+ "prod": true,+ "PRODUCTION": true,+ " Prod ": true,+ "dev": false,+ "": false,+ "staging": false,+ }+ for env, want := range cases {+ c := &Config{Env: env}+ if got := c.IsProduction(); got != want {+ t.Errorf("Env=%q: IsProduction() = %v, want %v", env, got, want)+ }+ }+}++// A non-production deployment must keep booting on the shipped defaults —+// that is the quick-start path, and breaking it would be a regression.+func TestValidateSecurity_DevAcceptsDefaults(t *testing.T) {+ c := &Config{+ Env: "dev",+ JWTSecret: "change-me-in-production",+ AdminPassword: "admin1234",+ }+ if err := c.ValidateSecurity(); err != nil {+ t.Fatalf("dev deployment rejected: %v", err)+ }+}++// A secret that is public knowledge is no secret at all, so production refuses+// to start on one.+func TestValidateSecurity_ProductionRejectsPublicJWTSecret(t *testing.T) {+ cases := []struct {+ name string+ secret string+ }{+ {"published placeholder", "change-me-in-production"},+ {"placeholder with different case and padding", " Change-Me-In-Production "},+ {"other known placeholder", "changeme"},+ {"empty", ""},+ {"whitespace only", " "},+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ c := &Config{Env: "production", JWTSecret: tc.secret, AdminPassword: strongSecret}+ err := c.ValidateSecurity()+ if err == nil {+ t.Fatalf("JWTSecret=%q accepted in production, want rejection", tc.secret)+ }+ if !strings.Contains(err.Error(), "POSTA_JWT_SECRET") {+ t.Errorf("error does not name the variable to fix: %v", err)+ }+ })+ }+}++// A short but operator-chosen secret is not published anywhere. It is reported,+// but it must not brick a running deployment on upgrade.+func TestValidateSecurity_ProductionWarnsOnShortJWTSecret(t *testing.T) {+ cases := []struct {+ name string+ secret string+ }{+ {"short custom secret", "abc123"},+ {"one below the minimum", strings.Repeat("a", MinJWTSecretLength-1)},+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ c := &Config{Env: "production", JWTSecret: tc.secret, AdminPassword: strongSecret}++ if err := c.ValidateSecurity(); err != nil {+ t.Fatalf("short custom secret blocked startup, want warning only: %v", err)+ }+ if !hasProblem(c.securityProblems(), "POSTA_JWT_SECRET") {+ t.Error("short secret not reported as a problem at all")+ }+ })+ }+}++// The boundary itself must be accepted without complaint.+func TestValidateSecurity_MinimumLengthSecretIsClean(t *testing.T) {+ c := &Config{+ Env: "production",+ JWTSecret: strings.Repeat("a", MinJWTSecretLength),+ AdminPassword: strongSecret,+ EncryptionKey: strongSecret,+ CORSOrigins: "https://mail.example.com",+ }+ if err := c.ValidateSecurity(); err != nil {+ t.Fatalf("secret at the minimum length rejected: %v", err)+ }+ if hasProblem(c.securityProblems(), "POSTA_JWT_SECRET") {+ t.Error("secret at the minimum length reported as a problem")+ }+}++func TestValidateSecurity_ProductionAcceptsStrongSecret(t *testing.T) {+ c := &Config{+ Env: "production",+ JWTSecret: strongSecret,+ AdminPassword: strongSecret,+ EncryptionKey: strongSecret,+ CORSOrigins: "https://mail.example.com",+ }+ if err := c.ValidateSecurity(); err != nil {+ t.Fatalf("well-configured production deployment rejected: %v", err)+ }+}++// A placeholder admin password must not block startup: an upgraded install+// changed the password in-app long ago and may never set the variable. The+// check belongs at the point of seeding instead.+func TestValidateSecurity_ProductionAllowsPlaceholderAdminPassword(t *testing.T) {+ c := &Config{+ Env: "production",+ JWTSecret: strongSecret,+ AdminPassword: "admin1234",+ }+ if err := c.ValidateSecurity(); err != nil {+ t.Fatalf("existing install blocked by seed password: %v", err)+ }+}++// Nor must an unset encryption key or a wildcard CORS policy, which need a+// migration and a deployment decision respectively.+func TestValidateSecurity_ProductionAllowsAdvisoryProblems(t *testing.T) {+ c := &Config{+ Env: "production",+ JWTSecret: strongSecret,+ AdminPassword: strongSecret,+ EncryptionKey: "",+ CORSOrigins: "*",+ }+ if err := c.ValidateSecurity(); err != nil {+ t.Fatalf("advisory problem treated as fatal: %v", err)+ }++ problems := c.securityProblems()+ for _, want := range []string{"POSTA_ENCRYPTION_KEY", "POSTA_CORS_ORIGINS"} {+ if !hasProblem(problems, want) {+ t.Errorf("%s not reported as a problem", want)+ }+ }+}++func TestValidateAdminSeedPassword(t *testing.T) {+ cases := []struct {+ name string+ env string+ password string+ wantReject bool+ }{+ {"production placeholder", "production", "admin1234", true},+ {"production too short", "production", "short", true},+ {"production strong", "production", strongSecret, false},+ {"dev placeholder", "dev", "admin1234", false},+ {"dev short", "dev", "x", false},+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ c := &Config{Env: tc.env, AdminPassword: tc.password}+ err := c.ValidateAdminSeedPassword()+ if tc.wantReject && err == nil {+ t.Fatalf("password %q accepted for seeding, want rejection", tc.password)+ }+ if !tc.wantReject && err != nil {+ t.Fatalf("password rejected unexpectedly: %v", err)+ }+ if tc.wantReject && !strings.Contains(err.Error(), "POSTA_ADMIN_PASSWORD") {+ t.Errorf("error does not name the variable to fix: %v", err)+ }+ })+ }+}++// The defaults compiled into Load must themselves be the ones the production+// check rejects. If someone changes a default, this catches a silent drift+// between the shipped value and the value the guard knows to refuse.+func TestShippedDefaultsAreRejectedInProduction(t *testing.T) {+ c := &Config{+ Env: "production",+ JWTSecret: "change-me-in-production",+ AdminPassword: "admin1234",+ }+ if err := c.ValidateSecurity(); err == nil {+ t.Fatal("shipped default JWT secret accepted in production")+ }+ if err := c.ValidateAdminSeedPassword(); err == nil {+ t.Fatal("shipped default admin password accepted for production seeding")+ }+}++func hasProblem(problems []secretProblem, envVar string) bool {+ for _, p := range problems {+ if p.envVar == envVar {+ return true+ }+ }+ return false+}diff --git a/internal/handlers/workspace_handler.go b/internal/handlers/workspace_handler.goindex 6733226..2d4439a 100644--- a/internal/handlers/workspace_handler.go+++ b/internal/handlers/workspace_handler.go@@ -525,11 +525,21 @@ type DeleteInvitationRequest struct {}func (h *WorkspaceHandler) DeleteInvitation(c *okapi.Context, req *DeleteInvitationRequest) error {+ wsID := c.GetInt("workspace_id")+inv, err := h.workspaceRepo.FindInvitationByID(uint(req.InvitationID))if err != nil {return c.AbortNotFound("invitation not found")}+ // Invitation IDs are global and guessable, so an ID alone does not authorize+ // the revocation: it must belong to the workspace the caller is acting in.+ // Report it as missing rather than forbidden so the endpoint cannot be used+ // to probe which invitation IDs exist in other workspaces.+ if inv.WorkspaceID != uint(wsID) {+ return c.AbortNotFound("invitation not found")+ }+if err := h.workspaceRepo.DeleteInvitation(uint(req.InvitationID)); err != nil {return c.AbortNotFound("invitation not found")}diff --git a/internal/routes/auth_routes.go b/internal/routes/auth_routes.goindex efbe1d6..825fb5c 100644--- a/internal/routes/auth_routes.go+++ b/internal/routes/auth_routes.go@@ -52,15 +52,20 @@ func (r *Router) healthRoutes() []okapi.RouteDefinition {}// infoRoute returns the route definition for the application info endpoint.+//+// Authenticated: the version and commit ID identify the exact build running,+// which is what an attacker needs to match a deployment against known CVEs.+// Liveness and readiness probes use /healthz and /readyz, which stay public.func (r *Router) infoRoute() okapi.RouteDefinition {return okapi.RouteDefinition{Method: http.MethodGet,Path: "/info",Handler: handlers.Info,Group: r.v1,+ Middlewares: []okapi.Middleware{r.mw.auth},Tags: []string{"Info"},Summary: "Application info",- Description: "Returns app name, version, and commit ID",+ Description: "Returns app name, version, and commit ID. Requires a dashboard session or an API key.",Response: &dto.Response[handlers.AppInfo]{},}}diff --git a/internal/routes/oauth_routes.go b/internal/routes/oauth_routes.goindex 7817ca5..6cfb90c 100644--- a/internal/routes/oauth_routes.go+++ b/internal/routes/oauth_routes.go@@ -5,6 +5,8 @@ import ("github.com/goposta/posta/internal/dto""github.com/goposta/posta/internal/handlers"+ "github.com/goposta/posta/internal/middlewares"+ "github.com/goposta/posta/internal/models""github.com/jkaninda/okapi")@@ -164,32 +166,38 @@ func (r *Router) oauthRoutes() []okapi.RouteDefinition {routes = append(routes, []okapi.RouteDefinition{{- Method: http.MethodGet,- Path: "",- Handler: r.h.oauthAdmin.GetWorkspaceSSO,- Group: wsSSO,- Summary: "Get workspace SSO config",- Response: &dto.Response[handlers.WorkspaceSSOResponse]{},- Options: []okapi.RouteOption{workspaceHeaderRequired},+ Method: http.MethodGet,+ Path: "",+ Handler: r.h.oauthAdmin.GetWorkspaceSSO,+ Group: wsSSO,+ Middlewares: []okapi.Middleware{middlewares.RequireWorkspaceRole(models.WorkspaceRoleAdmin)},+ Summary: "Get workspace SSO config",+ Description: "Read the workspace's SSO enforcement config (admin/owner only)",+ Response: &dto.Response[handlers.WorkspaceSSOResponse]{},+ Options: []okapi.RouteOption{workspaceHeaderRequired},},{- Method: http.MethodPut,- Path: "",- Handler: okapi.H(r.h.oauthAdmin.SetWorkspaceSSO),- Group: wsSSO,- Summary: "Set workspace SSO config",- Request: &handlers.SetWorkspaceSSORequest{},- Response: &dto.Response[okapi.M]{},- Options: []okapi.RouteOption{workspaceHeaderRequired},+ Method: http.MethodPut,+ Path: "",+ Handler: okapi.H(r.h.oauthAdmin.SetWorkspaceSSO),+ Group: wsSSO,+ Middlewares: []okapi.Middleware{middlewares.RequireWorkspaceRole(models.WorkspaceRoleAdmin)},+ Summary: "Set workspace SSO config",+ Description: "Configure the workspace's SSO enforcement (admin/owner only)",+ Request: &handlers.SetWorkspaceSSORequest{},+ Response: &dto.Response[okapi.M]{},+ Options: []okapi.RouteOption{workspaceHeaderRequired},},{- Method: http.MethodDelete,- Path: "",- Handler: r.h.oauthAdmin.DeleteWorkspaceSSO,- Group: wsSSO,- Summary: "Delete workspace SSO config",- Response: &dto.Response[okapi.M]{},- Options: []okapi.RouteOption{workspaceHeaderRequired},+ Method: http.MethodDelete,+ Path: "",+ Handler: r.h.oauthAdmin.DeleteWorkspaceSSO,+ Group: wsSSO,+ Middlewares: []okapi.Middleware{middlewares.RequireWorkspaceRole(models.WorkspaceRoleAdmin)},+ Summary: "Delete workspace SSO config",+ Description: "Remove the workspace's SSO enforcement (admin/owner only)",+ Response: &dto.Response[okapi.M]{},+ Options: []okapi.RouteOption{workspaceHeaderRequired},},}...)diff --git a/internal/routes/workspace_rbac_test.go b/internal/routes/workspace_rbac_test.gonew file mode 100644index 0000000..b3a936f--- /dev/null+++ b/internal/routes/workspace_rbac_test.go@@ -0,0 +1,175 @@+/*+ * Copyright 2026 Jonas Kaninda+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ *+ */++package routes++import (+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/goposta/posta/internal/config"+ "github.com/goposta/posta/internal/middlewares"+ "github.com/goposta/posta/internal/models"+ "github.com/jkaninda/okapi"+)++// workspaceRouteDefs builds the real route definitions. The handlers are never+// invoked — only the middleware chain each route carries is exercised — so the+// zero-value handler set is enough, and this stays a pure wiring test with no+// database or service dependencies.+func workspaceRouteDefs(t *testing.T) []okapi.RouteDefinition {+ t.Helper()++ o := okapi.NewTestServer(t)+ r := &Router{+ app: o.Okapi,+ cfg: &config.Config{},+ v1: o.Group("/api/v1"),+ }+ return append(r.workspaceRoutes(), r.oauthRoutes()...)+}++// defBySummary indexes route definitions by their Summary, which is unique+// across the workspace surface and reads better in failure output than a+// method/path pair repeated across groups.+func defBySummary(t *testing.T, defs []okapi.RouteDefinition, summary string) okapi.RouteDefinition {+ t.Helper()++ for _, d := range defs {+ if d.Summary == summary {+ return d+ }+ }+ t.Fatalf("no route definition with summary %q", summary)+ return okapi.RouteDefinition{}+}++// seedSessionRole mimics what RequireWorkspaceMiddleware leaves in the context+// for a dashboard caller who is a member of the active workspace.+func seedSessionRole(role models.WorkspaceRole) okapi.Middleware {+ return func(c *okapi.Context) error {+ c.Set(middlewares.CtxUserID, 1)+ c.Set(middlewares.CtxAuthMethod, middlewares.AuthMethodJWT)+ c.Set(middlewares.CtxWorkspaceID, 1)+ c.Set(middlewares.CtxWorkspaceRole, string(role))+ return c.Next()+ }+}++// runRouteAs replays a route's own middleware chain against a caller holding+// the given workspace role and reports the resulting status. 200 means the+// chain let the request through to the handler.+func runRouteAs(t *testing.T, def okapi.RouteDefinition, role models.WorkspaceRole) int {+ t.Helper()++ chain := []okapi.Middleware{seedSessionRole(role)}+ for _, m := range def.Middlewares {+ if m != nil { // group-level middlewares are nil in this bare Router+ chain = append(chain, m)+ }+ }++ o := okapi.NewTestServer(t)+ o.Get("/t", func(c *okapi.Context) error {+ return c.String(http.StatusOK, "reached handler")+ }, okapi.UseMiddleware(chain...))++ rec := httptest.NewRecorder()+ o.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/t", nil))+ return rec.Code+}++// TestWorkspaceAdminRoutesRejectNonAdmins is the regression guard for the+// missing-RBAC finding: these routes documented themselves as admin/owner only+// while carrying no role guard at all, so any member — including a viewer —+// reached the handler.+func TestWorkspaceAdminRoutesRejectNonAdmins(t *testing.T) {+ defs := workspaceRouteDefs(t)++ adminOnly := []string{+ "Update workspace",+ "Update member role",+ "Remove member",+ "Invite member",+ "List pending invitations",+ "Cancel invitation",+ "Export workspace data",+ "Import workspace data",+ "Get workspace SSO config",+ "Set workspace SSO config",+ "Delete workspace SSO config",+ }++ for _, summary := range adminOnly {+ t.Run(summary, func(t *testing.T) {+ def := defBySummary(t, defs, summary)++ for _, role := range []models.WorkspaceRole{models.WorkspaceRoleOwner, models.WorkspaceRoleAdmin} {+ if got := runRouteAs(t, def, role); got != http.StatusOK {+ t.Errorf("%s as %s: status = %d, want 200", summary, role, got)+ }+ }+ for _, role := range []models.WorkspaceRole{models.WorkspaceRoleEditor, models.WorkspaceRoleViewer} {+ if got := runRouteAs(t, def, role); got != http.StatusForbidden {+ t.Errorf("%s as %s: status = %d, want 403", summary, role, got)+ }+ }+ })+ }+}++// TestDeleteWorkspaceIsOwnerOnly pins the stricter tier: the route documented+// itself as owner-only, but an admin could delete the workspace too.+func TestDeleteWorkspaceIsOwnerOnly(t *testing.T) {+ def := defBySummary(t, workspaceRouteDefs(t), "Delete workspace")++ if got := runRouteAs(t, def, models.WorkspaceRoleOwner); got != http.StatusOK {+ t.Errorf("delete workspace as owner: status = %d, want 200", got)+ }+ for _, role := range []models.WorkspaceRole{+ models.WorkspaceRoleAdmin,+ models.WorkspaceRoleEditor,+ models.WorkspaceRoleViewer,+ } {+ if got := runRouteAs(t, def, role); got != http.StatusForbidden {+ t.Errorf("delete workspace as %s: status = %d, want 403", role, got)+ }+ }+}++// TestWorkspaceMemberRoutesStayOpenToMembers guards the other direction: the+// fix must not lock ordinary members out of the reads they legitimately need.+func TestWorkspaceMemberRoutesStayOpenToMembers(t *testing.T) {+ defs := workspaceRouteDefs(t)++ for _, summary := range []string{"Get current workspace", "List workspace members", "Get workspace plan"} {+ t.Run(summary, func(t *testing.T) {+ def := defBySummary(t, defs, summary)+ for _, role := range []models.WorkspaceRole{+ models.WorkspaceRoleOwner,+ models.WorkspaceRoleAdmin,+ models.WorkspaceRoleEditor,+ models.WorkspaceRoleViewer,+ } {+ if got := runRouteAs(t, def, role); got != http.StatusOK {+ t.Errorf("%s as %s: status = %d, want 200", summary, role, got)+ }+ }+ })+ }+}diff --git a/internal/routes/workspace_routes.go b/internal/routes/workspace_routes.goindex a5bd588..f31167b 100644--- a/internal/routes/workspace_routes.go+++ b/internal/routes/workspace_routes.go@@ -82,10 +82,14 @@ func (r *Router) workspaceRoutes() []okapi.RouteDefinition {Options: []okapi.RouteOption{workspaceHeaderRequired},},{- Method: http.MethodPut,- Path: "",- Handler: okapi.H(r.h.workspace.Update),- Group: wsGroup,+ Method: http.MethodPut,+ Path: "",+ Handler: okapi.H(r.h.workspace.Update),+ Group: wsGroup,+ Middlewares: []okapi.Middleware{+ middlewares.RequireWorkspaceRole(models.WorkspaceRoleAdmin),+ middlewares.RequireScope(models.ScopeAdmin),+ },Summary: "Update workspace",Description: "Update workspace name and description (admin/owner only)",Request: &handlers.UpdateWorkspaceRequest{},@@ -93,10 +97,14 @@ func (r *Router) workspaceRoutes() []okapi.RouteDefinition {Options: []okapi.RouteOption{workspaceHeaderRequired},},{- Method: http.MethodDelete,- Path: "",- Handler: r.h.workspace.Delete,- Group: wsGroup,+ Method: http.MethodDelete,+ Path: "",+ Handler: r.h.workspace.Delete,+ Group: wsGroup,+ Middlewares: []okapi.Middleware{+ middlewares.RequireWorkspaceRole(models.WorkspaceRoleOwner),+ middlewares.RequireScope(models.ScopeAdmin),+ },Summary: "Delete workspace",Description: "Delete the workspace (owner only)",Options: []okapi.RouteOption{@@ -116,13 +124,15 @@ func (r *Router) workspaceRoutes() []okapi.RouteDefinition {Options: []okapi.RouteOption{workspaceHeaderRequired},},{- Method: http.MethodPut,- Path: "/members/{member_id:int}",- Handler: okapi.H(r.h.workspace.UpdateMemberRole),- Group: wsGroup,- Summary: "Update member role",- Request: &handlers.UpdateMemberRoleRequest{},- Response: &dto.Response[dto.MessageData]{},+ Method: http.MethodPut,+ Path: "/members/{member_id:int}",+ Handler: okapi.H(r.h.workspace.UpdateMemberRole),+ Group: wsGroup,+ Middlewares: []okapi.Middleware{middlewares.RequireWorkspaceRole(models.WorkspaceRoleAdmin)},+ Summary: "Update member role",+ Description: "Change a member's workspace role (admin/owner only)",+ Request: &handlers.UpdateMemberRoleRequest{},+ Response: &dto.Response[dto.MessageData]{},Options: []okapi.RouteOption{workspaceHeaderRequired,okapi.DocPathParam("member_id", "integer", "User ID of the member"),@@ -133,6 +143,7 @@ func (r *Router) workspaceRoutes() []okapi.RouteDefinition {Path: "/members/{member_id:int}",Handler: okapi.H(r.h.workspace.RemoveMember),Group: wsGroup,+ Middlewares: []okapi.Middleware{middlewares.RequireWorkspaceRole(models.WorkspaceRoleAdmin)},Summary: "Remove member",Description: "Remove a member from the workspace (admin/owner only)",Options: []okapi.RouteOption{@@ -144,13 +155,16 @@ func (r *Router) workspaceRoutes() []okapi.RouteDefinition {// Invitations (workspace-scoped){- Method: http.MethodPost,- Path: "/invitations",- Handler: okapi.H(r.h.workspace.InviteMember),- Group: wsGroup,- Middlewares: []okapi.Middleware{r.mw.verifiedEmail},+ Method: http.MethodPost,+ Path: "/invitations",+ Handler: okapi.H(r.h.workspace.InviteMember),+ Group: wsGroup,+ Middlewares: []okapi.Middleware{+ middlewares.RequireWorkspaceRole(models.WorkspaceRoleAdmin),+ r.mw.verifiedEmail,+ },Summary: "Invite member",- Description: "Invite a user to the workspace via email",+ Description: "Invite a user to the workspace via email (admin/owner only)",Request: &handlers.InviteMemberRequest{},Options: []okapi.RouteOption{workspaceHeaderRequired,@@ -159,20 +173,24 @@ func (r *Router) workspaceRoutes() []okapi.RouteDefinition {},},{- Method: http.MethodGet,- Path: "/invitations",- Handler: r.h.workspace.ListInvitations,- Group: wsGroup,- Summary: "List pending invitations",- Response: &dto.Response[[]handlers.InvitationResponse]{},- Options: []okapi.RouteOption{workspaceHeaderRequired},+ Method: http.MethodGet,+ Path: "/invitations",+ Handler: r.h.workspace.ListInvitations,+ Group: wsGroup,+ Middlewares: []okapi.Middleware{middlewares.RequireWorkspaceRole(models.WorkspaceRoleAdmin)},+ Summary: "List pending invitations",+ Description: "List the workspace's pending invitations (admin/owner only)",+ Response: &dto.Response[[]handlers.InvitationResponse]{},+ Options: []okapi.RouteOption{workspaceHeaderRequired},},{- Method: http.MethodDelete,- Path: "/invitations/{invitation_id:int}",- Handler: okapi.H(r.h.workspace.DeleteInvitation),- Group: wsGroup,- Summary: "Cancel invitation",+ Method: http.MethodDelete,+ Path: "/invitations/{invitation_id}",+ Handler: okapi.H(r.h.workspace.DeleteInvitation),+ Group: wsGroup,+ Middlewares: []okapi.Middleware{middlewares.RequireWorkspaceRole(models.WorkspaceRoleAdmin)},+ Summary: "Cancel invitation",+ Description: "Revoke a pending invitation in this workspace (admin/owner only)",Options: []okapi.RouteOption{workspaceHeaderRequired,okapi.DocPathParam("invitation_id", "integer", "Invitation ID"),@@ -242,24 +260,33 @@ func (r *Router) workspaceRoutes() []okapi.RouteDefinition {Options: []okapi.RouteOption{workspaceHeaderRequired},},- // Data Export/Import+ // Data Export/Import — a full tenant dump and a bulk overwrite, so both+ // are admin/owner only rather than ordinary workspace content.{- Method: http.MethodGet,- Path: "/data/export",- Handler: r.h.workspaceData.Export,- Group: wsGroup,+ Method: http.MethodGet,+ Path: "/data/export",+ Handler: r.h.workspaceData.Export,+ Group: wsGroup,+ Middlewares: []okapi.Middleware{+ middlewares.RequireWorkspaceRole(models.WorkspaceRoleAdmin),+ middlewares.RequireScope(models.ScopeAdmin),+ },Summary: "Export workspace data",- Description: "Export all workspace data including settings, templates, stylesheets, languages, contacts, contact lists, webhooks, SMTP servers, domains, subscribers, subscriber lists, and suppressions as JSON",+ Description: "Export all workspace data including settings, templates, stylesheets, languages, contacts, contact lists, webhooks, SMTP servers, domains, subscribers, subscriber lists, and suppressions as JSON (admin/owner only)",Response: &dto.Response[handlers.WorkspaceDataExport]{},Options: []okapi.RouteOption{workspaceHeaderRequired},},{- Method: http.MethodPost,- Path: "/data/import",- Handler: okapi.H(r.h.workspaceData.Import),- Group: wsGroup,+ Method: http.MethodPost,+ Path: "/data/import",+ Handler: okapi.H(r.h.workspaceData.Import),+ Group: wsGroup,+ Middlewares: []okapi.Middleware{+ middlewares.RequireWorkspaceRole(models.WorkspaceRoleAdmin),+ middlewares.RequireScope(models.ScopeAdmin),+ },Summary: "Import workspace data",- Description: "Import workspace data from a previously exported JSON payload. Duplicates are skipped. SMTP servers are imported as disabled (passwords excluded). Domains require re-verification.",+ Description: "Import workspace data from a previously exported JSON payload (admin/owner only). Duplicates are skipped. SMTP servers are imported as disabled (passwords excluded). Domains require re-verification.",Request: &handlers.ImportWorkspaceDataRequest{},Response: &dto.Response[any]{},Options: []okapi.RouteOption{workspaceHeaderRequired},diff --git a/internal/storage/postgres.go b/internal/storage/postgres.goindex d823aa8..4e344ed 100644--- a/internal/storage/postgres.go+++ b/internal/storage/postgres.go@@ -38,14 +38,25 @@ func ConnectPostgres(dsn string) (*gorm.DB, error) {return db, nil}-// SeedAdmin creates the default admin user-func SeedAdmin(db *gorm.DB, email, password string) error {+// SeedAdmin creates the default admin user.+//+// approve, when non-nil, is consulted only once it is settled that an admin+// will actually be created. That ordering matters: an existing deployment whose+// admin password was changed in-app must keep starting even though the+// configured seed password is still the shipped default.+func SeedAdmin(db *gorm.DB, email, password string, approve func() error) error {var count int64db.Model(&models.User{}).Count(&count)if count > 0 {return nil}+ if approve != nil {+ if err := approve(); err != nil {+ return err+ }+ }+hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)if err != nil {return fmt.Errorf("failed to hash admin password: %w", err)diff --git a/web/src/layouts/DashboardLayout.vue b/web/src/layouts/DashboardLayout.vueindex ab64bba..c37c07b 100644--- a/web/src/layouts/DashboardLayout.vue+++ b/web/src/layouts/DashboardLayout.vue@@ -202,7 +202,6 @@ const navSections: NavSection[] = [{ name: 'Metrics', path: '/admin/metrics', icon: 'pie-chart' },{ name: 'Events', path: '/admin/events', icon: 'zap' },{ name: 'Platform Settings', path: '/admin/settings', icon: 'settings' },- { name: 'About', path: '/about', icon: 'info' },],},]@@ -479,6 +478,14 @@ function getIcon(name: string): string {</svg>Settings</a>+ <a class="user-dropdown-item" @click.stop="navigate('/about'); userMenuOpen = false">+ <svg width="15" height="15" viewBox="0 0 16 16" fill="none">+ <circle cx="8" cy="8" r="6.5" stroke="currentColor" stroke-width="1.5" />+ <path d="M8 7.33V11.33" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />+ <circle cx="8" cy="4.83" r="0.83" fill="currentColor" />+ </svg>+ About+ </a><div class="user-dropdown-divider"></div><div class="user-dropdown-theme"><div class="user-dropdown-theme-label">