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.

refactor(auth): cookie sessions, unified credential middleware, workspace API keys (#164)

Jonas Kanindabaacb91cad84
diff --git a/go.mod b/go.mod
index 1ce1bcc..dddaae3 100644
--- a/go.mod
+++ b/go.mod
@@ -13,7 +13,7 @@ require (
github.com/hibiken/asynq v0.26.0
github.com/jkaninda/go-utils v0.1.4
github.com/jkaninda/logger v0.0.5
- github.com/jkaninda/okapi v0.7.0
+ github.com/jkaninda/okapi v0.8.0
github.com/joho/godotenv v1.5.1
github.com/lib/pq v1.12.3
github.com/pquerna/otp v1.5.0
@@ -49,7 +49,7 @@ require (
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6 // indirect
github.com/fatih/color v1.19.0 // indirect
- github.com/getkin/kin-openapi v0.139.0 // indirect
+ github.com/getkin/kin-openapi v0.140.0 // indirect
github.com/go-jose/go-jose/v4 v4.1.4 // indirect
github.com/go-openapi/jsonpointer v0.22.5 // indirect
github.com/go-openapi/swag/jsonname v0.25.5 // indirect
@@ -63,12 +63,9 @@ require (
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
- github.com/josharian/intern v1.0.0 // indirect
- github.com/mailru/easyjson v0.9.2 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.22 // indirect
- github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/oasdiff/yaml v0.1.0 // indirect
github.com/oasdiff/yaml3 v0.0.13 // indirect
@@ -76,7 +73,6 @@ require (
github.com/olekukonko/errors v1.2.0 // indirect
github.com/olekukonko/ll v0.1.8 // indirect
github.com/olekukonko/tablewriter v1.1.4 // indirect
- github.com/perimeterx/marshmallow v1.1.5 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.67.5 // indirect
github.com/prometheus/procfs v0.20.1 // indirect
@@ -85,7 +81,6 @@ require (
github.com/spf13/pflag v1.0.10 // indirect
github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect
github.com/vanng822/css v1.0.1 // indirect
- github.com/woodsbury/decimal128 v1.4.0 // indirect
go.uber.org/atomic v1.11.0 // indirect
go.yaml.in/yaml/v2 v2.4.4 // indirect
golang.org/x/sync v0.21.0 // indirect
diff --git a/go.sum b/go.sum
index bb9757a..08d9e29 100644
--- a/go.sum
+++ b/go.sum
@@ -58,8 +58,8 @@ github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w=
github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
-github.com/getkin/kin-openapi v0.139.0 h1:pBFXcZJFwz9J1X64jzxlOoNgFm+TF7kNrs9+HJVN6Ic=
-github.com/getkin/kin-openapi v0.139.0/go.mod h1:NGxPfE4PwS/TRXEbyx2RrxDFPZvxcWw31Tw8XXjPZLs=
+github.com/getkin/kin-openapi v0.140.0 h1:JFn675aXRFjyiZKa/BFWploGldQlI0gobp4J5k0EZ2g=
+github.com/getkin/kin-openapi v0.140.0/go.mod h1:lISrB64F0CPcuDJ3LdtPTMJBY8VENjR9wJBdrcT6J3g=
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-openapi/jsonpointer v0.22.5 h1:8on/0Yp4uTb9f4XvTrM2+1CPrV05QPZXu+rvu2o9jcA=
@@ -68,8 +68,6 @@ github.com/go-openapi/swag/jsonname v0.25.5 h1:8p150i44rv/Drip4vWI3kGi9+4W9TdI3U
github.com/go-openapi/swag/jsonname v0.25.5/go.mod h1:jNqqikyiAK56uS7n8sLkdaNY/uq6+D2m2LANat09pKU=
github.com/go-openapi/testify/v2 v2.4.0 h1:8nsPrHVCWkQ4p8h1EsRVymA2XABB4OT40gcvAu+voFM=
github.com/go-openapi/testify/v2 v2.4.0/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54=
-github.com/go-test/deep v1.0.8 h1:TDsG77qcSprGbC6vTN8OuXp5g+J+b5Pcguhf7Zt61VM=
-github.com/go-test/deep v1.0.8/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE=
github.com/goccy/go-json v0.10.6 h1:p8HrPJzOakx/mn/bQtjgNjdTcN+/S6FcG2CTtQOrHVU=
github.com/goccy/go-json v0.10.6/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
@@ -103,12 +101,10 @@ github.com/jkaninda/go-utils v0.1.4 h1:ZdNlI+yLWc4/S0qKcCNQIPj+6lHSdJcGaxtRADAif
github.com/jkaninda/go-utils v0.1.4/go.mod h1:Aa54jEAcDykc3CnOdreqZG80UfSZOvrYecyusu+oPb4=
github.com/jkaninda/logger v0.0.5 h1:fTHKgDsHtuN8rkSBvwe6QStfi8yIdm8O3r0g99dRDTY=
github.com/jkaninda/logger v0.0.5/go.mod h1:ZUXJ2BdxDPG6e8t6mbKhc2ZFaFi2Iuy/4ukquFrPkFE=
-github.com/jkaninda/okapi v0.7.0 h1:O6tFFjzI4B0Aw/h3aiJMv3F+eAkP9hvIzUc1lAAHK5o=
-github.com/jkaninda/okapi v0.7.0/go.mod h1:3oisc16k4EbUCUHr3TRZ9V9DkpdLACmo4Y04uEwagG4=
+github.com/jkaninda/okapi v0.8.0 h1:Ch/ZX9CCsiXlQqv4Ebm3/soGFwbklUAnKjtJ95XvSJo=
+github.com/jkaninda/okapi v0.8.0/go.mod h1:TzBj5VE2rzr0H/6pANG2+ISbe6u46XfLzUxHu62BPv8=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
-github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
-github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
@@ -121,8 +117,6 @@ github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/lib/pq v1.12.3 h1:tTWxr2YLKwIvK90ZXEw8GP7UFHtcbTtty8zsI+YjrfQ=
github.com/lib/pq v1.12.3/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA=
-github.com/mailru/easyjson v0.9.2 h1:dX8U45hQsZpxd80nLvDGihsQ/OxlvTkVUXH2r/8cb2M=
-github.com/mailru/easyjson v0.9.2/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
@@ -131,8 +125,6 @@ github.com/mattn/go-runewidth v0.0.22 h1:76lXsPn6FyHtTY+jt2fTTvsMUCZq1k0qwRsAMux
github.com/mattn/go-runewidth v0.0.22/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
-github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw=
-github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/oasdiff/yaml v0.1.0 h1:0bqZjfKc/8S9urj4JuwepX41WX9EoA6ifhU3SV06cXg=
@@ -147,8 +139,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/perimeterx/marshmallow v1.1.5 h1:a2LALqQ1BlHM8PZblsDdidgv1mWi1DgC2UmX50IvK2s=
-github.com/perimeterx/marshmallow v1.1.5/go.mod h1:dsXbUu8CRzfYP5a87xpp0xq9S3u0Vchtcl8we9tYaXw=
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=
@@ -165,8 +155,8 @@ github.com/redis/go-redis/v9 v9.21.0 h1:FPBE4hhbAke+TLmcY3WkpbDffJEomdqPn3HYiqAt
github.com/redis/go-redis/v9 v9.21.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3baQf57KlIkA=
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
-github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
-github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
+github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
+github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 h1:KRzFb2m7YtdldCEkzs6KqmJw4nqEVZGK7IN2kJkjTuQ=
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
@@ -180,14 +170,10 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV
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/ugorji/go/codec v1.2.7 h1:YPXUKf7fYbp/y8xloBqZOw2qaVggbfwMlI8WM3wZUJ0=
-github.com/ugorji/go/codec v1.2.7/go.mod h1:WGN1fab3R1fzQlVQTkfxVtIBhWDRqOviHU95kRgeqEY=
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.34.0 h1:CW7RUnjCfXrkuCbgC2wi/Cub7IwKslJWD/OkIBlcQUk=
github.com/vanng822/go-premailer v1.34.0/go.mod h1:LGYI7ym6FQ7KcHN16LiQRF+tlan7qwhP1KEhpTINFpo=
-github.com/woodsbury/decimal128 v1.4.0 h1:xJATj7lLu4f2oObouMt2tgGiElE5gO6mSWUjQsBgUlc=
-github.com/woodsbury/decimal128 v1.4.0/go.mod h1:BP46FUrVjVhdTbKT+XuQh2xfQaGki9LMIRJSFuh6THU=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
diff --git a/internal/config/config.go b/internal/config/config.go
index 643d6b0..17c8453 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -346,7 +346,7 @@ func (c *Config) Initialize(app *okapi.Okapi) error {
}
app.WithCORS(okapi.Cors{
AllowedOrigins: corsOrigins,
- AllowedHeaders: []string{"Content-Type", "Authorization", "X-Request-ID"},
+ AllowedHeaders: []string{"Content-Type", "Authorization", "X-Request-ID", "X-Posta-Workspace-Id"},
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowCredentials: true,
})
diff --git a/internal/handlers/api_key_handler.go b/internal/handlers/api_key_handler.go
index 93b4d74..3ec00c7 100644
--- a/internal/handlers/api_key_handler.go
+++ b/internal/handlers/api_key_handler.go
@@ -48,7 +48,7 @@ type CreateAPIKeyRequest struct {
Body struct {
Name string `json:"name" required:"true"`
AllowedIPs []string `json:"allowed_ips"`
- Scopes []string `json:"scopes" enum:"send,read,webhooks,*" default:"send"`
+ Scopes []string `json:"scopes" enum:"send,read,webhooks,write,admin,*" default:"send"`
ExpiresInDays *int `json:"expires_in_days"`
} `json:"body"`
}
diff --git a/internal/handlers/oauth_handler.go b/internal/handlers/oauth_handler.go
index 7e5bac9..823e1fe 100644
--- a/internal/handlers/oauth_handler.go
+++ b/internal/handlers/oauth_handler.go
@@ -14,6 +14,7 @@ import (
"github.com/goposta/posta/internal/services/auth"
"github.com/goposta/posta/internal/services/eventbus"
"github.com/goposta/posta/internal/services/seeder"
+ sessionpkg "github.com/goposta/posta/internal/services/session"
"github.com/goposta/posta/internal/services/workspacemigrate"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/jkaninda/logger"
@@ -270,8 +271,11 @@ func (h *OAuthHandler) Callback(c *okapi.Context) error {
user.LastLoginAt = &now
_ = h.userRepo.Update(user)
- // Redirect to frontend with token
- c.Redirect(http.StatusFound, fmt.Sprintf("%s/auth/oauth/callback?token=%s", h.appWebURL, jwtToken))
+ // Hand the session to the browser as an HttpOnly cookie rather than a query
+ // parameter, so the JWT never lands in browser history or a Referer header.
+ // The SPA callback route just fetches /users/me to learn who it is.
+ sessionpkg.SetCookie(c, jwtToken, jwtTokenTTL)
+ c.Redirect(http.StatusFound, h.appWebURL+"/auth/oauth/callback")
return nil
}
@@ -345,7 +349,7 @@ func (h *OAuthHandler) generateToken(c *okapi.Context, user *models.User) (strin
"role": string(user.Role),
"aud": "posta",
"jti": jti,
- }, 24*time.Hour)
+ }, jwtTokenTTL)
if err != nil {
return "", err
}
@@ -357,7 +361,7 @@ func (h *OAuthHandler) generateToken(c *okapi.Context, user *models.User) (strin
JTI: jti,
IPAddress: c.RealIP(),
UserAgent: c.Request().UserAgent(),
- ExpiresAt: time.Now().Add(24 * time.Hour),
+ ExpiresAt: time.Now().Add(jwtTokenTTL),
}
_ = h.sessionRepo.Create(session)
}
diff --git a/internal/handlers/session_handler.go b/internal/handlers/session_handler.go
index 48dc61b..0e224c2 100644
--- a/internal/handlers/session_handler.go
+++ b/internal/handlers/session_handler.go
@@ -135,8 +135,12 @@ func (h *SessionHandler) RevokeOthers(c *okapi.Context) error {
})
}
-// Logout revokes the current session.
+// Logout revokes the current session and clears the browser session cookie.
+// Clearing the cookie unconditionally means a browser holding a token we can no
+// longer resolve still ends up logged out.
func (h *SessionHandler) Logout(c *okapi.Context) error {
+ session.ClearCookie(c)
+
currentJTI := c.GetString("jti")
if currentJTI == "" {
return ok(c, okapi.M{"message": "logged out"})
diff --git a/internal/handlers/user_handler.go b/internal/handlers/user_handler.go
index 6dd1d1c..370ee39 100644
--- a/internal/handlers/user_handler.go
+++ b/internal/handlers/user_handler.go
@@ -33,6 +33,7 @@ import (
"github.com/goposta/posta/internal/services/notification"
"github.com/goposta/posta/internal/services/passwordreset"
"github.com/goposta/posta/internal/services/seeder"
+ "github.com/goposta/posta/internal/services/session"
"github.com/goposta/posta/internal/services/settings"
"github.com/goposta/posta/internal/services/twofactor"
"github.com/goposta/posta/internal/services/workspacemigrate"
@@ -258,6 +259,7 @@ func (h *UserHandler) Register(c *okapi.Context, req *RegisterRequest) error {
if err != nil {
return c.AbortInternalServerError("failed to generate token", err)
}
+ session.SetCookie(c, token, jwtTokenTTL)
return created(c, AuthResponse{
Token: token,
@@ -508,11 +510,14 @@ func (h *UserHandler) Login(c *okapi.Context, req *LoginRequest) error {
ua := c.Header("User-Agent")
newDevice := h.isNewDevice(user.ID, ua)
- token, jti, err := h.generateTokenWithSession(c, user)
+ token, _, err := h.generateTokenWithSession(c, user)
if err != nil {
return c.AbortInternalServerError("failed to generate token", err)
}
- _ = jti
+
+ // Browser clients ride the HttpOnly cookie; the body's token remains for
+ // CLI/SDK clients, which send it back as a Bearer header.
+ session.SetCookie(c, token, jwtTokenTTL)
if newDevice {
h.sendLoginAlert(user.ID, ua, c.RealIP())
diff --git a/internal/middlewares/authenticate_test.go b/internal/middlewares/authenticate_test.go
new file mode 100644
index 0000000..46b87fd
--- /dev/null
+++ b/internal/middlewares/authenticate_test.go
@@ -0,0 +1,229 @@
+/*
+ * 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 middlewares
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/goposta/posta/internal/config"
+ "github.com/jkaninda/okapi"
+)
+
+const testSecret = "test-secret-value"
+
+func testJWT(t *testing.T, role string) string {
+ t.Helper()
+ tok, err := okapi.GenerateJwtToken([]byte(testSecret), map[string]any{
+ "sub": 1,
+ "email": "[email protected]",
+ "role": role,
+ "aud": "posta",
+ "jti": "jti-1",
+ }, time.Hour)
+ if err != nil {
+ t.Fatalf("GenerateJwtToken: %v", err)
+ }
+ return tok
+}
+
+// jwtOnlyServer mounts Authenticate with nil API-key collaborators. That is safe
+// precisely because a credential without the psk_ prefix must never reach the
+// API-key path — if it did, these tests would panic rather than quietly pass.
+func jwtOnlyServer(t *testing.T) *okapi.TestServer {
+ t.Helper()
+ cfg := &config.Config{JWTSecret: testSecret}
+ o := okapi.NewTestServer(t)
+ o.Get("/protected", func(c *okapi.Context) error {
+ return c.String(http.StatusOK, c.GetString(CtxAuthMethod))
+ }).Use(Authenticate(JWTAuth(cfg), nil, nil, nil))
+ return o
+}
+
+func TestAuthenticate_JWT(t *testing.T) {
+ token := testJWT(t, "user")
+
+ cases := []struct {
+ name string
+ apply func(*http.Request)
+ wantStatus int
+ }{
+ {
+ name: "authorization header",
+ apply: func(r *http.Request) { r.Header.Set("Authorization", "Bearer "+token) },
+ wantStatus: http.StatusOK,
+ },
+ {
+ name: "session cookie",
+ apply: func(r *http.Request) { r.AddCookie(&http.Cookie{Name: SessionCookieName, Value: token}) },
+ wantStatus: http.StatusOK,
+ },
+ {
+ name: "no credential",
+ apply: func(*http.Request) {},
+ wantStatus: http.StatusUnauthorized,
+ },
+ {
+ name: "garbage bearer token",
+ apply: func(r *http.Request) { r.Header.Set("Authorization", "Bearer not-a-jwt") },
+ wantStatus: http.StatusUnauthorized,
+ },
+ {
+ // The whole point of dropping query:token — a JWT in the URL must not
+ // authenticate, even though it is otherwise a perfectly valid token.
+ name: "valid jwt in query is refused",
+ apply: func(r *http.Request) { r.URL.RawQuery = "token=" + token },
+ wantStatus: http.StatusUnauthorized,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ o := jwtOnlyServer(t)
+ req := httptest.NewRequest(http.MethodGet, "/protected", nil)
+ tc.apply(req)
+ rec := httptest.NewRecorder()
+ o.ServeHTTP(rec, req)
+
+ if rec.Code != tc.wantStatus {
+ t.Fatalf("status = %d, want %d (body %s)", rec.Code, tc.wantStatus, rec.Body.String())
+ }
+ if tc.wantStatus == http.StatusOK && rec.Body.String() != AuthMethodJWT {
+ t.Errorf("auth_method = %q, want %q", rec.Body.String(), AuthMethodJWT)
+ }
+ })
+ }
+}
+
+// An expired or revoked cookie must not fall through to "authentication
+// required" — it has to be rejected as an invalid session.
+func TestAuthenticate_RejectsExpiredCookie(t *testing.T) {
+ expired, err := okapi.GenerateJwtToken([]byte(testSecret), map[string]any{
+ "sub": 1, "aud": "posta", "jti": "jti-1",
+ }, -time.Hour)
+ if err != nil {
+ t.Fatalf("GenerateJwtToken: %v", err)
+ }
+
+ o := jwtOnlyServer(t)
+ req := httptest.NewRequest(http.MethodGet, "/protected", nil)
+ req.AddCookie(&http.Cookie{Name: SessionCookieName, Value: expired})
+ rec := httptest.NewRecorder()
+ o.ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusUnauthorized {
+ t.Errorf("status = %d, want 401", rec.Code)
+ }
+}
+
+// A token with no jti cannot be checked against the revocation list, so it is
+// not a usable session. It must read as unauthenticated (401), not as a
+// permissions problem (403) — okapi's default for a ValidateClaims failure.
+func TestAuthenticate_RejectsTokenWithoutJTI(t *testing.T) {
+ noJTI, err := okapi.GenerateJwtToken([]byte(testSecret), map[string]any{
+ "sub": 1, "aud": "posta", "role": "user",
+ }, time.Hour)
+ if err != nil {
+ t.Fatalf("GenerateJwtToken: %v", err)
+ }
+
+ o := jwtOnlyServer(t)
+ req := httptest.NewRequest(http.MethodGet, "/protected", nil)
+ req.AddCookie(&http.Cookie{Name: SessionCookieName, Value: noJTI})
+ rec := httptest.NewRecorder()
+ o.ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusUnauthorized {
+ t.Errorf("status = %d, want 401", rec.Code)
+ }
+}
+
+// A psk_ credential must never be parsed as a JWT, wherever it arrives. With nil
+// API-key collaborators the API-key path panics, which is what we assert: it
+// proves dispatch reached that branch rather than silently 401ing as a bad JWT.
+func TestAuthenticate_RoutesAPIKeyPrefixToKeyPath(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ apply func(*http.Request)
+ }{
+ {"header", func(r *http.Request) { r.Header.Set("Authorization", "Bearer psk_deadbeef") }},
+ {"bare header", func(r *http.Request) { r.Header.Set("Authorization", "psk_deadbeef") }},
+ {"query", func(r *http.Request) { r.URL.RawQuery = "token=psk_deadbeef" }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ defer func() {
+ if recover() == nil {
+ t.Error("psk_ credential did not reach the API-key path")
+ }
+ }()
+
+ cfg := &config.Config{JWTSecret: testSecret}
+ mw := Authenticate(JWTAuth(cfg), nil, nil, nil)
+ req := httptest.NewRequest(http.MethodGet, "/protected", nil)
+ tc.apply(req)
+
+ o := okapi.NewTestServer(t)
+ c := okapi.NewContext(o.Okapi, httptest.NewRecorder(), req)
+ _ = mw(c)
+ })
+ }
+}
+
+// A JWT is not an admin credential unless its role claim says so.
+func TestJWTAdminAuth_RejectsNonAdmin(t *testing.T) {
+ cfg := &config.Config{JWTSecret: testSecret}
+
+ for _, tc := range []struct {
+ role string
+ wantStatus int
+ }{
+ {"admin", http.StatusOK},
+ {"user", http.StatusForbidden},
+ } {
+ t.Run(tc.role, func(t *testing.T) {
+ adminAuth := JWTAdminAuth(cfg)
+ o := okapi.NewTestServer(t)
+ o.Get("/admin", func(c *okapi.Context) error {
+ return c.String(http.StatusOK, "ok")
+ }).Use(adminAuth.Middleware)
+
+ req := httptest.NewRequest(http.MethodGet, "/admin", nil)
+ req.AddCookie(&http.Cookie{Name: SessionCookieName, Value: testJWT(t, tc.role)})
+ rec := httptest.NewRecorder()
+ o.ServeHTTP(rec, req)
+
+ if rec.Code != tc.wantStatus {
+ t.Errorf("role %q: status = %d, want %d", tc.role, rec.Code, tc.wantStatus)
+ }
+ })
+ }
+}
+
+// The lookup order and contents are load-bearing: header for CLI/SDK, cookie for
+// the browser, and no query source at all.
+func TestTokenLookup(t *testing.T) {
+ if want := "header:Authorization,cookie:posta_session"; tokenLookup != want {
+ t.Errorf("tokenLookup = %q, want %q", tokenLookup, want)
+ }
+ if strings.Contains(tokenLookup, "query") {
+ t.Error("a user JWT must never be accepted from the query string")
+ }
+}
diff --git a/internal/middlewares/middleware.go b/internal/middlewares/middleware.go
index 773868f..203107c 100644
--- a/internal/middlewares/middleware.go
+++ b/internal/middlewares/middleware.go
@@ -15,11 +15,24 @@
*
*/
+// Package middlewares holds HTTP middleware: authentication, workspace scoping,
+// and role-based access control.
+//
+// Two credentials reach the API:
+//
+// - A user JWT, presented by the dashboard as an HttpOnly session cookie or by
+// CLI/SDK clients as `Authorization: Bearer <jwt>`.
+// - An API key (psk_…), presented as `Authorization: Bearer psk_…` or, for
+// browser-direct streams that cannot set headers, as `?token=psk_…`.
+//
+// Authenticate accepts either. APIKeyAuth accepts only the latter, and the
+// admin JWT middleware only the former.
package middlewares
import (
"errors"
"net"
+ "net/http"
"strings"
"github.com/golang-jwt/jwt/v5"
@@ -33,99 +46,324 @@ import (
"github.com/jkaninda/okapi"
)
-const sessionRevokedKey = "session_revoked"
+// Context keys populated by these middlewares.
+const (
+ CtxUserID = "user_id"
+ CtxUserEmail = "user_email"
+ // CtxUserRole is the platform role ("admin" | "user"). For JWT callers okapi
+ // forwards it from the token; for API-key callers it is read from the owner.
+ CtxUserRole = "role"
+ CtxJTI = "jti"
+ // CtxAuthMethod records how the request authenticated, so downstream
+ // middleware (notably RequireScope) can tell a session from a machine key.
+ CtxAuthMethod = "auth_method"
+ CtxWorkspaceID = "workspace_id"
+ CtxWorkspaceRole = "workspace_role"
+ CtxAPIKeyID = "api_key_id"
+ CtxAPIKeyScopes = "api_key_scopes"
+ // CtxAPIKeyWorkspaceID holds the workspace an API key is bound to, when the
+ // presented key is workspace-scoped (absent for account-wide keys).
+ CtxAPIKeyWorkspaceID = "api_key_workspace_id"
+)
+
+// Values stored under CtxAuthMethod.
+const (
+ AuthMethodJWT = "jwt"
+ AuthMethodAPIKey = "api_key"
+)
+
+// SessionCookieName re-exports the browser session cookie name, so route and
+// middleware code need not reach into the session package for it.
+const SessionCookieName = sessionpkg.CookieName
+
+// tokenLookup resolves the JWT from the Authorization header (CLI, SDKs) and
+// then the browser session cookie. It deliberately omits `query:token`: browsers
+// send cookies on EventSource handshakes and CLIs set the header, so a user JWT
+// never has to travel in a URL — where it would land in proxy logs, browser
+// history, and Referer headers.
+const tokenLookup = "header:Authorization,cookie:" + SessionCookieName
+
+// ctxRejection records why claim validation failed, so OnUnauthorized can answer
+// with the right status. okapi routes every failure — a missing token, an expired
+// one, and a valid token whose claims fall short — through that single hook, so
+// without this marker "you are not an admin" would be indistinguishable from "you
+// are not logged in", and the dashboard would sign the user out on a 403.
+const ctxRejection = "auth_rejection"
+
+const (
+ rejectionRevoked = "revoked"
+ rejectionForbidden = "forbidden"
+)
-func baseJWTAuth(cfg *config.Config) okapi.JWTAuth {
- return okapi.JWTAuth{
+func baseJWTAuth(cfg *config.Config, store *sessionpkg.Store, requireAdmin bool) okapi.JWTAuth {
+ a := okapi.JWTAuth{
SigningSecret: []byte(cfg.JWTSecret),
Audience: "posta",
ContextKey: "jwt_user",
+ TokenLookup: tokenLookup,
ForwardClaims: map[string]string{
- "user_id": "sub",
- "email": "email",
- "role": "role",
- "jti": "jti",
+ CtxUserID: "sub",
+ "email": "email",
+ CtxUserRole: "role",
+ CtxJTI: "jti",
},
+ // Deliberately not ClaimsExpression: okapi evaluates it before
+ // ValidateClaims, which would deny us the chance to tag the rejection.
+ ValidateClaims: validateClaims(store, requireAdmin),
+ }
+ a.OnUnauthorized = func(c *okapi.Context) error {
+ switch c.GetString(ctxRejection) {
+ case rejectionForbidden:
+ return c.AbortForbidden("insufficient permissions")
+ case rejectionRevoked:
+ return c.AbortUnauthorized("session has been revoked")
+ default:
+ return c.AbortUnauthorized("invalid or expired session")
+ }
}
+ return a
}
-// sessionValidator returns a ValidateClaims function that checks the Redis blacklist.
-func sessionValidator(store *sessionpkg.Store) func(c *okapi.Context, claims jwt.Claims) error {
+// validateClaims runs only once okapi has accepted the token's signature and
+// expiry, so reaching it means the caller holds a genuine session.
+func validateClaims(store *sessionpkg.Store, requireAdmin bool) func(c *okapi.Context, claims jwt.Claims) error {
return func(c *okapi.Context, claims jwt.Claims) error {
mapClaims, ok := claims.(jwt.MapClaims)
if !ok {
- return nil // no claims to check
+ return errors.New("invalid token: unexpected claims")
}
+
jti, _ := mapClaims["jti"].(string)
if jti == "" {
- return errors.New("invalid token, missing jti")
+ return errors.New("invalid token: missing jti")
}
- if store.IsRevoked(c.Request().Context(), jti) {
- c.Set(sessionRevokedKey, true)
+ if store != nil && store.IsRevoked(c.Request().Context(), jti) {
+ c.Set(ctxRejection, rejectionRevoked)
return errors.New("session has been revoked")
}
+
+ if requireAdmin {
+ if role, _ := mapClaims["role"].(string); role != string(models.UserRoleAdmin) {
+ c.Set(ctxRejection, rejectionForbidden)
+ return errors.New("admin role required")
+ }
+ }
return nil
}
}
-// func sessionAwareUnauthorized(c *okapi.Context) error {
-// if c.GetBool(sessionRevokedKey) {
-// return c.AbortUnauthorized("session has been revoked")
-// }
-// return c.AbortForbidden("Insufficient permissions")
-// }
-
-// JWTAuth creates user JWT auth middleware. If sessionStore is non-nil, revoked sessions are rejected.
+// JWTAuth builds user JWT auth (Authorization header or session cookie).
+// Revoked sessions are rejected when sessionStore is provided.
func JWTAuth(cfg *config.Config, sessionStore ...*sessionpkg.Store) okapi.JWTAuth {
- auth := baseJWTAuth(cfg)
- if len(sessionStore) > 0 && sessionStore[0] != nil {
- auth.ValidateClaims = sessionValidator(sessionStore[0])
- // auth.OnUnauthorized = sessionAwareUnauthorized
- }
- return auth
+ return baseJWTAuth(cfg, firstStore(sessionStore), false)
}
-// JWTAdminAuth creates admin JWT auth middleware.
+// JWTAdminAuth builds admin-only JWT auth. An API key is never an admin
+// credential: a psk_ token presented here fails JWT parsing and is rejected.
func JWTAdminAuth(cfg *config.Config, sessionStore ...*sessionpkg.Store) okapi.JWTAuth {
- auth := baseJWTAuth(cfg)
- auth.ClaimsExpression = "Equals(`role`,`admin`)"
- if len(sessionStore) > 0 && sessionStore[0] != nil {
- auth.ValidateClaims = sessionValidator(sessionStore[0])
- // auth.OnUnauthorized = sessionAwareUnauthorized
+ return baseJWTAuth(cfg, firstStore(sessionStore), true)
+}
+
+func firstStore(stores []*sessionpkg.Store) *sessionpkg.Store {
+ if len(stores) > 0 {
+ return stores[0]
+ }
+ return nil
+}
+
+// Authenticate accepts either a user JWT or an API key.
+//
+// API keys (psk_…) are read from the Authorization header or the `?token=` query
+// param — the latter so browser-direct streams (EventSource, download links) and
+// machine clients can authenticate without headers. Any other credential is
+// treated as a JWT and resolved by okapi from the header or the session cookie.
+func Authenticate(jwtAuth okapi.JWTAuth, keyService *auth.APIKeyService, userRepo *repositories.UserRepository, keyRepo *repositories.APIKeyRepository) okapi.Middleware {
+ return func(c *okapi.Context) error {
+ raw := bearerToken(c)
+ if raw == "" {
+ raw = strings.TrimSpace(c.Query("token"))
+ }
+ if strings.HasPrefix(raw, auth.APIKeyPrefix) {
+ return authenticateAPIKey(c, keyService, userRepo, keyRepo, raw)
+ }
+ if raw == "" {
+ // A browser presents the JWT only as an HttpOnly cookie, which never
+ // shows up in the header or query. Let okapi read it via TokenLookup.
+ if _, err := c.Cookie(SessionCookieName); err != nil {
+ return c.AbortUnauthorized("authentication required")
+ }
+ }
+ c.Set(CtxAuthMethod, AuthMethodJWT)
+ return jwtAuth.Middleware(c)
+ }
+}
+
+// APIKeyAuth accepts only an API key, and only from the Authorization header. It
+// guards the public machine-facing API (/api/v1/emails/*, /webhooks, …), where a
+// browser session is not a valid credential and no caller needs the key in a URL.
+func APIKeyAuth(keyService *auth.APIKeyService, userRepo *repositories.UserRepository, keyRepo *repositories.APIKeyRepository) okapi.Middleware {
+ return func(c *okapi.Context) error {
+ raw := bearerToken(c)
+ if raw == "" {
+ return c.AbortUnauthorized("missing Authorization header")
+ }
+ if !strings.HasPrefix(raw, auth.APIKeyPrefix) {
+ return c.AbortUnauthorized("invalid Authorization format, expected: Bearer <API_KEY>")
+ }
+ return authenticateAPIKey(c, keyService, userRepo, keyRepo, raw)
+ }
+}
+
+// bearerToken returns the Authorization header's token, stripping an optional
+// `Bearer ` prefix so a bare `Authorization: psk_…` still works.
+func bearerToken(c *okapi.Context) string {
+ return strings.TrimSpace(strings.TrimPrefix(c.Header("Authorization"), "Bearer "))
+}
+
+func authenticateAPIKey(c *okapi.Context, keyService *auth.APIKeyService, userRepo *repositories.UserRepository, keyRepo *repositories.APIKeyRepository, rawKey string) error {
+ apiKey, err := keyService.ValidateKey(rawKey)
+ if err != nil {
+ return c.AbortUnauthorized("invalid API key")
+ }
+
+ user, err := userRepo.FindByID(apiKey.UserID)
+ if err != nil {
+ return c.AbortUnauthorized("invalid API key")
+ }
+ if !user.Active {
+ return c.AbortForbidden("account is disabled")
+ }
+ if !ipAllowed(apiKey.AllowedIPs, c.RealIP()) {
+ return c.AbortForbidden("IP address not allowed for this API key")
+ }
+
+ scopes := []string(apiKey.Scopes)
+ if len(scopes) == 0 {
+ scopes = []string{models.ScopeSend}
+ }
+
+ c.Set(CtxUserID, int(apiKey.UserID))
+ c.Set(CtxUserEmail, user.Email)
+ c.Set(CtxUserRole, string(user.Role))
+ c.Set(CtxAuthMethod, AuthMethodAPIKey)
+ c.Set(CtxAPIKeyID, int(apiKey.ID))
+ c.Set(CtxAPIKeyScopes, strings.Join(scopes, ","))
+ if apiKey.WorkspaceID != nil {
+ // Tenant resolution proper happens in the workspace middleware; this is
+ // the binding it reads, and what the legacy API-key routes rely on.
+ c.Set(CtxWorkspaceID, int(*apiKey.WorkspaceID))
+ c.Set(CtxAPIKeyWorkspaceID, int(*apiKey.WorkspaceID))
+ }
+
+ if keyRepo != nil {
+ go func() { _ = keyRepo.UpdateLastUsed(apiKey.ID) }()
+ }
+
+ return c.Next()
+}
+
+// ipAllowed reports whether clientIP is permitted by an API key's allowlist. An
+// empty allowlist permits any IP; entries may be exact IPs or CIDR ranges.
+func ipAllowed(allowed []string, clientIP string) bool {
+ if len(allowed) == 0 {
+ return true
}
- return auth
+ ip := net.ParseIP(clientIP)
+ for _, a := range allowed {
+ if a == clientIP {
+ return true
+ }
+ if strings.Contains(a, "/") {
+ if _, network, err := net.ParseCIDR(a); err == nil && ip != nil && network.Contains(ip) {
+ return true
+ }
+ }
+ }
+ return false
}
-// JWTAdminQueryAuth creates admin JWT auth via query param (for SSE).
-func JWTAdminQueryAuth(cfg *config.Config, sessionStore ...*sessionpkg.Store) okapi.JWTAuth {
- auth := baseJWTAuth(cfg)
- auth.ClaimsExpression = "Equals(`role`,`admin`)"
- auth.TokenLookup = "query:token"
- if len(sessionStore) > 0 && sessionStore[0] != nil {
- auth.ValidateClaims = sessionValidator(sessionStore[0])
- // auth.OnUnauthorized = sessionAwareUnauthorized
+// hasScope reports whether the resolved API key grants scope ("*" grants all).
+func hasScope(c *okapi.Context, scope string) bool {
+ for _, s := range strings.Split(c.GetString(CtxAPIKeyScopes), ",") {
+ if s == models.ScopeAll || s == scope {
+ return true
+ }
}
- return auth
+ return false
+}
+
+// tenantAdminPaths are workspace path segments whose routes administer the
+// tenant itself — credentials, membership, billing, and configuration — rather
+// than its content. They demand ScopeAdmin whatever the method, so a key that
+// can manage templates cannot also mint credentials or invite members.
+var tenantAdminPaths = []string{
+ "/api-keys",
+ "/members",
+ "/invitations",
+ "/settings",
+ "/sso",
+ "/plan",
}
-// JWTQueryAuth creates user JWT auth via query param (for SSE endpoints —
-// browsers cannot attach Authorization headers to EventSource connections).
-func JWTQueryAuth(cfg *config.Config, sessionStore ...*sessionpkg.Store) okapi.JWTAuth {
- auth := baseJWTAuth(cfg)
- auth.TokenLookup = "query:token"
- if len(sessionStore) > 0 && sessionStore[0] != nil {
- auth.ValidateClaims = sessionValidator(sessionStore[0])
+// workspaceScopeFor returns the scope a workspace-scoped request demands.
+// Reads need `read`, mutations need `write`, and tenant administration needs
+// `admin`. Note that `send` grants none of these: sending lives on the public
+// API (/api/v1/emails/*), so a send-only key is confined to it and cannot read
+// or modify workspace resources.
+func workspaceScopeFor(method, path string) string {
+ for _, p := range tenantAdminPaths {
+ if strings.Contains(path, p) {
+ return models.ScopeAdmin
+ }
+ }
+ switch method {
+ case http.MethodGet, http.MethodHead, http.MethodOptions:
+ return models.ScopeRead
+ default:
+ return models.ScopeWrite
+ }
+}
+
+// requireWorkspaceScope enforces workspaceScopeFor on API-key callers. Session
+// callers pass through — their access is governed by workspace RBAC instead.
+//
+// This runs inside workspace resolution rather than as a route-group middleware
+// so that it cannot be forgotten: any route that resolves a workspace is scope
+// checked by construction, and a new group cannot silently fail open.
+func requireWorkspaceScope(c *okapi.Context) error {
+ if c.GetString(CtxAuthMethod) != AuthMethodAPIKey {
+ return nil
+ }
+ required := workspaceScopeFor(c.Request().Method, c.Request().URL.Path)
+ if hasScope(c, required) {
+ return nil
+ }
+ return c.AbortForbidden("API key missing required scope: " + required)
+}
+
+// RequireScope guards a route for API-key callers, demanding the presented key
+// carry the given scope (or "*"). Session/JWT callers pass through — their access
+// is governed by workspace RBAC instead.
+func RequireScope(scope string) okapi.Middleware {
+ return func(c *okapi.Context) error {
+ if c.GetString(CtxAuthMethod) != AuthMethodAPIKey {
+ return c.Next()
+ }
+ if hasScope(c, scope) {
+ return c.Next()
+ }
+ return c.AbortForbidden("API key missing required scope: " + scope)
}
- return auth
}
// RequireVerifiedEmail blocks actions that are risky when the caller's email
+// address has not been confirmed.
func RequireVerifiedEmail(verifier *emailverify.Service, userRepo *repositories.UserRepository) okapi.Middleware {
return func(c *okapi.Context) error {
if verifier == nil || !verifier.Required() {
return c.Next()
}
- userID := c.GetInt("user_id")
+ userID := c.GetInt(CtxUserID)
if userID == 0 {
return c.Next()
}
@@ -143,94 +381,40 @@ func RequireVerifiedEmail(verifier *emailverify.Service, userRepo *repositories.
// LoginRateLimitMiddleware limits login attempts per IP address using Redis.
func LoginRateLimitMiddleware(limiter *ratelimit.RedisLimiter) okapi.Middleware {
return func(c *okapi.Context) error {
- ip := c.RealIP()
- if err := limiter.AllowLogin(c.Request().Context(), ip); err != nil {
+ if err := limiter.AllowLogin(c.Request().Context(), c.RealIP()); err != nil {
return c.AbortTooManyRequests(err.Error())
}
return c.Next()
-
}
}
-// APIKeyAuthMiddleware validates API key from Authorization header and sets user context.
-func APIKeyAuthMiddleware(keyService *auth.APIKeyService, userRepo *repositories.UserRepository, keyRepo *repositories.APIKeyRepository) okapi.Middleware {
- return func(c *okapi.Context) error {
- authHeader := c.Header("Authorization")
- if authHeader == "" {
- return c.AbortUnauthorized("missing Authorization header")
- }
-
- rawKey := strings.TrimPrefix(authHeader, "Bearer ")
- if rawKey == authHeader {
- return c.AbortUnauthorized("invalid Authorization format, expected: Bearer <API_KEY>")
- }
+// UserID returns the authenticated user id (0 if absent).
+func UserID(c *okapi.Context) uint { return uint(c.GetInt(CtxUserID)) }
- apiKey, err := keyService.ValidateKey(rawKey)
- if err != nil {
- return c.AbortUnauthorized(err.Error())
- }
+// AuthMethod returns how the request authenticated ("jwt" | "api_key" | "").
+func AuthMethod(c *okapi.Context) string { return c.GetString(CtxAuthMethod) }
- user, err := userRepo.FindByID(apiKey.UserID)
- if err != nil {
- return c.AbortUnauthorized("user not found")
- }
+// IsAPIKey reports whether the caller authenticated with an API key.
+func IsAPIKey(c *okapi.Context) bool { return AuthMethod(c) == AuthMethodAPIKey }
- if !user.Active {
- return c.AbortForbidden("account is disabled")
- }
-
- // Check IP allowlist
- if len(apiKey.AllowedIPs) > 0 {
- clientIP := c.RealIP()
- allowed := false
- for _, ip := range apiKey.AllowedIPs {
- if ip == clientIP {
- allowed = true
- break
- }
- // Support CIDR notation
- if strings.Contains(ip, "/") {
- _, network, err := net.ParseCIDR(ip)
- if err == nil && network.Contains(net.ParseIP(clientIP)) {
- allowed = true
- break
- }
- }
- }
- if !allowed {
- return c.AbortForbidden("IP address not allowed for this API key")
- }
- }
-
- c.Set("user_id", int(apiKey.UserID))
- c.Set("api_key_id", int(apiKey.ID))
- c.Set("user_email", user.Email)
- if apiKey.WorkspaceID != nil {
- c.Set("workspace_id", int(*apiKey.WorkspaceID))
- }
-
- scopes := []string(apiKey.Scopes)
- if len(scopes) == 0 {
- scopes = []string{models.ScopeSend}
- }
- c.Set("api_key_scopes", strings.Join(scopes, ","))
-
- go func() { _ = keyRepo.UpdateLastUsed(apiKey.ID) }()
-
- return c.Next()
+// APIKeyID returns the presented API key's id (0 for session/JWT callers).
+func APIKeyID(c *okapi.Context) uint { return uint(c.GetInt(CtxAPIKeyID)) }
+// APIKeyWorkspaceID returns the workspace an API key is bound to, or nil for an
+// account-wide key or a non-API-key caller.
+func APIKeyWorkspaceID(c *okapi.Context) *uint {
+ if id := c.GetInt(CtxAPIKeyWorkspaceID); id > 0 {
+ v := uint(id)
+ return &v
}
+ return nil
}
-// RequireScope aborts 403 unless the authenticated API key grants scope (or "*").
-func RequireScope(scope string) okapi.Middleware {
- return func(c *okapi.Context) error {
- raw := c.GetString("api_key_scopes")
- for _, s := range strings.Split(raw, ",") {
- if s == models.ScopeAll || s == scope {
- return c.Next()
- }
- }
- return c.AbortForbidden("API key missing required scope: " + scope)
+// APIKeyScopes returns the presented key's scopes (nil for session/JWT callers).
+func APIKeyScopes(c *okapi.Context) []string {
+ raw := c.GetString(CtxAPIKeyScopes)
+ if raw == "" {
+ return nil
}
+ return strings.Split(raw, ",")
}
diff --git a/internal/middlewares/scope_test.go b/internal/middlewares/scope_test.go
index 3640787..d9acea1 100644
--- a/internal/middlewares/scope_test.go
+++ b/internal/middlewares/scope_test.go
@@ -26,10 +26,11 @@ import (
"github.com/jkaninda/okapi"
)
-// stashScopes mimics APIKeyAuthMiddleware setting the key's scopes on context.
-func stashScopes(raw string) okapi.Middleware {
+// stashAuth mimics authenticateAPIKey populating the auth context.
+func stashAuth(method, scopes string) okapi.Middleware {
return func(c *okapi.Context) error {
- c.Set("api_key_scopes", raw)
+ c.Set(CtxAuthMethod, method)
+ c.Set(CtxAPIKeyScopes, scopes)
return c.Next()
}
}
@@ -37,31 +38,41 @@ func stashScopes(raw string) okapi.Middleware {
func TestRequireScope(t *testing.T) {
cases := []struct {
name string
+ authMethod string
keyScopes string
required string
wantStatus int
}{
- {"exact match allowed", "read", models.ScopeRead, http.StatusOK},
- {"wildcard allowed", "*", models.ScopeWebhooks, http.StatusOK},
- {"one of many allowed", "send,read", models.ScopeRead, http.StatusOK},
- {"missing scope forbidden", "send", models.ScopeRead, http.StatusForbidden},
- {"empty scopes forbidden for read", "", models.ScopeRead, http.StatusForbidden},
- {"send-only forbidden for webhooks", "send", models.ScopeWebhooks, http.StatusForbidden},
+ {"exact match allowed", AuthMethodAPIKey, "read", models.ScopeRead, http.StatusOK},
+ {"wildcard allowed", AuthMethodAPIKey, "*", models.ScopeWebhooks, http.StatusOK},
+ {"one of many allowed", AuthMethodAPIKey, "send,read", models.ScopeRead, http.StatusOK},
+ {"missing scope forbidden", AuthMethodAPIKey, "send", models.ScopeRead, http.StatusForbidden},
+ {"empty scopes forbidden for read", AuthMethodAPIKey, "", models.ScopeRead, http.StatusForbidden},
+ {"send-only forbidden for webhooks", AuthMethodAPIKey, "send", models.ScopeWebhooks, http.StatusForbidden},
+
+ // Scopes describe API keys only. A dashboard session carries none, and is
+ // governed by workspace RBAC instead, so RequireScope must let it through.
+ {"jwt session bypasses scopes", AuthMethodJWT, "", models.ScopeWebhooks, http.StatusOK},
+
+ // write and admin are ordinary workspace scopes: the wildcard covers them.
+ {"wildcard grants admin", AuthMethodAPIKey, "*", models.ScopeAdmin, http.StatusOK},
+ {"explicit admin scope allowed", AuthMethodAPIKey, "admin", models.ScopeAdmin, http.StatusOK},
+ {"read-only denied write", AuthMethodAPIKey, "read", models.ScopeWrite, http.StatusForbidden},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
o := okapi.NewTestServer(t)
o.Get("/guarded", func(c *okapi.Context) error {
return c.String(http.StatusOK, "ok")
- }).Use(stashScopes(tc.keyScopes), RequireScope(tc.required))
+ }).Use(stashAuth(tc.authMethod, tc.keyScopes), RequireScope(tc.required))
req := httptest.NewRequest(http.MethodGet, "/guarded", nil)
rec := httptest.NewRecorder()
o.ServeHTTP(rec, req)
if rec.Code != tc.wantStatus {
- t.Errorf("scopes=%q require=%q: status = %d, want %d",
- tc.keyScopes, tc.required, rec.Code, tc.wantStatus)
+ t.Errorf("auth=%s scopes=%q require=%q: status = %d, want %d",
+ tc.authMethod, tc.keyScopes, tc.required, rec.Code, tc.wantStatus)
}
})
}
diff --git a/internal/middlewares/workspace.go b/internal/middlewares/workspace.go
index be98a03..1dfcbf4 100644
--- a/internal/middlewares/workspace.go
+++ b/internal/middlewares/workspace.go
@@ -25,120 +25,115 @@ import (
"github.com/jkaninda/okapi"
)
-func OptionalWorkspaceMiddleware(workspaceRepo *repositories.WorkspaceRepository, userRepo *repositories.UserRepository) okapi.Middleware {
- return func(c *okapi.Context) error {
- wsHeader := c.Header("X-Posta-Workspace-Id")
- if wsHeader == "" {
- if c.GetInt("workspace_id") > 0 {
- return c.Next()
- }
- userID := c.GetInt("user_id")
- if userID == 0 || userRepo == nil {
- return c.Next()
+// WorkspaceHeader names the header carrying the active workspace. Browser-direct
+// requests (EventSource, download links) cannot set headers, so the
+// query-tolerant middleware also accepts `?workspace_id=`.
+const WorkspaceHeader = "X-Posta-Workspace-Id"
+
+// resolveWorkspace establishes the request's workspace and the caller's role in
+// it, given the raw workspace id the caller asked for ("" when unspecified).
+//
+// Three callers, three sources of authority:
+//
+// - A workspace-bound API key IS the workspace. It gets owner-equivalent
+// access to it and cannot reach any other workspace, whatever it asks for.
+// - An account-wide API key, and any JWT session, must prove membership of the
+// workspace they name, and inherit that membership's role.
+// - When nobody names a workspace and `required` is false, we fall back to the
+// user's personal workspace.
+//
+// Membership answers "which workspace?", never "how much of it?". An API key's
+// scopes answer the latter, and are enforced here for every workspace-scoped
+// route — see requireWorkspaceScope.
+func resolveWorkspace(c *okapi.Context, workspaceRepo *repositories.WorkspaceRepository, userRepo *repositories.UserRepository, raw string, required bool) error {
+ userID := c.GetInt(CtxUserID)
+ if userID == 0 {
+ return c.AbortUnauthorized("authentication required")
+ }
+
+ // Checked before the workspace is resolved, so an under-scoped key is refused
+ // without learning whether the workspace it named exists.
+ if err := requireWorkspaceScope(c); err != nil {
+ return err
+ }
+
+ if bound := APIKeyWorkspaceID(c); bound != nil {
+ if raw != "" {
+ wsID, err := strconv.Atoi(raw)
+ if err != nil || wsID <= 0 {
+ return c.AbortBadRequest("invalid workspace id")
}
- personalID, err := userRepo.PersonalWorkspaceID(uint(userID))
- if err != nil || personalID == nil {
- // Not migrated yet — legacy personal mode.
- return c.Next()
+ if uint(wsID) != *bound {
+ return c.AbortForbidden("API key is not bound to this workspace")
}
- c.Set("workspace_id", int(*personalID))
- c.Set("workspace_role", string(models.WorkspaceRoleOwner))
- return c.Next()
- }
-
- userID := c.GetInt("user_id")
- if userID == 0 {
- return c.AbortUnauthorized("authentication required")
}
+ c.Set(CtxWorkspaceID, int(*bound))
+ c.Set(CtxWorkspaceRole, string(models.WorkspaceRoleOwner))
+ return c.Next()
+ }
- wsID, err := strconv.Atoi(wsHeader)
+ if raw != "" {
+ wsID, err := strconv.Atoi(raw)
if err != nil || wsID <= 0 {
- return c.AbortBadRequest("invalid X-Posta-Workspace-Id")
+ return c.AbortBadRequest("invalid workspace id")
}
-
member, err := workspaceRepo.FindMember(uint(wsID), uint(userID))
if err != nil {
return c.AbortForbidden("you are not a member of this workspace")
}
-
- c.Set("workspace_id", wsID)
- c.Set("workspace_role", string(member.Role))
-
+ c.Set(CtxWorkspaceID, wsID)
+ c.Set(CtxWorkspaceRole, string(member.Role))
return c.Next()
}
-}
-
-func WorkspaceFromQueryOrHeader(workspaceRepo *repositories.WorkspaceRepository, userRepo *repositories.UserRepository) okapi.Middleware {
- return func(c *okapi.Context) error {
- userID := c.GetInt("user_id")
- if userID == 0 {
- return c.AbortUnauthorized("authentication required")
- }
- raw := c.Header("X-Posta-Workspace-Id")
- if raw == "" {
- raw = c.Query("workspace_id")
- }
- if raw != "" {
- wsID, err := strconv.Atoi(raw)
- if err != nil || wsID <= 0 {
- return c.AbortBadRequest("invalid workspace id")
- }
- member, err := workspaceRepo.FindMember(uint(wsID), uint(userID))
- if err != nil {
- return c.AbortForbidden("you are not a member of this workspace")
- }
- c.Set("workspace_id", wsID)
- c.Set("workspace_role", string(member.Role))
- return c.Next()
- }
+ if required {
+ return c.AbortBadRequest(WorkspaceHeader + " header is required")
+ }
- // Neither header nor query — fall back to the personal workspace.
- if userRepo != nil {
- if personalID, err := userRepo.PersonalWorkspaceID(uint(userID)); err == nil && personalID != nil {
- c.Set("workspace_id", int(*personalID))
- c.Set("workspace_role", string(models.WorkspaceRoleOwner))
- }
+ // Nobody named a workspace: fall back to the caller's personal one. An
+ // unmigrated user has none — that is the legacy personal mode, not an error.
+ if userRepo != nil {
+ if personalID, err := userRepo.PersonalWorkspaceID(uint(userID)); err == nil && personalID != nil {
+ c.Set(CtxWorkspaceID, int(*personalID))
+ c.Set(CtxWorkspaceRole, string(models.WorkspaceRoleOwner))
}
- return c.Next()
}
+ return c.Next()
}
-// RequireWorkspaceMiddleware is like OptionalWorkspaceMiddleware but requires
-// the header to be present (for workspace-only endpoints like member management).
-func RequireWorkspaceMiddleware(workspaceRepo *repositories.WorkspaceRepository) okapi.Middleware {
+// RequireWorkspaceMiddleware demands an explicit workspace, except for a
+// workspace-bound API key, whose binding names it.
+func RequireWorkspaceMiddleware(workspaceRepo *repositories.WorkspaceRepository, userRepo *repositories.UserRepository) okapi.Middleware {
return func(c *okapi.Context) error {
- wsHeader := c.Header("X-Posta-Workspace-Id")
- if wsHeader == "" {
- return c.AbortBadRequest("X-Posta-Workspace-Id header is required")
- }
-
- userID := c.GetInt("user_id")
- if userID == 0 {
- return c.AbortUnauthorized("authentication required")
- }
+ return resolveWorkspace(c, workspaceRepo, userRepo, c.Header(WorkspaceHeader), true)
+ }
+}
- wsID, err := strconv.Atoi(wsHeader)
- if err != nil || wsID <= 0 {
- return c.AbortBadRequest("invalid X-Posta-Workspace-Id")
- }
+// OptionalWorkspaceMiddleware resolves the workspace when named, and otherwise
+// falls back to the caller's personal workspace.
+func OptionalWorkspaceMiddleware(workspaceRepo *repositories.WorkspaceRepository, userRepo *repositories.UserRepository) okapi.Middleware {
+ return func(c *okapi.Context) error {
+ return resolveWorkspace(c, workspaceRepo, userRepo, c.Header(WorkspaceHeader), false)
+ }
+}
- member, err := workspaceRepo.FindMember(uint(wsID), uint(userID))
- if err != nil {
- return c.AbortForbidden("you are not a member of this workspace")
+// WorkspaceFromQueryOrHeader is OptionalWorkspaceMiddleware for browser-direct
+// requests, which can pass the workspace only as a query parameter.
+func WorkspaceFromQueryOrHeader(workspaceRepo *repositories.WorkspaceRepository, userRepo *repositories.UserRepository) okapi.Middleware {
+ return func(c *okapi.Context) error {
+ raw := c.Header(WorkspaceHeader)
+ if raw == "" {
+ raw = c.Query("workspace_id")
}
-
- c.Set("workspace_id", wsID)
- c.Set("workspace_role", string(member.Role))
-
- return c.Next()
+ return resolveWorkspace(c, workspaceRepo, userRepo, raw, false)
}
}
-// RequireWorkspaceRole returns a middleware that enforces a minimum workspace role.
+// RequireWorkspaceRole enforces a minimum workspace role. A workspace-bound API
+// key resolves as owner, so it clears every tier.
func RequireWorkspaceRole(minRole models.WorkspaceRole) okapi.Middleware {
return func(c *okapi.Context) error {
- roleStr := c.GetString("workspace_role")
+ roleStr := c.GetString(CtxWorkspaceRole)
if roleStr == "" {
return c.AbortForbidden("workspace context required")
}
diff --git a/internal/middlewares/workspace_test.go b/internal/middlewares/workspace_test.go
new file mode 100644
index 0000000..72df905
--- /dev/null
+++ b/internal/middlewares/workspace_test.go
@@ -0,0 +1,256 @@
+/*
+ * 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 middlewares
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/jkaninda/okapi"
+)
+
+// stashAPIKey mimics authenticateAPIKey's context for a workspace-bound key.
+// boundWorkspace of 0 means an account-wide key.
+func stashAPIKey(userID, boundWorkspace int, scopes string) okapi.Middleware {
+ return func(c *okapi.Context) error {
+ c.Set(CtxUserID, userID)
+ c.Set(CtxAuthMethod, AuthMethodAPIKey)
+ c.Set(CtxAPIKeyScopes, scopes)
+ if boundWorkspace > 0 {
+ c.Set(CtxWorkspaceID, boundWorkspace)
+ c.Set(CtxAPIKeyWorkspaceID, boundWorkspace)
+ }
+ return c.Next()
+ }
+}
+
+// stashJWT mimics okapi's ForwardClaims for a session caller.
+func stashJWT(userID int) okapi.Middleware {
+ return func(c *okapi.Context) error {
+ c.Set(CtxUserID, userID)
+ c.Set(CtxAuthMethod, AuthMethodJWT)
+ return c.Next()
+ }
+}
+
+// A workspace-bound API key needs no repository lookup: the binding itself is
+// the authority, so these cases exercise resolveWorkspace with nil repos.
+func TestRequireWorkspace_BoundAPIKey(t *testing.T) {
+ cases := []struct {
+ name string
+ header string
+ wantStatus int
+ wantWSID string
+ wantRole string
+ }{
+ {
+ name: "binding supplies the workspace when no header is sent",
+ header: "",
+ wantStatus: http.StatusOK,
+ wantWSID: "7",
+ wantRole: string(models.WorkspaceRoleOwner),
+ },
+ {
+ name: "header agreeing with the binding is accepted",
+ header: "7",
+ wantStatus: http.StatusOK,
+ wantWSID: "7",
+ wantRole: string(models.WorkspaceRoleOwner),
+ },
+ {
+ name: "header naming another workspace is refused",
+ header: "9",
+ wantStatus: http.StatusForbidden,
+ },
+ {
+ name: "unparseable header is a bad request",
+ header: "abc",
+ wantStatus: http.StatusBadRequest,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ o := okapi.NewTestServer(t)
+ o.Get("/ws", func(c *okapi.Context) error {
+ return c.JSON(http.StatusOK, okapi.M{
+ "workspace_id": c.GetInt(CtxWorkspaceID),
+ "role": c.GetString(CtxWorkspaceRole),
+ })
+ }).Use(stashAPIKey(1, 7, models.ScopeRead), RequireWorkspaceMiddleware(nil, nil))
+
+ req := httptest.NewRequest(http.MethodGet, "/ws", nil)
+ if tc.header != "" {
+ req.Header.Set(WorkspaceHeader, tc.header)
+ }
+ rec := httptest.NewRecorder()
+ o.ServeHTTP(rec, req)
+
+ if rec.Code != tc.wantStatus {
+ t.Fatalf("status = %d, want %d (body %s)", rec.Code, tc.wantStatus, rec.Body.String())
+ }
+ if tc.wantStatus != http.StatusOK {
+ return
+ }
+ if body := rec.Body.String(); !strings.Contains(body, `"workspace_id":`+tc.wantWSID) || !strings.Contains(body, `"role":"`+tc.wantRole+`"`) {
+ t.Errorf("body = %s, want workspace %s as %s", body, tc.wantWSID, tc.wantRole)
+ }
+ })
+ }
+}
+
+// route registers a handler for an arbitrary method and returns the *Route, so
+// middleware can be attached (okapi's Handle returns nothing).
+func route(o *okapi.TestServer, method, path string, h okapi.HandlerFunc) *okapi.Route {
+ switch method {
+ case http.MethodGet:
+ return o.Get(path, h)
+ case http.MethodPost:
+ return o.Post(path, h)
+ case http.MethodPut:
+ return o.Put(path, h)
+ case http.MethodDelete:
+ return o.Delete(path, h)
+ default:
+ panic("unsupported method " + method)
+ }
+}
+
+// Scopes bound what a key may do inside the workspace it is bound to. The
+// binding alone must never imply full access: a send-only key is confined to the
+// public sending API and must not read or modify workspace resources.
+func TestWorkspaceScopeEnforcement(t *testing.T) {
+ cases := []struct {
+ name string
+ scopes string
+ method string
+ path string
+ wantStatus int
+ }{
+ // The vulnerability this guards: `send` is the default scope for a key
+ // created without an explicit set, so a leak of the weakest key must not
+ // expose the workspace's contacts, templates or domains.
+ {"send cannot read", models.ScopeSend, http.MethodGet, "/templates", http.StatusForbidden},
+ {"send cannot write", models.ScopeSend, http.MethodPost, "/templates", http.StatusForbidden},
+ {"send cannot administer", models.ScopeSend, http.MethodGet, "/api-keys", http.StatusForbidden},
+
+ {"read may read", models.ScopeRead, http.MethodGet, "/templates", http.StatusOK},
+ {"read may not write", models.ScopeRead, http.MethodPost, "/templates", http.StatusForbidden},
+ {"read may not delete", models.ScopeRead, http.MethodDelete, "/templates/1", http.StatusForbidden},
+
+ {"write may write", models.ScopeWrite, http.MethodPost, "/templates", http.StatusOK},
+ {"write may delete", models.ScopeWrite, http.MethodDelete, "/templates/1", http.StatusOK},
+ // write covers content, not the tenant itself — minting credentials or
+ // inviting members stays behind admin.
+ {"write may not mint keys", models.ScopeWrite, http.MethodPost, "/api-keys", http.StatusForbidden},
+ {"write may not invite", models.ScopeWrite, http.MethodPost, "/invitations", http.StatusForbidden},
+ {"write may not change settings", models.ScopeWrite, http.MethodPut, "/settings", http.StatusForbidden},
+
+ {"admin may mint keys", models.ScopeAdmin, http.MethodPost, "/api-keys", http.StatusOK},
+ {"admin may manage members", models.ScopeAdmin, http.MethodGet, "/members", http.StatusOK},
+ // admin is tenant administration, not a superset of content access.
+ {"admin alone cannot read templates", models.ScopeAdmin, http.MethodGet, "/templates", http.StatusForbidden},
+
+ {"wildcard grants everything", models.ScopeAll, http.MethodDelete, "/templates/1", http.StatusOK},
+ {"wildcard may administer", models.ScopeAll, http.MethodPost, "/api-keys", http.StatusOK},
+
+ {"multiple scopes combine", "read,write", http.MethodPost, "/templates", http.StatusOK},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ o := okapi.NewTestServer(t)
+ route(o, tc.method, "/api/v1/workspaces/current"+tc.path, func(c *okapi.Context) error {
+ return c.String(http.StatusOK, "ok")
+ }).Use(stashAPIKey(1, 7, tc.scopes), RequireWorkspaceMiddleware(nil, nil))
+
+ req := httptest.NewRequest(tc.method, "/api/v1/workspaces/current"+tc.path, nil)
+ rec := httptest.NewRecorder()
+ o.ServeHTTP(rec, req)
+
+ if rec.Code != tc.wantStatus {
+ t.Errorf("scopes=%q %s %s: status = %d, want %d",
+ tc.scopes, tc.method, tc.path, rec.Code, tc.wantStatus)
+ }
+ })
+ }
+}
+
+// A dashboard session carries no scopes; workspace RBAC governs it instead.
+func TestWorkspaceScope_SessionUnaffected(t *testing.T) {
+ o := okapi.NewTestServer(t)
+ o.Get("/api/v1/workspaces/current/api-keys", func(c *okapi.Context) error {
+ return c.String(http.StatusOK, "ok")
+ }).Use(stashJWT(1), WorkspaceFromQueryOrHeader(nil, nil))
+
+ rec := httptest.NewRecorder()
+ o.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/v1/workspaces/current/api-keys", nil))
+
+ if rec.Code != http.StatusOK {
+ t.Errorf("status = %d, want 200 (a session must not be scope checked)", rec.Code)
+ }
+}
+
+func TestRequireWorkspace_RejectsUnauthenticated(t *testing.T) {
+ o := okapi.NewTestServer(t)
+ o.Get("/ws", func(c *okapi.Context) error {
+ return c.String(http.StatusOK, "ok")
+ }).Use(RequireWorkspaceMiddleware(nil, nil))
+
+ rec := httptest.NewRecorder()
+ o.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/ws", nil))
+
+ if rec.Code != http.StatusUnauthorized {
+ t.Errorf("status = %d, want 401", rec.Code)
+ }
+}
+
+// A session caller must name a workspace on a required-workspace route; there is
+// no binding to fall back on.
+func TestRequireWorkspace_JWTWithoutHeader(t *testing.T) {
+ o := okapi.NewTestServer(t)
+ o.Get("/ws", func(c *okapi.Context) error {
+ return c.String(http.StatusOK, "ok")
+ }).Use(stashJWT(1), RequireWorkspaceMiddleware(nil, nil))
+
+ rec := httptest.NewRecorder()
+ o.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/ws", nil))
+
+ if rec.Code != http.StatusBadRequest {
+ t.Errorf("status = %d, want 400", rec.Code)
+ }
+}
+
+// WorkspaceFromQueryOrHeader exists for EventSource and download links, which
+// cannot set headers. A bound key still overrides whatever the query claims.
+func TestWorkspaceFromQuery_BoundKeyIgnoresMismatchedQuery(t *testing.T) {
+ o := okapi.NewTestServer(t)
+ o.Get("/stream", func(c *okapi.Context) error {
+ return c.String(http.StatusOK, "ok")
+ }).Use(stashAPIKey(1, 7, models.ScopeRead), WorkspaceFromQueryOrHeader(nil, nil))
+
+ rec := httptest.NewRecorder()
+ o.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/stream?workspace_id=9", nil))
+
+ if rec.Code != http.StatusForbidden {
+ t.Errorf("status = %d, want 403", rec.Code)
+ }
+}
diff --git a/internal/models/api_key.go b/internal/models/api_key.go
index 8b6cfc5..72f42c9 100644
--- a/internal/models/api_key.go
+++ b/internal/models/api_key.go
@@ -23,18 +23,25 @@ import (
"github.com/lib/pq"
)
+// API key scopes gate what an API-key caller may do inside the workspace the key
+// is scoped to. They never confer platform administration: /api/v1/admin/* is
+// reachable only from the admin dashboard with a user session.
const (
- ScopeSend = "send"
- ScopeRead = "read"
- ScopeWebhooks = "webhooks"
- ScopeSetup = "setup"
- ScopeAll = "*"
+ ScopeSend = "send" // send emails, batches, templates; subscriber-list ops
+ ScopeRead = "read" // read-only access to workspace resources
+ ScopeWebhooks = "webhooks" // create, list, and delete webhooks
+ ScopeWrite = "write" // create/update/delete workspace resources
+ ScopeAdmin = "admin" // administrative operations within the workspace
+ ScopeSetup = "setup" // reserved, not yet accepted on creation
+ ScopeAll = "*" // all scopes
)
var ValidScopes = map[string]bool{
ScopeSend: true,
ScopeRead: true,
ScopeWebhooks: true,
+ ScopeWrite: true,
+ ScopeAdmin: true,
ScopeAll: true,
}
@@ -56,6 +63,8 @@ type APIKey struct {
CreatedBy *ActorRef `json:"created_by,omitempty" gorm:"foreignKey:UserID;references:ID;constraint:false"`
}
+// HasScope reports whether the key grants scope s. An empty scope set means the
+// key predates scopes and grants only `send`; "*" grants everything.
func (k *APIKey) HasScope(s string) bool {
if len(k.Scopes) == 0 {
return s == ScopeSend
diff --git a/internal/models/api_key_test.go b/internal/models/api_key_test.go
index ff8d800..fbb202b 100644
--- a/internal/models/api_key_test.go
+++ b/internal/models/api_key_test.go
@@ -39,6 +39,16 @@ func TestAPIKeyHasScope(t *testing.T) {
{"wildcard grants webhooks", []string{ScopeAll}, ScopeWebhooks, true},
{"multi grants both", []string{ScopeSend, ScopeWebhooks}, ScopeWebhooks, true},
{"multi denies missing", []string{ScopeSend, ScopeWebhooks}, ScopeRead, false},
+
+ // write and admin are workspace-level scopes, covered by the wildcard like
+ // any other. Neither confers platform administration.
+ {"wildcard grants write", []string{ScopeAll}, ScopeWrite, true},
+ {"wildcard grants admin", []string{ScopeAll}, ScopeAdmin, true},
+ {"explicit write grants write", []string{ScopeWrite}, ScopeWrite, true},
+ {"explicit admin grants admin", []string{ScopeAdmin}, ScopeAdmin, true},
+ {"admin alone denies send", []string{ScopeAdmin}, ScopeSend, false},
+ {"empty denies write", nil, ScopeWrite, false},
+ {"empty denies admin", nil, ScopeAdmin, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
diff --git a/internal/routes/admin_routes.go b/internal/routes/admin_routes.go
index 80b4c7d..f6cada8 100644
--- a/internal/routes/admin_routes.go
+++ b/internal/routes/admin_routes.go
@@ -500,7 +500,7 @@ func (r *Router) adminRoutes() []okapi.RouteDefinition {
// adminSSERoutes returns route definitions for admin SSE (Server-Sent Events) endpoints.
func (r *Router) adminSSERoutes() []okapi.RouteDefinition {
- adminSSE := r.v1.Group("/admin", r.mw.jwtAdminQueryAuth.Middleware).WithTagInfo(okapi.GroupTag{
+ adminSSE := r.v1.Group("/admin", r.mw.jwtAdminAuth.Middleware).WithTagInfo(okapi.GroupTag{
Name: "Admin",
Description: "Platform-level administration: users, workspaces, global settings, OAuth providers, and live event streams. Admin-only.",
})
@@ -512,7 +512,7 @@ func (r *Router) adminSSERoutes() []okapi.RouteDefinition {
Handler: r.h.event.Stream,
Group: adminSSE,
Summary: "Stream events (SSE)",
- Description: "Real-time event stream via Server-Sent Events. Pass JWT token as ?token= query parameter.",
+ Description: "Real-time event stream via Server-Sent Events. Authenticated by the session cookie the browser sends on the EventSource handshake.",
Options: []okapi.RouteOption{okapi.DocHide()},
},
{
@@ -521,7 +521,7 @@ func (r *Router) adminSSERoutes() []okapi.RouteDefinition {
Handler: r.h.admin.MetricsStream,
Group: adminSSE,
Summary: "Stream platform metrics (SSE)",
- Description: "Real-time worker status and system runtime stats via Server-Sent Events. Emits worker.status and system.status events. Pass JWT token as ?token= query parameter.",
+ Description: "Real-time worker status and system runtime stats via Server-Sent Events. Emits worker.status and system.status events. Authenticated by the session cookie.",
Options: []okapi.RouteOption{okapi.DocHide()},
},
}
diff --git a/internal/routes/inbound_routes.go b/internal/routes/inbound_routes.go
index 0c60619..01a2eef 100644
--- a/internal/routes/inbound_routes.go
+++ b/internal/routes/inbound_routes.go
@@ -54,18 +54,15 @@ func (r *Router) inboundWebhookRoutes() []okapi.RouteDefinition {
}
func (r *Router) inboundWorkspaceRoutes() []okapi.RouteDefinition {
- userGroup := r.v1.Group("/workspaces/current", r.mw.jwtAuth.Middleware, r.mw.workspaceQuery).WithTagInfo(okapi.GroupTag{
+ // The SSE stream shares this group: EventSource cannot set an Authorization
+ // header, but it does send the session cookie, which r.mw.auth reads. Machine
+ // clients may stream with an API key via `?token=psk_…`.
+ userGroup := r.v1.Group("/workspaces/current", r.mw.auth, r.mw.workspaceQuery).WithTagInfo(okapi.GroupTag{
Name: "Inbound",
- Description: "Inbound email ingestion and retrieval: receive messages from upstream providers, browse history, and stream live events. Public ingest endpoints use opaque secrets; user endpoints use JWT.",
+ Description: "Inbound email ingestion and retrieval: receive messages from upstream providers, browse history, and stream live events. Public ingest endpoints use opaque secrets; user endpoints use a dashboard session or an API key.",
})
userGroup.WithBearerAuth()
- // SSE endpoints
- streamGroup := r.v1.Group("/workspaces/current", r.mw.jwtQueryAuth.Middleware, r.mw.workspaceQuery).WithTagInfo(okapi.GroupTag{
- Name: "Inbound",
- Description: "Inbound email ingestion and retrieval: receive messages from upstream providers, browse history, and stream live events. Public ingest endpoints use opaque secrets; user endpoints use JWT.",
- })
-
return []okapi.RouteDefinition{
{
Method: http.MethodGet,
@@ -125,7 +122,7 @@ func (r *Router) inboundWorkspaceRoutes() []okapi.RouteDefinition {
Method: http.MethodGet,
Path: "/inbound-stream",
Handler: r.h.inbound.Stream,
- Group: streamGroup,
+ Group: userGroup,
Summary: "Server-sent events stream of inbound-email events",
Options: []okapi.RouteOption{okapi.DocHide()},
},
diff --git a/internal/routes/oauth_routes.go b/internal/routes/oauth_routes.go
index c0c12e8..7817ca5 100644
--- a/internal/routes/oauth_routes.go
+++ b/internal/routes/oauth_routes.go
@@ -63,7 +63,7 @@ func (r *Router) oauthRoutes() []okapi.RouteDefinition {
}...)
// Authenticated OAuth routes (linked accounts)
- oauthUser := r.v1.Group("/users/me/oauth", r.mw.jwtAuth.Middleware).WithTagInfo(okapi.GroupTag{
+ oauthUser := r.v1.Group("/users/me/oauth", r.mw.jwtOnly).WithTagInfo(okapi.GroupTag{
Name: "OAuth",
Description: "Single sign-on via external identity providers (Google, GitHub, generic OIDC). Covers public flow, user-account linking, admin provider config, and workspace SSO enforcement.",
})
@@ -150,7 +150,7 @@ func (r *Router) oauthRoutes() []okapi.RouteDefinition {
}...)
// Workspace SSO config
- wsSSO := r.v1.Group("/workspaces/current/sso", r.mw.jwtAuth.Middleware, r.mw.workspace).WithTagInfo(
+ wsSSO := r.v1.Group("/workspaces/current/sso", r.mw.auth, r.mw.workspace).WithTagInfo(
okapi.GroupTag{
Name: "Workspaces",
Description: "Create workspaces, manage members and invitations, and configure workspace-scoped settings (including SSO).",
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index 95443a9..b5bd3a6 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -64,12 +64,18 @@ type Router struct {
}
type routerMiddleware struct {
- jwtAuth okapi.JWTAuth
- jwtQueryAuth okapi.JWTAuth
- jwtAdminAuth okapi.JWTAuth
- jwtAdminQueryAuth okapi.JWTAuth
- loginLimiter okapi.Middleware
+ // jwtAdminAuth guards platform administration. Only an admin user session
+ // satisfies it — /admin/* is dashboard-only and an API key is never a valid
+ // credential there, whatever scopes it carries.
+ jwtAdminAuth okapi.JWTAuth
+ // auth accepts a user JWT or an API key; it guards workspace-scoped routes.
+ auth okapi.Middleware
+ // jwtOnly accepts only a user JWT; it guards account-level routes (profile,
+ // 2FA, API key management), which a machine key must not reach.
+ jwtOnly okapi.Middleware
+ // apiKey accepts only an API key; it guards the public machine-facing API.
apiKey okapi.Middleware
+ loginLimiter okapi.Middleware
workspace okapi.Middleware
optionalWorkspace okapi.Middleware
workspaceQuery okapi.Middleware
@@ -216,18 +222,20 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
wm.OnCount(metrics.SetActiveWorkers)
wm.Start(ctx)
+ jwtAuth := middlewares.JWTAuth(cfg, sessionStore)
+ jwtAdminAuth := middlewares.JWTAdminAuth(cfg, sessionStore)
+
r := &Router{
app: app,
cfg: cfg,
v1: app.Group("/api/v1"),
mw: routerMiddleware{
- jwtAuth: middlewares.JWTAuth(cfg, sessionStore),
- jwtQueryAuth: middlewares.JWTQueryAuth(cfg, sessionStore),
- jwtAdminAuth: middlewares.JWTAdminAuth(cfg, sessionStore),
- jwtAdminQueryAuth: middlewares.JWTAdminQueryAuth(cfg, sessionStore),
+ jwtAdminAuth: jwtAdminAuth,
+ auth: middlewares.Authenticate(jwtAuth, apiKeyService, userRepo, apiKeyRepo),
+ jwtOnly: jwtAuth.Middleware,
+ apiKey: middlewares.APIKeyAuth(apiKeyService, userRepo, apiKeyRepo),
loginLimiter: loginLimiterMiddleware(cfg, limiter),
- apiKey: middlewares.APIKeyAuthMiddleware(apiKeyService, userRepo, apiKeyRepo),
- workspace: middlewares.RequireWorkspaceMiddleware(workspaceRepo),
+ workspace: middlewares.RequireWorkspaceMiddleware(workspaceRepo, userRepo),
optionalWorkspace: middlewares.OptionalWorkspaceMiddleware(workspaceRepo, userRepo),
workspaceQuery: middlewares.WorkspaceFromQueryOrHeader(workspaceRepo, userRepo),
},
diff --git a/internal/routes/tracking_routes.go b/internal/routes/tracking_routes.go
index e3c0bf6..c849d7b 100644
--- a/internal/routes/tracking_routes.go
+++ b/internal/routes/tracking_routes.go
@@ -109,7 +109,7 @@ func (r *Router) bounceWebhookRoutes() []okapi.RouteDefinition {
// trackingAnalyticsRoutes returns the authenticated campaign analytics route,
// scoped to the active workspace (workspace-only migration §7).
func (r *Router) trackingAnalyticsRoutes() []okapi.RouteDefinition {
- wsGroup := r.v1.Group("/workspaces/current", r.mw.jwtAuth.Middleware, r.mw.workspace).WithTagInfo(okapi.GroupTag{
+ wsGroup := r.v1.Group("/workspaces/current", r.mw.auth, r.mw.workspace).WithTagInfo(okapi.GroupTag{
Name: "Campaigns",
Description: "Email campaign analytics — open, click, bounce, and engagement metrics for campaigns in the active workspace.",
})
diff --git a/internal/routes/user_routes.go b/internal/routes/user_routes.go
index 231fe3d..04bc989 100644
--- a/internal/routes/user_routes.go
+++ b/internal/routes/user_routes.go
@@ -28,9 +28,9 @@ import (
// userRoutes returns route definitions for all authenticated user endpoints.
func (r *Router) userRoutes() []okapi.RouteDefinition {
- userGroup := r.v1.Group("/users/me", r.mw.jwtAuth.Middleware, r.mw.optionalWorkspace).WithTagInfo(okapi.GroupTag{
+ userGroup := r.v1.Group("/users/me", r.mw.jwtOnly, r.mw.optionalWorkspace).WithTagInfo(okapi.GroupTag{
Name: "User",
- Description: "Manage the authenticated user: profile, password, API keys, notification preferences, and session.",
+ Description: "Manage the authenticated user: profile, password, API keys, notification preferences, and session. Requires a dashboard session — an API key cannot administer the account that issued it.",
})
userGroup.WithBearerAuth()
diff --git a/internal/routes/workspace_resource_routes.go b/internal/routes/workspace_resource_routes.go
index 818c39a..ca16d08 100644
--- a/internal/routes/workspace_resource_routes.go
+++ b/internal/routes/workspace_resource_routes.go
@@ -28,9 +28,9 @@ import (
)
func (r *Router) workspaceResourceRoutes() []okapi.RouteDefinition {
- opsGroup := r.v1.Group("/workspaces/current", r.mw.jwtAuth.Middleware, r.mw.workspace).WithTagInfo(okapi.GroupTag{
+ opsGroup := r.v1.Group("/workspaces/current", r.mw.auth, r.mw.workspace).WithTagInfo(okapi.GroupTag{
Name: "Workspace resources",
- Description: "Operational resources scoped to the active workspace: sending, templates, stylesheets, languages, API keys, contacts, subscribers, campaigns, domains, SMTP servers, webhooks, suppressions, and workspace analytics.",
+ Description: "Operational resources scoped to the active workspace: sending, templates, stylesheets, languages, API keys, contacts, subscribers, campaigns, domains, SMTP servers, webhooks, suppressions, and workspace analytics. Authenticated with a dashboard session or an API key bound to the workspace.",
})
opsGroup.WithBearerAuth()
diff --git a/internal/routes/workspace_routes.go b/internal/routes/workspace_routes.go
index 720c24c..a5bd588 100644
--- a/internal/routes/workspace_routes.go
+++ b/internal/routes/workspace_routes.go
@@ -30,9 +30,9 @@ import (
// workspaceRoutes returns route definitions for workspace management.
func (r *Router) workspaceRoutes() []okapi.RouteDefinition {
// Routes that don't require workspace context (user-level)
- userGroup := r.v1.Group("/workspaces", r.mw.jwtAuth.Middleware).WithTagInfo(okapi.GroupTag{
+ userGroup := r.v1.Group("/workspaces", r.mw.jwtOnly).WithTagInfo(okapi.GroupTag{
Name: "Workspaces",
- Description: "Create workspaces, manage members and invitations, and configure workspace-scoped settings.",
+ Description: "Create workspaces, manage members and invitations, and configure workspace-scoped settings. Creating and listing workspaces is account-level and requires a dashboard session.",
})
userGroup.WithBearerAuth()
@@ -65,7 +65,7 @@ func (r *Router) workspaceRoutes() []okapi.RouteDefinition {
}...)
// Workspace-scoped routes (require workspace context via middleware)
- wsGroup := r.v1.Group("/workspaces/current", r.mw.jwtAuth.Middleware, r.mw.workspace).WithTagInfo(okapi.GroupTag{
+ wsGroup := r.v1.Group("/workspaces/current", r.mw.auth, r.mw.workspace).WithTagInfo(okapi.GroupTag{
Name: "Workspaces",
Description: "Create workspaces, manage members and invitations, and configure workspace-scoped settings (including SSO).",
})
@@ -293,7 +293,7 @@ func (r *Router) workspaceRoutes() []okapi.RouteDefinition {
}...)
// User-level invitation actions (no workspace context needed)
- invGroup := r.v1.Group("/invitations", r.mw.jwtAuth.Middleware).WithTagInfo(okapi.GroupTag{
+ invGroup := r.v1.Group("/invitations", r.mw.jwtOnly).WithTagInfo(okapi.GroupTag{
Name: "Workspaces",
Description: "Create workspaces, manage members and invitations, and configure workspace-scoped settings (including SSO).",
})
diff --git a/internal/services/auth/api_key.go b/internal/services/auth/api_key.go
index fd09a24..4dc85c1 100644
--- a/internal/services/auth/api_key.go
+++ b/internal/services/auth/api_key.go
@@ -29,7 +29,9 @@ import (
"github.com/goposta/posta/internal/storage/repositories"
)
-const apiKeyPrefix = "psk_"
+// APIKeyPrefix identifies a raw Posta API key. Auth middleware uses it to tell
+// an API key apart from a JWT without parsing either.
+const APIKeyPrefix = "psk_"
type APIKeyService struct {
repo *repositories.APIKeyRepository
@@ -69,7 +71,7 @@ func (s *APIKeyService) GenerateKey(userID uint, workspaceID *uint, name string,
return "", nil, fmt.Errorf("failed to generate key: %w", err)
}
- rawKey := apiKeyPrefix + hex.EncodeToString(rawBytes)
+ rawKey := APIKeyPrefix + hex.EncodeToString(rawBytes)
hash := hashKey(rawKey)
key := &models.APIKey{
@@ -77,7 +79,7 @@ func (s *APIKeyService) GenerateKey(userID uint, workspaceID *uint, name string,
WorkspaceID: workspaceID,
Name: name,
KeyHash: hash,
- KeyPrefix: rawKey[:len(apiKeyPrefix)+8],
+ KeyPrefix: rawKey[:len(APIKeyPrefix)+8],
AllowedIPs: allowedIPs,
Scopes: normScopes,
ExpiresAt: expiresAt,
@@ -92,11 +94,14 @@ func (s *APIKeyService) GenerateKey(userID uint, workspaceID *uint, name string,
// ValidateKey checks if a raw API key is valid and returns the matching APIKey.
func (s *APIKeyService) ValidateKey(rawKey string) (*models.APIKey, error) {
- if !strings.HasPrefix(rawKey, apiKeyPrefix) {
+ if !strings.HasPrefix(rawKey, APIKeyPrefix) {
+ return nil, fmt.Errorf("invalid key format")
+ }
+ if len(rawKey) < len(APIKeyPrefix)+8 {
return nil, fmt.Errorf("invalid key format")
}
- prefix := rawKey[:len(apiKeyPrefix)+8]
+ prefix := rawKey[:len(APIKeyPrefix)+8]
candidates, err := s.repo.FindByPrefix(prefix)
if err != nil {
return nil, fmt.Errorf("key not found")
diff --git a/internal/services/session/cookie.go b/internal/services/session/cookie.go
new file mode 100644
index 0000000..07737fa
--- /dev/null
+++ b/internal/services/session/cookie.go
@@ -0,0 +1,75 @@
+/*
+ * 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 session
+
+import (
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/jkaninda/okapi"
+)
+
+// CookieName holds the user JWT for browser clients. It is HttpOnly (so XSS
+// cannot read it) and SameSite=Strict (so it is never sent cross-site, which
+// blocks CSRF). Non-browser clients (CLI, SDKs, n8n) keep using the
+// Authorization header, so this cookie is additive, not a breaking change.
+const CookieName = "posta_session"
+
+// SetCookie writes the session cookie carrying token, expiring after ttl.
+//
+// okapi's Context.SetCookie cannot express SameSite, so the cookie is written
+// directly. The JWT alphabet (base64url plus '.') needs no escaping.
+func SetCookie(c *okapi.Context, token string, ttl time.Duration) {
+ http.SetCookie(c.Response(), &http.Cookie{
+ Name: CookieName,
+ Value: token,
+ Path: "/",
+ MaxAge: int(ttl.Seconds()),
+ Expires: time.Now().Add(ttl),
+ Secure: isHTTPS(c),
+ HttpOnly: true,
+ SameSite: http.SameSiteStrictMode,
+ })
+}
+
+// ClearCookie expires the session cookie. The attributes other than MaxAge must
+// match SetCookie's or the browser will keep the original cookie.
+func ClearCookie(c *okapi.Context) {
+ http.SetCookie(c.Response(), &http.Cookie{
+ Name: CookieName,
+ Value: "",
+ Path: "/",
+ MaxAge: -1,
+ Expires: time.Unix(0, 0),
+ Secure: isHTTPS(c),
+ HttpOnly: true,
+ SameSite: http.SameSiteStrictMode,
+ })
+}
+
+// isHTTPS reports whether the client reached us over TLS, either directly or
+// through a terminating proxy. A Secure cookie is dropped by the browser on a
+// plain-HTTP origin, so this must stay false for local http:// development.
+func isHTTPS(c *okapi.Context) bool {
+ r := c.Request()
+ if r.TLS != nil {
+ return true
+ }
+ return strings.EqualFold(c.Header("X-Forwarded-Proto"), "https")
+}
diff --git a/internal/services/session/cookie_test.go b/internal/services/session/cookie_test.go
new file mode 100644
index 0000000..2191b69
--- /dev/null
+++ b/internal/services/session/cookie_test.go
@@ -0,0 +1,121 @@
+/*
+ * 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 session
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/jkaninda/okapi"
+)
+
+// A JWT written by SetCookie must come back byte-identical from Cookie(),
+// otherwise okapi's cookie TokenLookup hands a corrupted token to the parser.
+func TestSetCookie_RoundTripsJWT(t *testing.T) {
+ const jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImp0aSI6ImEtYl9jIn0.7Hy-_signature"
+
+ o := okapi.NewTestServer(t)
+ o.Get("/login", func(c *okapi.Context) error {
+ SetCookie(c, jwt, time.Hour)
+ return c.String(http.StatusOK, "ok")
+ })
+ o.Get("/echo", func(c *okapi.Context) error {
+ v, err := c.Cookie(CookieName)
+ if err != nil {
+ return c.String(http.StatusUnauthorized, "missing")
+ }
+ return c.String(http.StatusOK, v)
+ })
+
+ rec := httptest.NewRecorder()
+ o.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/login", nil))
+
+ cookies := rec.Result().Cookies()
+ if len(cookies) != 1 {
+ t.Fatalf("got %d cookies, want 1", len(cookies))
+ }
+ ck := cookies[0]
+
+ if ck.Name != CookieName {
+ t.Errorf("name = %q, want %q", ck.Name, CookieName)
+ }
+ if !ck.HttpOnly {
+ t.Error("cookie must be HttpOnly so XSS cannot read the session")
+ }
+ if ck.SameSite != http.SameSiteStrictMode {
+ t.Errorf("SameSite = %v, want Strict", ck.SameSite)
+ }
+ if ck.Path != "/" {
+ t.Errorf("path = %q, want /", ck.Path)
+ }
+ if ck.Secure {
+ t.Error("plain-HTTP request must not get a Secure cookie, the browser would drop it")
+ }
+
+ echo := httptest.NewRequest(http.MethodGet, "/echo", nil)
+ echo.AddCookie(ck)
+ rec2 := httptest.NewRecorder()
+ o.ServeHTTP(rec2, echo)
+
+ if got := rec2.Body.String(); got != jwt {
+ t.Errorf("round-tripped token = %q, want %q", got, jwt)
+ }
+}
+
+func TestSetCookie_SecureBehindTLSTerminatingProxy(t *testing.T) {
+ o := okapi.NewTestServer(t)
+ o.Get("/login", func(c *okapi.Context) error {
+ SetCookie(c, "tok", time.Hour)
+ return c.String(http.StatusOK, "ok")
+ })
+
+ req := httptest.NewRequest(http.MethodGet, "/login", nil)
+ req.Header.Set("X-Forwarded-Proto", "https")
+ rec := httptest.NewRecorder()
+ o.ServeHTTP(rec, req)
+
+ if ck := rec.Result().Cookies()[0]; !ck.Secure {
+ t.Error("cookie must be Secure when the edge terminated TLS")
+ }
+}
+
+// ClearCookie must expire the cookie; its other attributes have to match
+// SetCookie's or the browser keeps the original.
+func TestClearCookie_Expires(t *testing.T) {
+ o := okapi.NewTestServer(t)
+ o.Get("/logout", func(c *okapi.Context) error {
+ ClearCookie(c)
+ return c.String(http.StatusOK, "ok")
+ })
+
+ rec := httptest.NewRecorder()
+ o.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/logout", nil))
+
+ ck := rec.Result().Cookies()[0]
+ if ck.Name != CookieName || ck.Value != "" {
+ t.Errorf("cookie = %s=%q, want %s empty", ck.Name, ck.Value, CookieName)
+ }
+ if ck.MaxAge >= 0 {
+ t.Errorf("MaxAge = %d, want negative", ck.MaxAge)
+ }
+ if ck.Path != "/" || !ck.HttpOnly || ck.SameSite != http.SameSiteStrictMode {
+ t.Error("clearing cookie attributes must match the ones SetCookie wrote")
+ }
+}
diff --git a/web/src/api/auth.ts b/web/src/api/auth.ts
index a86e6a9..25483ca 100644
--- a/web/src/api/auth.ts
+++ b/web/src/api/auth.ts
@@ -10,6 +10,10 @@ export const authApi = {
me() {
return api.get<ApiResponse<UserProfile>>('/users/me')
},
+ // Revokes the current session server-side and expires the session cookie.
+ logout() {
+ return api.post<ApiResponse<{ message: string }>>('/users/me/sessions/logout')
+ },
updateProfile(data: { name: string; require_verified_domain?: boolean }) {
return api.put<ApiResponse<UserProfile>>('/users/me', data)
},
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
index 383eb68..f008039 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -6,14 +6,9 @@ const api = axios.create({
headers: {
'Content-Type': 'application/json',
},
-})
-
-api.interceptors.request.use((config) => {
- const auth = useAuthStore()
- if (auth.token) {
- config.headers.Authorization = `Bearer ${auth.token}`
- }
- return config
+ // The session travels as an HttpOnly cookie. Same-origin requests would send
+ // it anyway; this also covers a cross-origin VITE_API_URL in development.
+ withCredentials: true,
})
api.interceptors.response.use(
@@ -22,7 +17,8 @@ api.interceptors.response.use(
if (error.response?.status === 401 && !error.response?.data?.data?.requires_2fa) {
const auth = useAuthStore()
const message = error.response?.data?.error?.message || 'Your session has expired'
- auth.logout()
+ // clearSession, not logout: logout() calls the API, which would 401 in turn.
+ auth.clearSession()
window.location.href = `/login?error=${encodeURIComponent(message)}`
}
return Promise.reject(error)
diff --git a/web/src/api/inbound.ts b/web/src/api/inbound.ts
index ca9146a..590596a 100644
--- a/web/src/api/inbound.ts
+++ b/web/src/api/inbound.ts
@@ -48,10 +48,10 @@ export const inboundApi = {
const ws = workspaceParam()
return `/api/v1/workspaces/current/inbound-emails/${uuid}/attachments/${idx}${ws ? `?${ws}` : ''}`
},
- streamUrl(token?: string) {
- const t = token ?? localStorage.getItem('posta_token') ?? ''
- const parts = [t ? `token=${encodeURIComponent(t)}` : '', workspaceParam()].filter(Boolean)
- const qs = parts.length ? `?${parts.join('&')}` : ''
- return `/api/v1/workspaces/current/inbound-stream${qs}`
+ // No token in the URL: EventSource sends the HttpOnly session cookie on the
+ // handshake, same as the download links above.
+ streamUrl() {
+ const ws = workspaceParam()
+ return `/api/v1/workspaces/current/inbound-stream${ws ? `?${ws}` : ''}`
},
}
diff --git a/web/src/layouts/DashboardLayout.vue b/web/src/layouts/DashboardLayout.vue
index 0886ca8..57b3ce3 100644
--- a/web/src/layouts/DashboardLayout.vue
+++ b/web/src/layouts/DashboardLayout.vue
@@ -301,8 +301,8 @@ function createWorkspace() {
router.push('/workspaces?create=1')
}
-function logout() {
- auth.logout()
+async function logout() {
+ await auth.logout()
router.push('/login')
}
diff --git a/web/src/stores/auth.ts b/web/src/stores/auth.ts
index b6df7b0..26bcaa0 100644
--- a/web/src/stores/auth.ts
+++ b/web/src/stores/auth.ts
@@ -1,13 +1,19 @@
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { authApi } from '../api/auth'
-import type { User, UserProfile, AuthResponse } from '../api/types'
+import type { User, UserProfile } from '../api/types'
+
+// The session lives in an HttpOnly cookie that the browser attaches to every
+// same-origin request, so there is no token here to hold. `posta_user` caches the
+// profile only so a reload can render before /users/me resolves — it is not a
+// credential. If the cookie is missing or expired the first API call 401s and the
+// response interceptor in api/client.ts sends us to /login.
+const USER_KEY = 'posta_user'
export const useAuthStore = defineStore('auth', () => {
- const token = ref(localStorage.getItem('posta_token') || '')
- const user = ref<User | UserProfile | null>(JSON.parse(localStorage.getItem('posta_user') || 'null'))
+ const user = ref<User | UserProfile | null>(JSON.parse(localStorage.getItem(USER_KEY) || 'null'))
- const isAuthenticated = computed(() => !!token.value)
+ const isAuthenticated = computed(() => !!user.value)
const isAdmin = computed(() => user.value?.role === 'admin')
async function login(email: string, password: string, twoFactorCode?: string) {
@@ -16,37 +22,46 @@ export const useAuthStore = defineStore('auth', () => {
if (!res.data.success && (res.data.data as any)?.requires_2fa) {
throw { requires2FA: true }
}
- setAuth(res.data.data)
+ setUser(res.data.data.user)
// Refresh to pick up extended profile fields (email_verified_at, etc).
await fetchUser()
return res.data.data
}
- function setAuth(data: AuthResponse) {
- token.value = data.token
- user.value = data.user
- localStorage.setItem('posta_token', data.token)
- localStorage.setItem('posta_user', JSON.stringify(data.user))
+ function setUser(u: User | UserProfile) {
+ user.value = u
+ localStorage.setItem(USER_KEY, JSON.stringify(u))
}
- function logout() {
- token.value = ''
+ // clearSession drops client state only. The 401 interceptor uses this: calling
+ // logout() there would fire another request that 401s in turn.
+ function clearSession() {
user.value = null
- localStorage.removeItem('posta_token')
- localStorage.removeItem('posta_user')
+ localStorage.removeItem(USER_KEY)
// Clear workspace state
localStorage.removeItem('posta_workspace_id')
}
+ // logout revokes the session server-side (blacklists its jti and expires the
+ // cookie), then clears client state. Best-effort: an offline or already-expired
+ // session still logs out locally.
+ async function logout() {
+ try {
+ await authApi.logout()
+ } catch {
+ /* the session is gone either way */
+ }
+ clearSession()
+ }
+
async function fetchUser() {
try {
const res = await authApi.me()
- user.value = res.data.data
- localStorage.setItem('posta_user', JSON.stringify(res.data.data))
+ setUser(res.data.data)
} catch {
- logout()
+ clearSession()
}
}
- return { token, user, isAuthenticated, isAdmin, login, logout, fetchUser }
+ return { user, isAuthenticated, isAdmin, login, logout, clearSession, fetchUser, setUser }
})
diff --git a/web/src/views/admin/Events.vue b/web/src/views/admin/Events.vue
index 0809b41..ca768f8 100644
--- a/web/src/views/admin/Events.vue
+++ b/web/src/views/admin/Events.vue
@@ -2,11 +2,9 @@
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { adminApi } from '../../api/admin'
-import { useAuthStore } from '../../stores/auth'
import type { Event } from '../../api/types'
import { usePagination } from '@/composables/usePagination'
import Pagination from '@/components/Pagination.vue'
-const auth = useAuthStore()
const router = useRouter()
const loading = ref(true)
const events = ref<Event[]>([])
@@ -55,10 +53,9 @@ function filterByCategory(cat: string) {
function startStream() {
const baseUrl = import.meta.env.VITE_API_URL || '/api/v1'
- const token = auth.token
- if (!token) return
- const url = `${baseUrl}/admin/events/stream?token=${encodeURIComponent(token)}`
- eventSource = new EventSource(url)
+ // EventSource cannot set an Authorization header, but it does send the
+ // HttpOnly session cookie on the handshake, which is what the server reads.
+ eventSource = new EventSource(`${baseUrl}/admin/events/stream`, { withCredentials: true })
eventSource.onopen = () => {
streaming.value = true
diff --git a/web/src/views/admin/Metrics.vue b/web/src/views/admin/Metrics.vue
index f7c2d63..527fdd0 100644
--- a/web/src/views/admin/Metrics.vue
+++ b/web/src/views/admin/Metrics.vue
@@ -2,10 +2,8 @@
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { adminApi } from '../../api/admin'
import { analyticsApi } from '../../api/analytics'
-import { useAuthStore } from '../../stores/auth'
import type { AdminMetrics, WorkerStatus, SystemStatus, AnalyticsResponse, DashboardAnalyticsResponse } from '../../api/types'
-const auth = useAuthStore()
const loading = ref(true)
const metrics = ref<AdminMetrics | null>(null)
const workerStatus = ref<WorkerStatus | null>(null)
@@ -37,10 +35,9 @@ onBeforeUnmount(() => {
function startWorkerStream() {
const baseUrl = import.meta.env.VITE_API_URL || '/api/v1'
- const token = auth.token
- if (!token) return
- const url = `${baseUrl}/admin/metrics/stream?token=${encodeURIComponent(token)}`
- workerSSE = new EventSource(url)
+ // EventSource cannot set an Authorization header; the HttpOnly session cookie
+ // rides the handshake instead.
+ workerSSE = new EventSource(`${baseUrl}/admin/metrics/stream`, { withCredentials: true })
workerSSE.addEventListener('worker.status', (e) => {
try {
diff --git a/web/src/views/apikeys/ApiKeys.vue b/web/src/views/apikeys/ApiKeys.vue
index c914988..d6e05c0 100644
--- a/web/src/views/apikeys/ApiKeys.vue
+++ b/web/src/views/apikeys/ApiKeys.vue
@@ -25,10 +25,14 @@ const newKeyIPs = ref('')
const newKeyScopes = ref<string[]>(['send'])
const newKeyExpiry = ref('default')
+// Workspace-level scopes. None of them grant platform administration — the
+// /admin dashboard is reachable only with a user session.
const scopeOptions = [
{ value: 'send', label: 'Send', hint: 'Send emails, batches, templates, and manage subscriber lists' },
{ value: 'read', label: 'Read', hint: 'List/get emails, bounces, and webhook deliveries' },
{ value: 'webhooks', label: 'Webhooks', hint: 'Create, list, and delete webhooks' },
+ { value: 'write', label: 'Write', hint: 'Create, update, and delete workspace resources' },
+ { value: 'admin', label: 'Admin', hint: 'Administrative operations within the workspace' },
]
function toggleScope(value: string) {
diff --git a/web/src/views/auth/OAuthCallback.vue b/web/src/views/auth/OAuthCallback.vue
index ad30c8e..62e6e63 100644
--- a/web/src/views/auth/OAuthCallback.vue
+++ b/web/src/views/auth/OAuthCallback.vue
@@ -9,7 +9,6 @@ const auth = useAuthStore()
const error = ref('')
onMounted(async () => {
- const token = route.query.token as string
const errorParam = route.query.error as string
if (errorParam) {
@@ -18,23 +17,15 @@ onMounted(async () => {
return
}
- if (!token) {
- error.value = 'No token received'
- setTimeout(() => router.push('/login'), 3000)
- return
- }
-
- // Set token and fetch user profile
- localStorage.setItem('posta_token', token)
- auth.token = token
-
- try {
- await auth.fetchUser()
- router.push('/')
- } catch {
+ // The callback set an HttpOnly session cookie, so there is no token on the URL
+ // to pick up. Fetching the profile both loads it and proves the cookie is good.
+ await auth.fetchUser()
+ if (!auth.isAuthenticated) {
error.value = 'Failed to load user profile'
setTimeout(() => router.push('/login'), 3000)
+ return
}
+ router.push('/')
})
</script>
diff --git a/web/src/views/auth/Register.vue b/web/src/views/auth/Register.vue
index 59423a3..dde9011 100644
--- a/web/src/views/auth/Register.vue
+++ b/web/src/views/auth/Register.vue
@@ -58,10 +58,9 @@ async function handleRegister() {
loading.value = true
try {
+ // Register auto-logs-in by setting the session cookie on the response.
const res = await authApi.register(name.value.trim(), email.value.trim(), password.value)
- const data = res.data.data
- localStorage.setItem('posta_token', data.token)
- localStorage.setItem('posta_user', JSON.stringify(data.user))
+ auth.setUser(res.data.data.user)
window.location.href = '/'
} catch (err: any) {
const message = err?.response?.data?.error?.message || err?.response?.data?.error || err?.message || 'Registration failed.'