Self-hosted email delivery platform that enables applications to send emails via HTTP APIs while handling SMTP delivery, templates, storage, security, and analytics. Fully self-hostable alternative to services like SendGrid or Mailgun.
Go email-relayemail-routinghttp-to-smtpmail-deliverymailchimp-alternativemailgun-alternativemailsendermailservermailtemplatemailtestpostmark-alternativesend-emailsendgrid-alternativesendmailtransactional-emailtransactional-outbox
fix(templates): enforce workspace scope
Jonas Kanindad72bc2258c2b
diff --git a/internal/handlers/template_handler.go b/internal/handlers/template_handler.goindex dd5bc40..22d30bb 100644--- a/internal/handlers/template_handler.go+++ b/internal/handlers/template_handler.go@@ -210,9 +210,8 @@ func (h *TemplateHandler) Preview(c *okapi.Context, req *PreviewTemplateRequest)TextTemplate: req.Body.TextTemplate,}- // Resolve the linked stylesheet for previewif req.Body.StyleSheetID != nil && *req.Body.StyleSheetID > 0 {- ss, err := h.stylesheetRepo.FindByID(*req.Body.StyleSheetID)+ ss, err := h.stylesheetRepo.FindByIDInScope(getScope(c), *req.Body.StyleSheetID)if err != nil {return c.AbortNotFound("stylesheet not found")}diff --git a/internal/handlers/template_version_handler.go b/internal/handlers/template_version_handler.goindex 0d1ada7..9cbcded 100644--- a/internal/handlers/template_version_handler.go+++ b/internal/handlers/template_version_handler.go@@ -26,8 +26,9 @@ import ()type TemplateVersionHandler struct {- templateRepo *repositories.TemplateRepository- versionRepo *repositories.TemplateVersionRepository+ templateRepo *repositories.TemplateRepository+ versionRepo *repositories.TemplateVersionRepository+ stylesheetRepo *repositories.StyleSheetRepository}type ListVersionsRequest struct {TemplateID int `param:"id"`@@ -58,13 +59,25 @@ type DeleteVersionRequest struct {func NewTemplateVersionHandler(templateRepo *repositories.TemplateRepository,versionRepo *repositories.TemplateVersionRepository,+ stylesheetRepo *repositories.StyleSheetRepository,) *TemplateVersionHandler {return &TemplateVersionHandler{- templateRepo: templateRepo,- versionRepo: versionRepo,+ templateRepo: templateRepo,+ versionRepo: versionRepo,+ stylesheetRepo: stylesheetRepo,}}+func (h *TemplateVersionHandler) resolveStyleSheetID(scope repositories.ResourceScope, id *uint) (*uint, error) {+ if id == nil || *id == 0 {+ return nil, nil+ }+ if _, err := h.stylesheetRepo.FindByIDInScope(scope, *id); err != nil {+ return nil, err+ }+ return id, nil+}+func (h *TemplateVersionHandler) List(c *okapi.Context, req *ListVersionsRequest) error {tmpl, err := h.templateRepo.FindByID(uint(req.TemplateID))if err != nil || !ownsResource(c, tmpl.UserID, tmpl.WorkspaceID) {@@ -88,6 +101,11 @@ func (h *TemplateVersionHandler) Create(c *okapi.Context, req *CreateVersionRequreturn c.AbortNotFound("template not found")}+ styleSheetID, err := h.resolveStyleSheetID(getScope(c), req.Body.StyleSheetID)+ if err != nil {+ return c.AbortNotFound("stylesheet not found")+ }+nextVersion, err := h.versionRepo.NextVersion(tmpl.ID)if err != nil {return c.AbortInternalServerError("failed to determine next version")@@ -96,7 +114,7 @@ func (h *TemplateVersionHandler) Create(c *okapi.Context, req *CreateVersionRequv := &models.TemplateVersion{TemplateID: tmpl.ID,Version: nextVersion,- StyleSheetID: req.Body.StyleSheetID,+ StyleSheetID: styleSheetID,SampleData: req.Body.SampleData,}@@ -122,7 +140,11 @@ func (h *TemplateVersionHandler) Update(c *okapi.Context, req *UpdateVersionRequreturn c.AbortNotFound("version not found")}- v.StyleSheetID = req.Body.StyleSheetID+ styleSheetID, err := h.resolveStyleSheetID(getScope(c), req.Body.StyleSheetID)+ if err != nil {+ return c.AbortNotFound("stylesheet not found")+ }+ v.StyleSheetID = styleSheetIDif err := h.versionRepo.Update(v); err != nil {return c.AbortInternalServerError("failed to update version")diff --git a/internal/routes/routes.go b/internal/routes/routes.goindex 6d552be..e2cb09d 100644--- a/internal/routes/routes.go+++ b/internal/routes/routes.go@@ -243,7 +243,7 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *cemail: handlers.NewEmailHandler(emailService, emailRepo, bus, statsCache),apiKey: handlers.NewAPIKeyHandler(apiKeyService, apiKeyRepo, userSettingRepo, auditLogger),template: handlers.NewTemplateHandler(templateRepo, stylesheetRepo, versionRepo, localizationRepo, languageRepo, emailService),- version: handlers.NewTemplateVersionHandler(templateRepo, versionRepo),+ version: handlers.NewTemplateVersionHandler(templateRepo, versionRepo, stylesheetRepo),localization: handlers.NewTemplateLocalizationHandler(templateRepo, versionRepo, localizationRepo, stylesheetRepo),language: handlers.NewLanguageHandler(languageRepo),stylesheet: handlers.NewStyleSheetHandler(stylesheetRepo),diff --git a/internal/storage/repositories/stylesheet_repo.go b/internal/storage/repositories/stylesheet_repo.goindex 97a287f..27b68d7 100644--- a/internal/storage/repositories/stylesheet_repo.go+++ b/internal/storage/repositories/stylesheet_repo.go@@ -80,6 +80,14 @@ func (r *StyleSheetRepository) FindByUserID(userID uint, limit, offset int) ([]mreturn sheets, total, nil}+func (r *StyleSheetRepository) FindByIDInScope(scope ResourceScope, id uint) (*models.StyleSheet, error) {+ var ss models.StyleSheet+ if err := ApplyScope(r.db, scope).Where("id = ?", id).First(&ss).Error; err != nil {+ return nil, err+ }+ return &ss, nil+}+func (r *StyleSheetRepository) FindByNameInScope(scope ResourceScope, name string) (*models.StyleSheet, error) {var ss models.StyleSheetif err := ApplyScope(r.db, scope).Where("name = ?", name).First(&ss).Error; err != nil {diff --git a/internal/storage/repositories/stylesheet_repo_test.go b/internal/storage/repositories/stylesheet_repo_test.gonew file mode 100644index 0000000..ad7bcbd--- /dev/null+++ b/internal/storage/repositories/stylesheet_repo_test.go@@ -0,0 +1,112 @@+/*+ * 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 repositories++import (+ "errors"+ "os"+ "testing"++ "github.com/goposta/posta/internal/models"+ "gorm.io/driver/postgres"+ "gorm.io/gorm"+ "gorm.io/gorm/logger"+)++func testDB(t *testing.T) *gorm.DB {+ t.Helper()+ dsn := os.Getenv("TEST_DATABASE_DSN")+ if dsn == "" {+ dsn = "host=localhost user=posta password=posta dbname=posta port=5432 sslmode=disable"+ }+ db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})+ if err != nil {+ t.Skipf("skipping: no test database available: %v", err)+ }+ if err := db.AutoMigrate(&models.User{}, &models.StyleSheet{}); err != nil {+ t.Skipf("skipping: cannot migrate test schema: %v", err)+ }+ return db+}++func uintPtr(v uint) *uint { return &v }++func createUser(t *testing.T, tx *gorm.DB, email string) uint {+ t.Helper()+ u := &models.User{Name: "test", Email: email, PasswordHash: "x"}+ if err := tx.Create(u).Error; err != nil {+ t.Fatalf("create user %s: %v", email, err)+ }+ return u.ID+}++func TestFindByIDInScope_RejectsForeignWorkspace(t *testing.T) {+ db := testDB(t)++ tx := db.Begin()+ t.Cleanup(func() { tx.Rollback() })++ repo := NewStyleSheetRepository(tx)++ userA := createUser(t, tx, "[email protected]")+ userB := createUser(t, tx, "[email protected]")++ const wsA, wsB uint = 90001, 90002+ owned := &models.StyleSheet{UserID: userA, WorkspaceID: uintPtr(wsA), Name: "owned", CSS: "body{color:red}"}+ foreign := &models.StyleSheet{UserID: userB, WorkspaceID: uintPtr(wsB), Name: "foreign", CSS: "body{color:blue}"}+ if err := repo.Create(owned); err != nil {+ t.Fatalf("create owned: %v", err)+ }+ if err := repo.Create(foreign); err != nil {+ t.Fatalf("create foreign: %v", err)+ }++ scopeA := ResourceScope{UserID: userA, WorkspaceID: uintPtr(wsA)}++ got, err := repo.FindByIDInScope(scopeA, owned.ID)+ if err != nil {+ t.Fatalf("expected in-scope stylesheet to resolve, got error: %v", err)+ }+ if got.ID != owned.ID {+ t.Fatalf("expected stylesheet %d, got %d", owned.ID, got.ID)+ }++ if _, err := repo.FindByIDInScope(scopeA, foreign.ID); !errors.Is(err, gorm.ErrRecordNotFound) {+ t.Fatalf("expected ErrRecordNotFound for foreign stylesheet, got: %v", err)+ }+}++func TestFindByIDInScope_PersonalScopeIsolated(t *testing.T) {+ db := testDB(t)++ tx := db.Begin()+ t.Cleanup(func() { tx.Rollback() })++ repo := NewStyleSheetRepository(tx)++ userID := createUser(t, tx, "[email protected]")+ wsOwned := &models.StyleSheet{UserID: userID, WorkspaceID: uintPtr(90003), Name: "ws", CSS: "a{}"}+ if err := repo.Create(wsOwned); err != nil {+ t.Fatalf("create: %v", err)+ }++ personal := ResourceScope{UserID: userID}+ if _, err := repo.FindByIDInScope(personal, wsOwned.ID); !errors.Is(err, gorm.ErrRecordNotFound) {+ t.Fatalf("expected personal scope to not resolve workspace stylesheet, got: %v", err)+ }+}