Skip to content

High performance, self-hosted, newsletter and mailing list manager with a modern dashboard. Single binary app.

Fix multiple, separate security/sanity issues.

Kailash Nadha7af420f47d4
diff --git a/cmd/bounce.go b/cmd/bounce.go
index 172cb6ab..7c4439ec 100644
--- a/cmd/bounce.go
+++ b/cmd/bounce.go
@@ -105,7 +105,7 @@ func (a *App) GetSubscriberBounces(c echo.Context) error {
subID := getID(c)
// Check if the user has access to at least one of the lists on the subscriber.
- if err := a.hasSubPerm(auth.GetUser(c), []int{subID}); err != nil {
+ if err := a.hasSubPerm(auth.GetUser(c), auth.PermTypeGet|auth.PermTypeManage, []int{subID}); err != nil {
return err
}
diff --git a/cmd/campaigns.go b/cmd/campaigns.go
index 58b67949..995dbaec 100644
--- a/cmd/campaigns.go
+++ b/cmd/campaigns.go
@@ -100,7 +100,7 @@ func (a *App) ViewNewCampaign(c echo.Context) error {
if raw := c.QueryParams()["list_id"]; len(raw) > 0 {
ids, _ := parseStringIDs(raw)
user := auth.GetUser(c)
- selIDs = user.GetPermittedListIDs(ids)
+ selIDs = user.GetPermittedListIDs(auth.PermTypeGet|auth.PermTypeManage, ids)
}
allLists, err := a.getViewableLists(c)
@@ -392,7 +392,7 @@ func (a *App) PreviewCampaign(c echo.Context) error {
return c.String(http.StatusOK, string(msg.Body()))
}
- return c.HTML(http.StatusOK, string(msg.Body()))
+ return renderSandboxedHTML(c, string(msg.Body()))
}
// PreviewCampaignArchive renders the public campaign archives page.
@@ -430,7 +430,7 @@ func (a *App) PreviewCampaignArchive(c echo.Context) error {
makeMsgTpl(a.i18n.T("public.errorTitle"), "", a.i18n.Ts("public.errorFetchingCampaign")))
}
- return c.HTML(http.StatusOK, string(msg.Body()))
+ return renderSandboxedHTML(c, string(msg.Body()))
}
// CampaignContent handles campaign content (body) format conversions.
@@ -459,7 +459,7 @@ func (a *App) CreateCampaign(c echo.Context) error {
// Filter lists against the current user's permitted lists.
user := auth.GetUser(c)
- o.ListIDs = user.FilterListsByPerm(auth.PermTypeGet|auth.PermTypeManage, o.ListIDs)
+ o.ListIDs = user.FilterListsByPerm(auth.PermTypeManage, o.ListIDs)
// If the campaign's 'opt-in', prepare a default message.
switch o.Type {
@@ -532,7 +532,7 @@ func (a *App) UpdateCampaign(c echo.Context) error {
// Filter lists against the current user's permitted lists.
user := auth.GetUser(c)
- o.ListIDs = user.FilterListsByPerm(auth.PermTypeGet|auth.PermTypeManage, o.ListIDs)
+ o.ListIDs = user.FilterListsByPerm(auth.PermTypeManage, o.ListIDs)
if c, err := a.validateCampaignFields(o); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
@@ -644,8 +644,8 @@ func (a *App) DeleteCampaigns(c echo.Context) error {
if !hasAllPerm {
// Either the user has campaigns:manage_all permissions and can manage all campaigns,
- // or the campaigns are filtered by the lists the user has get|manage access to.
- hasAllPerm, permittedLists = user.GetPermittedLists(auth.PermTypeGet | auth.PermTypeManage)
+ // or the campaigns are filtered by the lists the user has manage access to.
+ hasAllPerm, permittedLists = user.GetPermittedLists(auth.PermTypeManage)
}
var (
@@ -757,7 +757,7 @@ func (a *App) TestCampaign(c echo.Context) error {
user := auth.GetUser(c)
validSubs := subs[:0]
for _, s := range subs {
- if err := a.hasSubPerm(user, []int{s.ID}); err == nil {
+ if err := a.hasSubPerm(user, auth.PermTypeGet|auth.PermTypeManage, []int{s.ID}); err == nil {
validSubs = append(validSubs, s)
}
}
@@ -964,6 +964,7 @@ func (a *App) checkCampaignPerm(types auth.PermType, id int, c echo.Context) err
user := auth.GetUser(c)
perm := auth.PermCampaignsGet
+ listPerm := auth.PermTypeGet | auth.PermTypeManage
if types&auth.PermTypeGet != 0 {
// It's a get request and there's a blanket get all permission.
if user.HasPerm(auth.PermCampaignsGetAll) {
@@ -976,13 +977,14 @@ func (a *App) checkCampaignPerm(types auth.PermType, id int, c echo.Context) err
}
perm = auth.PermCampaignsManage
+ listPerm = auth.PermTypeManage
}
// There are no *_all campaign permissions. Instead, check if the user access
// blanket get_all/manage_all list permissions. If yes, then the user can access
// all campaigns. If there are no *_all permissions, then ensure that the
// campaign belongs to the lists that the user has access to.
- if hasAllPerm, permittedListIDs := user.GetPermittedLists(auth.PermTypeGet | auth.PermTypeManage); !hasAllPerm {
+ if hasAllPerm, permittedListIDs := user.GetPermittedLists(listPerm); !hasAllPerm {
if ok, err := a.core.CampaignHasLists(id, permittedListIDs); err != nil {
return err
} else if !ok {
diff --git a/cmd/handlers.go b/cmd/handlers.go
index d8a5c442..df8362f0 100644
--- a/cmd/handlers.go
+++ b/cmd/handlers.go
@@ -493,3 +493,9 @@ func trustedURLsToCORSOrigins(urls []string) []string {
return out
}
+
+// renderSandboxedHTML executes the HTML rendering handler with CSP sandboxing headers (for iframes).
+func renderSandboxedHTML(c echo.Context, body string) error {
+ c.Response().Header().Add("Content-Security-Policy", "sandbox allow-scripts allow-popups allow-popups-to-escape-sandbox")
+ return c.HTML(http.StatusOK, body)
+}
diff --git a/cmd/subscribers.go b/cmd/subscribers.go
index 018b3430..d61f8822 100644
--- a/cmd/subscribers.go
+++ b/cmd/subscribers.go
@@ -262,7 +262,7 @@ func (a *App) getViewSubscriber(c echo.Context) (models.Subscriber, error) {
user := auth.GetUser(c)
id := getID(c)
- if err := a.hasSubPerm(user, []int{id}); err != nil {
+ if err := a.hasSubPerm(user, auth.PermTypeGet|auth.PermTypeManage, []int{id}); err != nil {
return models.Subscriber{}, err
}
@@ -301,7 +301,7 @@ func (a *App) getSubscribers(c echo.Context, listID int) ([]models.Subscriber, m
// Filter the list IDs by permission.
var listIDs []int
if listID > 0 {
- listIDs = user.GetPermittedListIDs([]int{listID})
+ listIDs = user.GetPermittedListIDs(auth.PermTypeGet|auth.PermTypeManage, []int{listID})
} else {
ids, err := a.filterListQueryByPerm("list_id", params, user)
if err != nil {
@@ -346,7 +346,7 @@ func (a *App) GetSubscriber(c echo.Context) error {
// Check if the user has access to at least one of the lists on the subscriber.
id := getID(c)
- if err := a.hasSubPerm(user, []int{id}); err != nil {
+ if err := a.hasSubPerm(user, auth.PermTypeGet|auth.PermTypeManage, []int{id}); err != nil {
return err
}
@@ -367,7 +367,7 @@ func (a *App) GetSubscriberActivity(c echo.Context) error {
// Check if the user has access to at least one of the lists on the subscriber.
id := getID(c)
- if err := a.hasSubPerm(user, []int{id}); err != nil {
+ if err := a.hasSubPerm(user, auth.PermTypeGet|auth.PermTypeManage, []int{id}); err != nil {
return err
}
@@ -383,7 +383,7 @@ func (a *App) GetSubscriberActivity(c echo.Context) error {
// DeleteSubscriberActivity deletes a subscriber's campaign views or link clicks.
func (a *App) DeleteSubscriberActivity(c echo.Context) error {
id := getID(c)
- if err := a.hasSubPerm(auth.GetUser(c), []int{id}); err != nil {
+ if err := a.hasSubPerm(auth.GetUser(c), auth.PermTypeManage, []int{id}); err != nil {
return err
}
@@ -595,7 +595,7 @@ func (a *App) UpdateSubscriber(c echo.Context) error {
id := getID(c)
// Check if the user has access to at least one of the lists on the target subscriber.
- if err := a.hasSubPerm(user, []int{id}); err != nil {
+ if err := a.hasSubPerm(user, auth.PermTypeManage, []int{id}); err != nil {
return err
}
@@ -624,7 +624,7 @@ func (a *App) PatchSubscriber(c echo.Context) error {
// Check if the user has access to at least one of the lists on the target subscriber
// before fetching it. An empty PATCH body is otherwise a cross-scope PII read primitive.
- if err := a.hasSubPerm(user, []int{id}); err != nil {
+ if err := a.hasSubPerm(user, auth.PermTypeManage, []int{id}); err != nil {
return err
}
@@ -691,7 +691,7 @@ func (a *App) SubscriberSendOptin(c echo.Context) error {
// Fetch the subscriber.
id := getID(c)
- if err := a.hasSubPerm(user, []int{id}); err != nil {
+ if err := a.hasSubPerm(user, auth.PermTypeManage, []int{id}); err != nil {
return err
}
@@ -714,7 +714,7 @@ func (a *App) BlocklistSubscriber(c echo.Context) error {
// Update the subscribers in the DB.
id := getID(c)
- if err := a.hasSubPerm(user, []int{id}); err != nil {
+ if err := a.hasSubPerm(user, auth.PermTypeManage, []int{id}); err != nil {
return err
}
@@ -739,7 +739,7 @@ func (a *App) BlocklistSubscribers(c echo.Context) error {
a.i18n.Ts("globals.messages.errorInvalidIDs", "error", "ids"))
}
- if err := a.hasSubPerm(user, req.SubscriberIDs); err != nil {
+ if err := a.hasSubPerm(user, auth.PermTypeManage, req.SubscriberIDs); err != nil {
return err
}
@@ -786,7 +786,7 @@ func (a *App) ManageSubscriberLists(c echo.Context) error {
return echo.NewHTTPError(http.StatusBadRequest, a.i18n.T("subscribers.errorNoListsGiven"))
}
- if err := a.hasSubPerm(user, subIDs); err != nil {
+ if err := a.hasSubPerm(user, auth.PermTypeManage, subIDs); err != nil {
return err
}
@@ -824,7 +824,7 @@ func (a *App) DeleteSubscriber(c echo.Context) error {
// Delete the subscribers from the DB.
id := getID(c)
- if err := a.hasSubPerm(user, []int{id}); err != nil {
+ if err := a.hasSubPerm(user, auth.PermTypeManage, []int{id}); err != nil {
return err
}
@@ -850,7 +850,7 @@ func (a *App) DeleteSubscribers(c echo.Context) error {
a.i18n.Ts("globals.messages.errorInvalidIDs", "error", "ids"))
}
- if err := a.hasSubPerm(user, ids); err != nil {
+ if err := a.hasSubPerm(user, auth.PermTypeManage, ids); err != nil {
return err
}
@@ -888,7 +888,7 @@ func (a *App) DeleteSubscribersByQuery(c echo.Context) error {
}
// Filter list IDs against the current user's permitted lists.
- listIDs := user.GetPermittedListIDs(req.ListIDs)
+ listIDs := user.GetPermittedListIDs(auth.PermTypeManage, req.ListIDs)
// Delete the subscribers from the DB.
if err := a.core.DeleteSubscribersByQuery(req.Search, req.Query, listIDs, req.SubscriptionStatus, req.SubscriberStatus); err != nil {
@@ -923,7 +923,7 @@ func (a *App) BlocklistSubscribersByQuery(c echo.Context) error {
}
// Filter list IDs against the current user's permitted lists.
- listIDs := user.GetPermittedListIDs(req.ListIDs)
+ listIDs := user.GetPermittedListIDs(auth.PermTypeManage, req.ListIDs)
// Update the subscribers in the DB.
if err := a.core.BlocklistSubscribersByQuery(req.Search, req.Query, listIDs, req.SubscriptionStatus, req.SubscriberStatus); err != nil {
@@ -963,7 +963,7 @@ func (a *App) ManageSubscriberListsByQuery(c echo.Context) error {
}
// Filter lists against the current user's permitted lists.
- sourceListIDs := user.GetPermittedListIDs(req.ListIDs)
+ sourceListIDs := user.GetPermittedListIDs(auth.PermTypeManage, req.ListIDs)
targetListIDs := user.FilterListsByPerm(auth.PermTypeManage, req.TargetListIDs)
// Run the action in the DB.
@@ -991,7 +991,7 @@ func (a *App) DeleteSubscriberBounces(c echo.Context) error {
id := getID(c)
// Check if the user has access to at least one of the lists on the subscriber.
- if err := a.hasSubPerm(auth.GetUser(c), []int{id}); err != nil {
+ if err := a.hasSubPerm(auth.GetUser(c), auth.PermTypeManage, []int{id}); err != nil {
return err
}
@@ -1014,7 +1014,7 @@ func (a *App) ExportSubscriberData(c echo.Context) error {
id := getID(c)
// Check if the user has access to at least one of the lists on the subscriber.
- if err := a.hasSubPerm(auth.GetUser(c), []int{id}); err != nil {
+ if err := a.hasSubPerm(auth.GetUser(c), auth.PermTypeGet|auth.PermTypeManage, []int{id}); err != nil {
return err
}
@@ -1096,10 +1096,10 @@ func maskRestrictedSubLists(user auth.User, sub *models.Subscriber) {
// hasSubPerm checks whether the current user has permission to access the given list
// of subscriber IDs.
-func (a *App) hasSubPerm(u auth.User, subIDs []int) error {
- allPerm, listIDs := u.GetPermittedLists(auth.PermTypeGet | auth.PermTypeManage)
+func (a *App) hasSubPerm(u auth.User, types auth.PermType, subIDs []int) error {
+ allPerm, listIDs := u.GetPermittedLists(types)
- // User has blanket get_all|manage_all permission.
+ // User has the corresponding blanket list permission.
if allPerm {
return nil
}
@@ -1133,7 +1133,7 @@ func (a *App) filterListQueryByPerm(param string, qp url.Values, user auth.User)
listIDs = ids
}
- return user.GetPermittedListIDs(listIDs), nil
+ return user.GetPermittedListIDs(auth.PermTypeGet|auth.PermTypeManage, listIDs), nil
}
// formatSQLExp does basic sanitisation on arbitrary
diff --git a/cmd/templates.go b/cmd/templates.go
index dd319300..9b074815 100644
--- a/cmd/templates.go
+++ b/cmd/templates.go
@@ -147,7 +147,7 @@ func (a *App) PreviewTemplate(c echo.Context) error {
return err
}
- return c.HTML(http.StatusOK, string(out))
+ return renderSandboxedHTML(c, string(out))
}
// PreviewTemplateBody renders the HTML preview of a template given its type and body.
@@ -173,7 +173,7 @@ func (a *App) PreviewTemplateBody(c echo.Context) error {
return err
}
- return c.HTML(http.StatusOK, string(out))
+ return renderSandboxedHTML(c, string(out))
}
// CreateTemplate handles template creation.
diff --git a/internal/auth/models.go b/internal/auth/models.go
index af20e372..175da7cb 100644
--- a/internal/auth/models.go
+++ b/internal/auth/models.go
@@ -281,12 +281,12 @@ func (u *User) FilterListsByPerm(types PermType, listIDs []int) []int {
// If the user has full list management permission,
// no further checks are required.
if get {
- if _, ok := u.PermissionsMap[PermListGetAll]; ok {
+ if u.HasPerm(PermListGetAll) {
return listIDs
}
}
if manage {
- if _, ok := u.PermissionsMap[PermListManageAll]; ok {
+ if u.HasPerm(PermListManageAll) {
return listIDs
}
}
@@ -316,18 +316,21 @@ func (u *User) FilterListsByPerm(types PermType, listIDs []int) []int {
// IDs are requested (empty input), it falls back to the user's
// permitted list IDs if any. This is useful for endpoints which accept a few IDs
// or the lack of which implies "all".
-func (u *User) GetPermittedListIDs(listIDs []int) []int {
+func (u *User) GetPermittedListIDs(types PermType, listIDs []int) []int {
if len(listIDs) > 0 {
- if ids := u.FilterListsByPerm(PermTypeGet|PermTypeManage, listIDs); len(ids) > 0 {
+ if ids := u.FilterListsByPerm(types, listIDs); len(ids) > 0 {
return ids
}
return []int{-1}
}
- if _, ok := u.PermissionsMap[PermSubscribersGetAll]; !ok {
- if len(u.GetListIDs) > 0 {
- return u.GetListIDs
- }
- return []int{-1}
+
+ if types&PermTypeGet != 0 && u.HasPerm(PermSubscribersGetAll) {
+ return nil
+ }
+ if all, ids := u.GetPermittedLists(types); all {
+ return nil
+ } else if len(ids) > 0 {
+ return ids
}
- return listIDs
+ return []int{-1}
}
diff --git a/internal/core/subscribers.go b/internal/core/subscribers.go
index 9dd45dcc..d7665e0b 100644
--- a/internal/core/subscribers.go
+++ b/internal/core/subscribers.go
@@ -497,7 +497,7 @@ func (c *Core) BlocklistSubscribers(subIDs []int) error {
// BlocklistSubscribersByQuery blocklists the given list of subscribers.
func (c *Core) BlocklistSubscribersByQuery(searchStr, queryExp string, listIDs []int, subStatus, subscriberStatus string) error {
- if err := c.q.ExecSubQueryTpl(searchStr, sanitizeSQLExp(queryExp), c.q.BlocklistSubscribersByQuery, listIDs, c.db, subStatus, subscriberStatus); err != nil {
+ if err := c.execSubQueryTpl(searchStr, sanitizeSQLExp(queryExp), c.q.BlocklistSubscribersByQuery, listIDs, subStatus, subscriberStatus); err != nil {
c.log.Printf("error blocklisting subscribers: %v", err)
return echo.NewHTTPError(http.StatusInternalServerError,
c.i18n.Ts("subscribers.errorBlocklisting", "error", pqErrMsg(err)))
@@ -526,7 +526,7 @@ func (c *Core) DeleteSubscribers(subIDs []int, subUUIDs []string) error {
// DeleteSubscribersByQuery deletes subscribers by a given arbitrary query expression.
func (c *Core) DeleteSubscribersByQuery(searchStr, queryExp string, listIDs []int, subStatus, subscriberStatus string) error {
- err := c.q.ExecSubQueryTpl(searchStr, sanitizeSQLExp(queryExp), c.q.DeleteSubscribersByQuery, listIDs, c.db, subStatus, subscriberStatus)
+ err := c.execSubQueryTpl(searchStr, sanitizeSQLExp(queryExp), c.q.DeleteSubscribersByQuery, listIDs, subStatus, subscriberStatus)
if err != nil {
c.log.Printf("error deleting subscribers: %v", err)
return echo.NewHTTPError(http.StatusInternalServerError,
@@ -709,3 +709,64 @@ func traverseQueryPlan(node map[string]any, tables map[string]struct{}) {
}
}
}
+
+// compileSubscriberQueryTpl takes an arbitrary WHERE expressions
+// to filter subscribers from the subscribers table and prepares a query
+// using the raw `query-subscribers-template` template. It sanitizes the
+// query by dry-running it as a read only query.
+func (c *Core) compileSubscriberQueryTpl(searchStr, queryExp string, subStatus, subscriberStatus string) (string, error) {
+ // There's an arbitrary query condition.
+ cond := "TRUE"
+ if queryExp != "" {
+ cond = queryExp
+ }
+
+ // Validate before executing the dry run.
+ stmt := strings.ReplaceAll(c.q.QuerySubscribersTpl, "%query%", cond)
+ if err := validateQueryTables(c.db, stmt, allowedSubQueryTables, true, pq.Int64Array{}, subStatus, searchStr, subscriberStatus); err != nil {
+ return "", err
+ }
+
+ tx, err := c.db.BeginTxx(context.Background(), &sql.TxOptions{ReadOnly: true})
+ if err != nil {
+ return "", err
+ }
+ defer tx.Rollback()
+
+ // Perform the dry run.
+ if _, err := tx.Exec(stmt, true, pq.Int64Array{}, subStatus, searchStr, subscriberStatus); err != nil {
+ return "", err
+ }
+
+ return stmt, nil
+}
+
+// execSubQueryTpl takes an arbitrary WHERE expressions and a subscriber
+// query template that depends on the filter (eg: delete by query, blocklist by query etc.)
+// combines and executes them.
+func (c *Core) execSubQueryTpl(searchStr, queryExp, baseQueryTpl string, listIDs []int, subStatus, subscriberStatus string, args ...any) error {
+ queryExp, subStatus = models.ApplyOrphanFilter(queryExp, subStatus)
+
+ // Perform a dry run.
+ filterExp, err := c.compileSubscriberQueryTpl(searchStr, queryExp, subStatus, subscriberStatus)
+ if err != nil {
+ return err
+ }
+
+ if len(listIDs) == 0 {
+ listIDs = []int{}
+ }
+
+ // Insert the subscriber filter query into the target query.
+ stmt := strings.ReplaceAll(baseQueryTpl, "%query%", filterExp)
+
+ // First argument is the boolean indicating if the query is a dry run.
+ a := append([]any{false, pq.Array(listIDs), subStatus, searchStr, subscriberStatus}, args...)
+
+ // Execute the query on the DB.
+ if _, err := c.db.Exec(stmt, a...); err != nil {
+ return err
+ }
+
+ return nil
+}
diff --git a/internal/core/subscriptions.go b/internal/core/subscriptions.go
index d30edd22..6e25e97e 100644
--- a/internal/core/subscriptions.go
+++ b/internal/core/subscriptions.go
@@ -40,7 +40,7 @@ func (c *Core) AddSubscriptionsByQuery(searchStr, queryExp string, sourceListIDs
sourceListIDs = []int{}
}
- err := c.q.ExecSubQueryTpl(searchStr, queryExp, c.q.AddSubscribersToListsByQuery, sourceListIDs, c.db, subStatus, subscriberStatus, pq.Array(targetListIDs), status)
+ err := c.execSubQueryTpl(searchStr, queryExp, c.q.AddSubscribersToListsByQuery, sourceListIDs, subStatus, subscriberStatus, pq.Array(targetListIDs), status)
if err != nil {
c.log.Printf("error adding subscriptions by query: %v", err)
return echo.NewHTTPError(http.StatusInternalServerError,
@@ -69,7 +69,7 @@ func (c *Core) DeleteSubscriptionsByQuery(searchStr, queryExp string, sourceList
sourceListIDs = []int{}
}
- err := c.q.ExecSubQueryTpl(searchStr, queryExp, c.q.DeleteSubscriptionsByQuery, sourceListIDs, c.db, subStatus, subscriberStatus, pq.Array(targetListIDs))
+ err := c.execSubQueryTpl(searchStr, queryExp, c.q.DeleteSubscriptionsByQuery, sourceListIDs, subStatus, subscriberStatus, pq.Array(targetListIDs))
if err != nil {
c.log.Printf("error deleting subscriptions by query: %v", err)
return echo.NewHTTPError(http.StatusInternalServerError,
@@ -97,7 +97,7 @@ func (c *Core) UnsubscribeListsByQuery(searchStr, queryExp string, sourceListIDs
sourceListIDs = []int{}
}
- err := c.q.ExecSubQueryTpl(searchStr, queryExp, c.q.UnsubscribeSubscribersFromListsByQuery, sourceListIDs, c.db, subStatus, subscriberStatus, pq.Array(targetListIDs))
+ err := c.execSubQueryTpl(searchStr, queryExp, c.q.UnsubscribeSubscribersFromListsByQuery, sourceListIDs, subStatus, subscriberStatus, pq.Array(targetListIDs))
if err != nil {
c.log.Printf("error unsubscribing from lists by query: %v", err)
return echo.NewHTTPError(http.StatusInternalServerError,
diff --git a/models/campaigns.go b/models/campaigns.go
index 74fa2a5d..a0e94fac 100644
--- a/models/campaigns.go
+++ b/models/campaigns.go
@@ -78,15 +78,15 @@ type Campaign struct {
ArchiveMeta json.RawMessage `db:"archive_meta" json:"archive_meta"`
// TemplateBody is joined in from templates by the next-campaigns query.
- TemplateBody string `db:"template_body" json:"-"`
- ArchiveTemplateBody string `db:"archive_template_body" json:"-"`
- Tpl *template.Template `json:"-"`
- SubjectTpl *txttpl.Template `json:"-"`
- FromEmailTpl *txttpl.Template `json:"-"`
- AltBodyTpl *template.Template `json:"-"`
+ TemplateBody string `db:"template_body" json:"-"`
+ ArchiveTemplateBody string `db:"archive_template_body" json:"-"`
+ Tpl *tplRenderer `json:"-"`
+ SubjectTpl *tplRenderer `json:"-"`
+ FromEmailTpl *tplRenderer `json:"-"`
+ AltBodyTpl *tplRenderer `json:"-"`
// HeaderTpls holds optionally {{ templated }} campaign headers.
- HeaderTpls []map[string]*txttpl.Template `json:"-"`
+ HeaderTpls []map[string]*tplRenderer `json:"-"`
// List of media (attachment) IDs obtained from the next-campaign query
// while sending a campaign.
@@ -239,7 +239,7 @@ func (c *Campaign) CompileTemplate(f template.FuncMap) error {
if err != nil {
return fmt.Errorf("error inserting child template: %v", err)
}
- c.Tpl = out
+ c.Tpl = &tplRenderer{out}
if HasTplExpr(c.AltBody.String) {
b := c.AltBody.String
@@ -250,7 +250,7 @@ func (c *Campaign) CompileTemplate(f template.FuncMap) error {
if err != nil {
return fmt.Errorf("error compiling alt plaintext message: %v", err)
}
- c.AltBodyTpl = bTpl
+ c.AltBodyTpl = &tplRenderer{bTpl}
}
// Rebuild header templates in case the campaign is being recompiled.
@@ -266,10 +266,10 @@ func (c *Campaign) CompileTemplate(f template.FuncMap) error {
}
if c.HeaderTpls == nil {
- c.HeaderTpls = make([]map[string]*txttpl.Template, len(c.Headers))
+ c.HeaderTpls = make([]map[string]*tplRenderer, len(c.Headers))
}
if c.HeaderTpls[i] == nil {
- c.HeaderTpls[i] = make(map[string]*txttpl.Template)
+ c.HeaderTpls[i] = make(map[string]*tplRenderer)
}
c.HeaderTpls[i][hdr] = tpl
}
@@ -278,7 +278,7 @@ func (c *Campaign) CompileTemplate(f template.FuncMap) error {
return nil
}
-func compileTxtTpl(label, val string, f template.FuncMap) (*txttpl.Template, error) {
+func compileTxtTpl(label, val string, f template.FuncMap) (*tplRenderer, error) {
if !HasTplExpr(val) {
return nil, nil
}
@@ -292,7 +292,7 @@ func compileTxtTpl(label, val string, f template.FuncMap) (*txttpl.Template, err
return nil, fmt.Errorf("error compiling %s: %v", label, err)
}
- return tpl, nil
+ return &tplRenderer{tpl}, nil
}
// ConvertContent converts a campaign's body from one format to another,
diff --git a/models/messages.go b/models/messages.go
index f502dabe..3d99cdab 100644
--- a/models/messages.go
+++ b/models/messages.go
@@ -3,7 +3,6 @@ package models
import (
"bytes"
"fmt"
- "html/template"
"net/textproto"
txttpl "text/template"
)
@@ -69,9 +68,7 @@ type TxMessage struct {
// File attachments added from multi-part form data.
Attachments []Attachment `json:"-"`
- Body []byte `json:"-"`
- Tpl *template.Template `json:"-"`
- SubjectTpl *txttpl.Template `json:"-"`
+ Body []byte `json:"-"`
}
func (m *TxMessage) Render(sub Subscriber, tpl *Template, funcs txttpl.FuncMap) error {
@@ -104,7 +101,7 @@ func (m *TxMessage) Render(sub Subscriber, tpl *Template, funcs txttpl.FuncMap)
// Was a subject provided in the message?
var (
- subjTpl *txttpl.Template
+ subjTpl *tplRenderer
subject = m.Subject
)
if subject != "" {
@@ -114,7 +111,7 @@ func (m *TxMessage) Render(sub Subscriber, tpl *Template, funcs txttpl.FuncMap)
if err != nil {
return fmt.Errorf("error compiling subject: %v", err)
}
- subjTpl = s
+ subjTpl = &tplRenderer{s}
}
} else {
// Use the subject from the template.
diff --git a/models/queries.go b/models/queries.go
index 9eaa8eed..f87d96c9 100644
--- a/models/queries.go
+++ b/models/queries.go
@@ -1,13 +1,6 @@
package models
-import (
- "context"
- "database/sql"
- "strings"
-
- "github.com/jmoiron/sqlx"
- "github.com/lib/pq"
-)
+import "github.com/jmoiron/sqlx"
// Queries contains all prepared SQL queries.
type Queries struct {
@@ -158,62 +151,6 @@ type Queries struct {
DeleteListPermission *sqlx.Stmt `query:"delete-list-permission"`
}
-// compileSubscriberQueryTpl takes an arbitrary WHERE expressions
-// to filter subscribers from the subscribers table and prepares a query
-// out of it using the raw `query-subscribers-template` query template.
-// While doing this, a readonly transaction is created and the query is
-// dry run on it to ensure that it is indeed readonly.
-func (q *Queries) compileSubscriberQueryTpl(searchStr, queryExp string, db *sqlx.DB, subStatus, subscriberStatus string) (string, error) {
- tx, err := db.BeginTxx(context.Background(), &sql.TxOptions{ReadOnly: true})
- if err != nil {
- return "", err
- }
- defer tx.Rollback()
-
- // There's an arbitrary query condition.
- cond := "TRUE"
- if queryExp != "" {
- cond = queryExp
- }
-
- // Perform the dry run.
- stmt := strings.ReplaceAll(q.QuerySubscribersTpl, "%query%", cond)
- if _, err := tx.Exec(stmt, true, pq.Int64Array{}, subStatus, searchStr, subscriberStatus); err != nil {
- return "", err
- }
-
- return stmt, nil
-}
-
-// compileSubscriberQueryTpl takes an arbitrary WHERE expressions and a subscriber
-// query template that depends on the filter (eg: delete by query, blocklist by query etc.)
-// combines and executes them.
-func (q *Queries) ExecSubQueryTpl(searchStr, queryExp, baseQueryTpl string, listIDs []int, db *sqlx.DB, subStatus, subscriberStatus string, args ...any) error {
- queryExp, subStatus = ApplyOrphanFilter(queryExp, subStatus)
-
- // Perform a dry run.
- filterExp, err := q.compileSubscriberQueryTpl(searchStr, queryExp, db, subStatus, subscriberStatus)
- if err != nil {
- return err
- }
-
- if len(listIDs) == 0 {
- listIDs = []int{}
- }
-
- // Insert the subscriber filter query into the target query.
- stmt := strings.ReplaceAll(baseQueryTpl, "%query%", filterExp)
-
- // First argument is the boolean indicating if the query is a dry run.
- a := append([]any{false, pq.Array(listIDs), subStatus, searchStr, subscriberStatus}, args...)
-
- // Execute the query on the DB.
- if _, err := db.Exec(stmt, a...); err != nil {
- return err
- }
- return nil
-}
-
// ApplyOrphanFilter handles the special subscription_status value "none", which
// filters orphan subscribers (no list subscriptions).
func ApplyOrphanFilter(cond, subStatus string) (string, string) {
diff --git a/models/templates.go b/models/templates.go
index 0a820df5..68c4e0c0 100644
--- a/models/templates.go
+++ b/models/templates.go
@@ -3,6 +3,7 @@ package models
import (
"fmt"
"html/template"
+ "io"
txttpl "text/template"
"time"
@@ -17,6 +18,17 @@ const (
TemplateTypeTx = "tx"
)
+// tplRenderer exposes only execution and hides other unrelated methods.
+type tplRenderer struct {
+ tpl interface {
+ ExecuteTemplate(io.Writer, string, any) error
+ }
+}
+
+func (t *tplRenderer) ExecuteTemplate(w io.Writer, name string, data any) error {
+ return t.tpl.ExecuteTemplate(w, name, data)
+}
+
// Template represents a reusable e-mail template.
type Template struct {
Base
@@ -30,9 +42,9 @@ type Template struct {
IsDefault bool `db:"is_default" json:"is_default"`
// Only relevant to tx (transactional) templates.
- SubjectTpl *txttpl.Template `json:"-"`
- Tpl *template.Template `json:"-"`
- Attachments []Attachment `json:"-"`
+ SubjectTpl *tplRenderer `json:"-"`
+ Tpl *tplRenderer `json:"-"`
+ Attachments []Attachment `json:"-"`
}
// Compile compiles a template body and subject (only for tx templates) and
@@ -42,7 +54,7 @@ func (t *Template) Compile(f template.FuncMap) error {
if err != nil {
return fmt.Errorf("error compiling transactional template: %v", err)
}
- t.Tpl = tpl
+ t.Tpl = &tplRenderer{tpl}
// If the subject line has a template string, compile it.
if HasTplExpr(t.Subject) {
@@ -52,7 +64,7 @@ func (t *Template) Compile(f template.FuncMap) error {
if err != nil {
return fmt.Errorf("error compiling subject: %v", err)
}
- t.SubjectTpl = subjTpl
+ t.SubjectTpl = &tplRenderer{subjTpl}
}
return nil
diff --git a/static/admin/partials/campaign-preview.html b/static/admin/partials/campaign-preview.html
index 68249fd5..2d509f23 100644
--- a/static/admin/partials/campaign-preview.html
+++ b/static/admin/partials/campaign-preview.html
@@ -11,7 +11,7 @@
<input type="hidden" name="archive_meta" :value="preview.archiveMeta" />
<input type="hidden" name="body" :value="preview.body" />
</form>
- <iframe id="iframe" name="campaign-preview-frame" x-ref="previewFrame" title="{{ .L.T "campaigns.preview" }}" @load="preview.loading = false"></iframe>
+ <iframe id="iframe" name="campaign-preview-frame" x-ref="previewFrame" sandbox="allow-scripts allow-popups allow-popups-to-escape-sandbox" title="{{ .L.T "campaigns.preview" }}" @load="preview.loading = false"></iframe>
</section>
<footer class="dialog-foot">
<button type="button" class="outline" autofocus @click="$refs.previewDialog.close()">{{ .L.T "globals.buttons.close" }}</button>
diff --git a/static/admin/partials/template-preview.html b/static/admin/partials/template-preview.html
index 04aa84c2..db058703 100644
--- a/static/admin/partials/template-preview.html
+++ b/static/admin/partials/template-preview.html
@@ -9,7 +9,7 @@
<input type="hidden" name="template_type" :value="preview.templateType" />
<input type="hidden" name="body" :value="preview.body" />
</form>
- <iframe id="iframe" name="template-preview-frame" x-ref="previewFrame" title="{{ .L.T "templates.preview" }}" @load="preview.loading = false"></iframe>
+ <iframe id="iframe" name="template-preview-frame" x-ref="previewFrame" sandbox="allow-scripts allow-popups allow-popups-to-escape-sandbox" title="{{ .L.T "templates.preview" }}" @load="preview.loading = false"></iframe>
</section>
<footer class="dialog-foot align-right">
<button type="button" class="outline" autofocus @click="$refs.previewDialog.close()">{{ .L.T "globals.buttons.close" }}</button>