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.

feat(api-keys): scope-gated read & webhook access via API key (#141)

Jonas Kanindab535a19b050c
diff --git a/internal/dto/types.go b/internal/dto/types.go
index 003978d..67751db 100644
--- a/internal/dto/types.go
+++ b/internal/dto/types.go
@@ -54,11 +54,12 @@ type ErrorInfo struct {
}
type APIKeyCreatedData struct {
- Key string `json:"key"`
- ID uint `json:"id"`
- Name string `json:"name"`
- Prefix string `json:"prefix"`
- Message string `json:"message"`
+ Key string `json:"key"`
+ ID uint `json:"id"`
+ Name string `json:"name"`
+ Prefix string `json:"prefix"`
+ Scopes []string `json:"scopes" enum:"send,read,webhooks,*"`
+ Message string `json:"message"`
}
type MessageData struct {
diff --git a/internal/handlers/api_key_handler.go b/internal/handlers/api_key_handler.go
index 07c3d96..93b4d74 100644
--- a/internal/handlers/api_key_handler.go
+++ b/internal/handlers/api_key_handler.go
@@ -48,6 +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"`
ExpiresInDays *int `json:"expires_in_days"`
} `json:"body"`
}
@@ -79,6 +80,11 @@ func (h *APIKeyHandler) Create(c *okapi.Context, req *CreateAPIKeyRequest) error
}
scope := getScope(c)
+ scopes, err := auth.NormalizeScopes(req.Body.Scopes)
+ if err != nil {
+ return c.AbortBadRequest("invalid scope", err)
+ }
+
if h.quota != nil {
if err := h.quota.CheckQuota(h.db, scope.UserID, scope.WorkspaceID, "api_keys"); err != nil {
return c.AbortForbidden("API key quota exceeded for this workspace", err)
@@ -103,12 +109,14 @@ func (h *APIKeyHandler) Create(c *okapi.Context, req *CreateAPIKeyRequest) error
}
}
- rawKey, key, err := h.service.GenerateKey(scope.UserID, scope.WorkspaceID, req.Body.Name, req.Body.AllowedIPs, expiresAt)
+ rawKey, key, err := h.service.GenerateKey(scope.UserID, scope.WorkspaceID, req.Body.Name, req.Body.AllowedIPs, scopes, expiresAt)
if err != nil {
return c.AbortInternalServerError("failed to create API key", err)
}
- h.audit.LogCtx(c, "apikey.created", "API key created: "+req.Body.Name, nil)
+ h.audit.LogCtx(c, "apikey.created", "API key created: "+req.Body.Name, map[string]any{
+ "scopes": []string(key.Scopes),
+ })
// Send API key created notification
if h.notifier != nil {
@@ -132,6 +140,7 @@ func (h *APIKeyHandler) Create(c *okapi.Context, req *CreateAPIKeyRequest) error
"id": key.ID,
"name": key.Name,
"prefix": key.KeyPrefix,
+ "scopes": []string(key.Scopes),
"expires_at": key.ExpiresAt,
"message": "Save this key securely. It will not be shown again.",
})
diff --git a/internal/middlewares/middleware.go b/internal/middlewares/middleware.go
index c105b21..b6818af 100644
--- a/internal/middlewares/middleware.go
+++ b/internal/middlewares/middleware.go
@@ -24,6 +24,7 @@ import (
"github.com/golang-jwt/jwt/v5"
"github.com/goposta/posta/internal/config"
+ "github.com/goposta/posta/internal/models"
"github.com/goposta/posta/internal/services/auth"
"github.com/goposta/posta/internal/services/emailverify"
"github.com/goposta/posta/internal/services/ratelimit"
@@ -208,9 +209,29 @@ func APIKeyAuthMiddleware(keyService *auth.APIKeyService, userRepo *repositories
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()
}
}
+
+// RequireScope aborts 403 unless the authenticated API key grants scope (or "*").
+// These routes are API-key-only; JWT callers never reach this middleware.
+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)
+ }
+}
diff --git a/internal/middlewares/scope_test.go b/internal/middlewares/scope_test.go
new file mode 100644
index 0000000..3640787
--- /dev/null
+++ b/internal/middlewares/scope_test.go
@@ -0,0 +1,68 @@
+/*
+ * 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"
+ "testing"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/jkaninda/okapi"
+)
+
+// stashScopes mimics APIKeyAuthMiddleware setting the key's scopes on context.
+func stashScopes(raw string) okapi.Middleware {
+ return func(c *okapi.Context) error {
+ c.Set("api_key_scopes", raw)
+ return c.Next()
+ }
+}
+
+func TestRequireScope(t *testing.T) {
+ cases := []struct {
+ name 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},
+ }
+ 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))
+
+ 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)
+ }
+ })
+ }
+}
diff --git a/internal/models/api_key.go b/internal/models/api_key.go
index 65913d9..8b6cfc5 100644
--- a/internal/models/api_key.go
+++ b/internal/models/api_key.go
@@ -23,6 +23,21 @@ import (
"github.com/lib/pq"
)
+const (
+ ScopeSend = "send"
+ ScopeRead = "read"
+ ScopeWebhooks = "webhooks"
+ ScopeSetup = "setup"
+ ScopeAll = "*"
+)
+
+var ValidScopes = map[string]bool{
+ ScopeSend: true,
+ ScopeRead: true,
+ ScopeWebhooks: true,
+ ScopeAll: true,
+}
+
type APIKey struct {
ID uint `json:"id" gorm:"primaryKey"`
UserID uint `json:"user_id" gorm:"index;not null"`
@@ -35,11 +50,24 @@ type APIKey struct {
LastUsedAt *time.Time `json:"last_used_at"`
Revoked bool `json:"revoked" gorm:"default:false"`
AllowedIPs pq.StringArray `json:"allowed_ips" gorm:"type:text[]"`
+ Scopes pq.StringArray `json:"scopes" gorm:"type:text[]"`
User User `json:"-" gorm:"foreignKey:UserID"`
CreatedBy *ActorRef `json:"created_by,omitempty" gorm:"foreignKey:UserID;references:ID;constraint:false"`
}
+func (k *APIKey) HasScope(s string) bool {
+ if len(k.Scopes) == 0 {
+ return s == ScopeSend
+ }
+ for _, sc := range k.Scopes {
+ if sc == ScopeAll || sc == s {
+ return true
+ }
+ }
+ return false
+}
+
func (k *APIKey) IsExpired() bool {
if k.ExpiresAt == nil {
return false
diff --git a/internal/models/api_key_test.go b/internal/models/api_key_test.go
new file mode 100644
index 0000000..ff8d800
--- /dev/null
+++ b/internal/models/api_key_test.go
@@ -0,0 +1,51 @@
+/*
+ * 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 models
+
+import (
+ "testing"
+
+ "github.com/lib/pq"
+)
+
+func TestAPIKeyHasScope(t *testing.T) {
+ cases := []struct {
+ name string
+ scopes []string
+ query string
+ want bool
+ }{
+ {"empty defaults to send", nil, ScopeSend, true},
+ {"empty denies read", nil, ScopeRead, false},
+ {"empty denies webhooks", nil, ScopeWebhooks, false},
+ {"explicit read grants read", []string{ScopeRead}, ScopeRead, true},
+ {"explicit read denies send", []string{ScopeRead}, ScopeSend, false},
+ {"wildcard grants read", []string{ScopeAll}, ScopeRead, true},
+ {"wildcard grants webhooks", []string{ScopeAll}, ScopeWebhooks, true},
+ {"multi grants both", []string{ScopeSend, ScopeWebhooks}, ScopeWebhooks, true},
+ {"multi denies missing", []string{ScopeSend, ScopeWebhooks}, ScopeRead, false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ k := &APIKey{Scopes: pq.StringArray(tc.scopes)}
+ if got := k.HasScope(tc.query); got != tc.want {
+ t.Errorf("HasScope(%q) with scopes %v = %v, want %v", tc.query, tc.scopes, got, tc.want)
+ }
+ })
+ }
+}
diff --git a/internal/routes/auth_routes.go b/internal/routes/auth_routes.go
index 6af1c05..7ce3c89 100644
--- a/internal/routes/auth_routes.go
+++ b/internal/routes/auth_routes.go
@@ -22,6 +22,8 @@ import (
"github.com/goposta/posta/internal/dto"
"github.com/goposta/posta/internal/handlers"
+ "github.com/goposta/posta/internal/middlewares"
+ "github.com/goposta/posta/internal/models"
"github.com/goposta/posta/internal/services/email"
"github.com/goposta/posta/internal/services/verifier"
"github.com/jkaninda/okapi"
@@ -153,12 +155,31 @@ func (r *Router) authRoutes() []okapi.RouteDefinition {
// apiAuthRoutes returns route definitions for API-key authenticated endpoints.
func (r *Router) apiAuthRoutes() []okapi.RouteDefinition {
- apiAuth := r.v1.Group("", r.mw.apiKey).
+ apiKeySec := []map[string][]string{{"ApiKeyAuth": {}}}
+
+ // Send/subscriber routes require the `send` scope explicitly.
+ apiAuth := r.v1.Group("", r.mw.apiKey, middlewares.RequireScope(models.ScopeSend)).
WithTagInfo(okapi.GroupTag{
Name: "Emails",
Description: "Send transactional and templated emails, run batch sends, and manage scheduled delivery. Authenticated with an API key.",
}).
- WithSecurity([]map[string][]string{{"ApiKeyAuth": {}}})
+ WithSecurity(apiKeySec)
+
+ // Read routes (list/get emails, bounces, webhook deliveries) require `read`.
+ apiRead := r.v1.Group("", r.mw.apiKey, middlewares.RequireScope(models.ScopeRead)).
+ WithTagInfo(okapi.GroupTag{
+ Name: "Read",
+ Description: "Read-only access to emails, bounces, and webhook delivery logs. Authenticated with an API key holding the `read` scope.",
+ }).
+ WithSecurity(apiKeySec)
+
+ // Webhook management routes require the `webhooks` scope.
+ apiWebhooks := r.v1.Group("", r.mw.apiKey, middlewares.RequireScope(models.ScopeWebhooks)).
+ WithTagInfo(okapi.GroupTag{
+ Name: "Webhooks",
+ Description: "Create, list, and delete webhooks. Authenticated with an API key holding the `webhooks` scope.",
+ }).
+ WithSecurity(apiKeySec)
return []okapi.RouteDefinition{
{
@@ -303,5 +324,107 @@ func (r *Router) apiAuthRoutes() []okapi.RouteDefinition {
okapi.DocErrorResponse(400, &dto.ErrorResponseBody{}),
},
},
+
+ // read scope
+ {
+ Method: http.MethodGet,
+ Path: "/emails",
+ Handler: okapi.H(r.h.email.List),
+ Group: apiRead,
+ Summary: "List emails",
+ Description: "List sent emails with pagination. Requires the `read` scope.",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.Email]{},
+ Options: []okapi.RouteOption{
+ okapi.DocErrorResponse(401, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(403, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/emails/{id}",
+ Handler: okapi.H(r.h.email.Get),
+ Group: apiRead,
+ Summary: "Get email details",
+ Description: "Returns full details for a single email. Requires the `read` scope.",
+ Response: &dto.Response[models.Email]{},
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "string", "Email UUID"),
+ okapi.DocErrorResponse(403, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/bounces",
+ Handler: okapi.H(r.h.bounce.List),
+ Group: apiRead,
+ Summary: "List bounces",
+ Description: "List recorded bounces and complaints with pagination. Requires the `read` scope.",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.Bounce]{},
+ Options: []okapi.RouteOption{
+ okapi.DocErrorResponse(401, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(403, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodGet,
+ Path: "/webhook-deliveries",
+ Handler: okapi.H(r.h.webhookDelivery.List),
+ Group: apiRead,
+ Summary: "List webhook deliveries",
+ Description: "List webhook delivery attempts with pagination. Requires the `read` scope.",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.WebhookDelivery]{},
+ Options: []okapi.RouteOption{
+ okapi.DocErrorResponse(401, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(403, &dto.ErrorResponseBody{}),
+ },
+ },
+
+ // webhooks scope
+ {
+ Method: http.MethodGet,
+ Path: "/webhooks",
+ Handler: okapi.H(r.h.webhook.List),
+ Group: apiWebhooks,
+ Summary: "List webhooks",
+ Description: "List configured webhooks with pagination. Requires the `webhooks` scope.",
+ Request: &handlers.ListRequest{},
+ Response: &dto.PageableResponse[models.Webhook]{},
+ Options: []okapi.RouteOption{
+ okapi.DocErrorResponse(401, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(403, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/webhooks",
+ Handler: okapi.H(r.h.webhook.Create),
+ Group: apiWebhooks,
+ Summary: "Create webhook",
+ Description: "Register a webhook endpoint for event delivery. Requires the `webhooks` scope.",
+ Request: &handlers.CreateWebhookRequest{},
+ Options: []okapi.RouteOption{
+ okapi.DocResponse(201, &dto.Response[models.Webhook]{}),
+ okapi.DocErrorResponse(401, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(403, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodDelete,
+ Path: "/webhooks/{id:int}",
+ Handler: okapi.H(r.h.webhook.Delete),
+ Group: apiWebhooks,
+ Summary: "Delete webhook",
+ Description: "Delete a webhook by ID. Requires the `webhooks` scope.",
+ Options: []okapi.RouteOption{
+ okapi.DocPathParam("id", "integer", "Webhook ID"),
+ okapi.DocResponse(204, nil),
+ okapi.DocErrorResponse(403, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
}
}
diff --git a/internal/services/auth/api_key.go b/internal/services/auth/api_key.go
index ee081bb..fd09a24 100644
--- a/internal/services/auth/api_key.go
+++ b/internal/services/auth/api_key.go
@@ -39,9 +39,31 @@ func NewAPIKeyService(repo *repositories.APIKeyRepository) *APIKeyService {
return &APIKeyService{repo: repo}
}
-// GenerateKey creates a new API key and returns the raw key (only shown once).
-// If expiresAt is nil the key never expires.
-func (s *APIKeyService) GenerateKey(userID uint, workspaceID *uint, name string, allowedIPs []string, expiresAt *time.Time) (string, *models.APIKey, error) {
+func NormalizeScopes(scopes []string) ([]string, error) {
+ if len(scopes) == 0 {
+ return []string{models.ScopeSend}, nil
+ }
+ seen := make(map[string]bool, len(scopes))
+ out := make([]string, 0, len(scopes))
+ for _, sc := range scopes {
+ if !models.ValidScopes[sc] {
+ return nil, fmt.Errorf("unknown scope: %q", sc)
+ }
+ if seen[sc] {
+ continue
+ }
+ seen[sc] = true
+ out = append(out, sc)
+ }
+ return out, nil
+}
+
+func (s *APIKeyService) GenerateKey(userID uint, workspaceID *uint, name string, allowedIPs []string, scopes []string, expiresAt *time.Time) (string, *models.APIKey, error) {
+ normScopes, err := NormalizeScopes(scopes)
+ if err != nil {
+ return "", nil, err
+ }
+
rawBytes := make([]byte, 32)
if _, err := rand.Read(rawBytes); err != nil {
return "", nil, fmt.Errorf("failed to generate key: %w", err)
@@ -57,6 +79,7 @@ func (s *APIKeyService) GenerateKey(userID uint, workspaceID *uint, name string,
KeyHash: hash,
KeyPrefix: rawKey[:len(apiKeyPrefix)+8],
AllowedIPs: allowedIPs,
+ Scopes: normScopes,
ExpiresAt: expiresAt,
}
diff --git a/internal/services/auth/api_key_test.go b/internal/services/auth/api_key_test.go
new file mode 100644
index 0000000..742f07d
--- /dev/null
+++ b/internal/services/auth/api_key_test.go
@@ -0,0 +1,59 @@
+/*
+ * 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 auth
+
+import (
+ "reflect"
+ "testing"
+
+ "github.com/goposta/posta/internal/models"
+)
+
+func TestNormalizeScopes(t *testing.T) {
+ cases := []struct {
+ name string
+ in []string
+ want []string
+ wantErr bool
+ }{
+ {"nil defaults to send", nil, []string{models.ScopeSend}, false},
+ {"empty defaults to send", []string{}, []string{models.ScopeSend}, false},
+ {"passes through valid", []string{models.ScopeRead, models.ScopeWebhooks}, []string{models.ScopeRead, models.ScopeWebhooks}, false},
+ {"dedupes", []string{models.ScopeSend, models.ScopeSend, models.ScopeRead}, []string{models.ScopeSend, models.ScopeRead}, false},
+ {"wildcard is valid", []string{models.ScopeAll}, []string{models.ScopeAll}, false},
+ {"unknown scope errors", []string{"delete-everything"}, nil, true},
+ {"setup rejected until phase 2", []string{models.ScopeSetup}, nil, true},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got, err := NormalizeScopes(tc.in)
+ if tc.wantErr {
+ if err == nil {
+ t.Fatalf("NormalizeScopes(%v) = %v, want error", tc.in, got)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("NormalizeScopes(%v) unexpected error: %v", tc.in, err)
+ }
+ if !reflect.DeepEqual(got, tc.want) {
+ t.Errorf("NormalizeScopes(%v) = %v, want %v", tc.in, got, tc.want)
+ }
+ })
+ }
+}
diff --git a/internal/storage/migration/upgrade/step.go b/internal/storage/migration/upgrade/step.go
index abc3a2d..735c6f9 100644
--- a/internal/storage/migration/upgrade/step.go
+++ b/internal/storage/migration/upgrade/step.go
@@ -39,6 +39,10 @@ var registry = []Step{
ID: "2026-06-04-dedupe-contacts",
Apply: applyDedupeContacts,
},
+ {
+ ID: "2026-06-11-api-key-scopes",
+ Apply: applyAPIKeyScopes,
+ },
}
func Registry() []Step {
diff --git a/internal/storage/migration/upgrade/steps_2026_06_11_api_key_scopes.go b/internal/storage/migration/upgrade/steps_2026_06_11_api_key_scopes.go
new file mode 100644
index 0000000..f807b27
--- /dev/null
+++ b/internal/storage/migration/upgrade/steps_2026_06_11_api_key_scopes.go
@@ -0,0 +1,33 @@
+/*
+ * 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 upgrade
+
+import (
+ "fmt"
+
+ "gorm.io/gorm"
+)
+
+func applyAPIKeyScopes(tx *gorm.DB) error {
+ if err := tx.Exec(
+ `UPDATE api_keys SET scopes = '{send}' WHERE scopes IS NULL OR scopes = '{}'`,
+ ).Error; err != nil {
+ return fmt.Errorf("backfill api_key scopes: %w", err)
+ }
+ return nil
+}
diff --git a/web/src/api/apikeys.ts b/web/src/api/apikeys.ts
index e9fc2f6..365ae42 100644
--- a/web/src/api/apikeys.ts
+++ b/web/src/api/apikeys.ts
@@ -8,9 +8,10 @@ export const apiKeysApi = {
get(id: number) {
return api.get<ApiResponse<ApiKey>>(`/workspaces/current/api-keys/${id}`)
},
- create(name: string, allowedIPs?: string[], expiresInDays?: number) {
+ create(name: string, allowedIPs?: string[], scopes?: string[], expiresInDays?: number) {
const body: Record<string, any> = { name }
if (allowedIPs && allowedIPs.length > 0) body.allowed_ips = allowedIPs
+ if (scopes && scopes.length > 0) body.scopes = scopes
if (expiresInDays !== undefined) body.expires_in_days = expiresInDays
return api.post<ApiResponse<ApiKeyCreateResponse>>('/workspaces/current/api-keys', body)
},
diff --git a/web/src/api/types.ts b/web/src/api/types.ts
index c72c2d7..39710ee 100644
--- a/web/src/api/types.ts
+++ b/web/src/api/types.ts
@@ -119,6 +119,7 @@ export interface ApiKey {
last_used_at: string | null
revoked: boolean
allowed_ips: string[] | null
+ scopes: string[] | null
created_by?: ActorRef | null
}
@@ -139,6 +140,7 @@ export interface ApiKeyCreateResponse {
id: number
name: string
prefix: string
+ scopes: string[] | null
expires_at: string | null
message: string
}
diff --git a/web/src/views/apikeys/ApiKeyDetail.vue b/web/src/views/apikeys/ApiKeyDetail.vue
index 74f46f3..6f76d98 100644
--- a/web/src/views/apikeys/ApiKeyDetail.vue
+++ b/web/src/views/apikeys/ApiKeyDetail.vue
@@ -37,6 +37,9 @@ const status = computed<{ label: string; class: string }>(() => {
return { label: 'Active', class: 'badge-success' }
})
+// An empty/missing scope set means the key predates scopes; show it as send.
+const keyScopes = computed<string[]>(() => key.value?.scopes ?? [])
+
const isActive = computed(() => {
const k = key.value
return !!k && !k.revoked && !(k.expires_at && new Date(k.expires_at) < new Date())
@@ -144,6 +147,20 @@ async function remove() {
<td style="font-weight: 600">Expires</td>
<td>{{ formatDate(key.expires_at) }}</td>
</tr>
+ <tr>
+ <td style="font-weight: 600">Scopes</td>
+ <td>
+ <template v-if="keyScopes.length > 0">
+ <span
+ v-for="s in keyScopes"
+ :key="s"
+ style="display: inline-block; padding: 2px 8px; margin-right: 4px; font-size: 12px; border-radius: 4px; background: var(--bg-muted, #eef0f3); color: var(--text-secondary)"
+ >{{ s }}</span
+ >
+ </template>
+ <span v-else style="color: var(--text-muted)">send</span>
+ </td>
+ </tr>
<tr>
<td style="font-weight: 600">Allowed IPs</td>
<td>
diff --git a/web/src/views/apikeys/ApiKeys.vue b/web/src/views/apikeys/ApiKeys.vue
index bd1e6a1..c914988 100644
--- a/web/src/views/apikeys/ApiKeys.vue
+++ b/web/src/views/apikeys/ApiKeys.vue
@@ -22,7 +22,20 @@ const appInfo = ref<AppInfo | null>(null)
const showCreateModal = ref(false)
const newKeyName = ref('')
const newKeyIPs = ref('')
+const newKeyScopes = ref<string[]>(['send'])
const newKeyExpiry = ref('default')
+
+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' },
+]
+
+function toggleScope(value: string) {
+ const i = newKeyScopes.value.indexOf(value)
+ if (i === -1) newKeyScopes.value.push(value)
+ else newKeyScopes.value.splice(i, 1)
+}
const defaultExpiryDays = ref(90)
const creating = ref(false)
@@ -79,15 +92,18 @@ async function createKey() {
.map(ip => ip.trim())
.filter(ip => ip.length > 0)
const expiresInDays = resolveExpiryDays()
+ const scopes = newKeyScopes.value.length > 0 ? [...newKeyScopes.value] : ['send']
const res = await apiKeysApi.create(
newKeyName.value.trim(),
allowedIPs.length > 0 ? allowedIPs : undefined,
+ scopes,
expiresInDays,
)
createdKey.value = res.data.data
showCreateModal.value = false
newKeyName.value = ''
newKeyIPs.value = ''
+ newKeyScopes.value = ['send']
newKeyExpiry.value = 'default'
showKeyModal.value = true
notify.success('API key created')
@@ -289,6 +305,25 @@ onMounted(() => {
Choose when this key expires. "Never" means the key will not expire.
</small>
</div>
+ <div class="form-group">
+ <label class="form-label">Scopes</label>
+ <div class="scope-list">
+ <label v-for="opt in scopeOptions" :key="opt.value" class="scope-option">
+ <input
+ type="checkbox"
+ :checked="newKeyScopes.includes(opt.value)"
+ @change="toggleScope(opt.value)"
+ />
+ <span class="scope-text">
+ <strong>{{ opt.label }}</strong>
+ <small>{{ opt.hint }}</small>
+ </span>
+ </label>
+ </div>
+ <small style="font-size: 12px; color: var(--text-muted); margin-top: 4px; display: block">
+ Scopes are fixed at creation. To change them, create a new key.
+ </small>
+ </div>
<div class="form-group">
<label class="form-label">Allowed IPs <span style="font-weight: 400; color: var(--text-muted)">(optional)</span></label>
<textarea
@@ -355,4 +390,10 @@ onMounted(() => {
.api-docs-text span { font-size: 13px; color: var(--text-secondary); }
.api-docs-links { display: flex; gap: 8px; flex-shrink: 0; }
.api-docs-links .btn { text-decoration: none; }
+.scope-list { display: flex; flex-direction: column; gap: 8px; }
+.scope-option { display: flex; align-items: flex-start; gap: 8px; cursor: pointer; }
+.scope-option input { margin-top: 3px; }
+.scope-text { display: flex; flex-direction: column; gap: 1px; }
+.scope-text strong { font-size: 13px; color: var(--text-primary); }
+.scope-text small { font-size: 12px; color: var(--text-muted); }
</style>