Open platform to collect and prioritize feedback
fix(email): escape user-supplied names and titles in notification emails
Matt Robertse6729d2cf8aa
diff --git a/app/pkg/tpl/funcs.go b/app/pkg/tpl/funcs.goindex 03595e3f9..6423222bd 100644--- a/app/pkg/tpl/funcs.go+++ b/app/pkg/tpl/funcs.go@@ -19,6 +19,11 @@ var templateFunctions = map[string]any{"stripHtml": func(input string) string {return strictHtmlPolicy.Sanitize(input)},+ // escapeHtml escapes plain text so it can be safely interpolated into a+ // string that is later marked as HTML (e.g. a translation piped to "html").+ "escapeHtml": func(input string) string {+ return template.HTMLEscapeString(input)+ },"html": func(input string) template.HTML {return template.HTML(input)},diff --git a/app/services/email/email_test.go b/app/services/email/email_test.goindex f1d6f0905..90223eec3 100644--- a/app/services/email/email_test.go+++ b/app/services/email/email_test.go@@ -2,6 +2,7 @@ package email_testimport ("context"+ "strings""testing""github.com/getfider/fider/app/models/dto"@@ -24,6 +25,39 @@ func TestRenderMessage_SubjectUnescapesHTMLEntities(t *testing.T) {Expect(message.Subject).Equals(`Message to: Encontrar+se "quoted" & <tagged>`)}+func TestRenderMessage_EscapesPlainTextParams(t *testing.T) {+ RegisterT(t)++ // User and tenant controlled values are interpolated into translated+ // strings that are rendered as raw HTML, so they must be HTML-escaped+ // (not stripped) before interpolation.+ raw := "<b>x</b> & <3"+ escaped := "<b>x</b> & <3"++ testCases := []struct {+ template string+ params dto.Props+ expected int+ }{+ {"new_post", dto.Props{"userName": raw, "title": raw}, 2},+ {"new_comment", dto.Props{"messageLocaleString": "email.new_comment.text", "userName": raw, "title": raw}, 2},+ {"new_comment", dto.Props{"messageLocaleString": "email.new_mention.text", "userName": raw, "title": raw}, 2},+ {"change_status", dto.Props{"title": raw, "status": raw}, 2},+ {"change_status", dto.Props{"title": raw, "duplicate": "<a href='#'>original</a>"}, 1},+ {"delete_post", dto.Props{"title": raw}, 1},+ {"signin_email", dto.Props{"siteName": raw, "link": ""}, 1},+ {"delete_account_requested", dto.Props{"tenantName": raw, "scheduledAt": raw, "cancelLink": ""}, 2},+ {"delete_account_completed", dto.Props{"tenantName": raw, "subdomain": raw}, 2},+ {"change_emailaddress_email", dto.Props{"name": raw, "oldEmail": raw, "newEmail": raw, "link": ""}, 3},+ }++ for _, testCase := range testCases {+ message := email.RenderMessage(context.Background(), testCase.template, email.NoReply, testCase.params)+ Expect(strings.Count(message.Body, escaped)).Equals(testCase.expected)+ Expect(strings.Contains(message.Body, "<b>")).IsFalse()+ }+}+func TestRenderMessage(t *testing.T) {RegisterT(t)diff --git a/app/tasks/new_comment_test.go b/app/tasks/new_comment_test.goindex 98d8d5523..af448f4e6 100644--- a/app/tasks/new_comment_test.go+++ b/app/tasks/new_comment_test.go@@ -3,6 +3,7 @@ package tasks_testimport ("context""html/template"+ "strings""testing""time"@@ -17,6 +18,7 @@ import (. "github.com/getfider/fider/app/pkg/assert""github.com/getfider/fider/app/pkg/bus""github.com/getfider/fider/app/pkg/mock"+ "github.com/getfider/fider/app/services/email""github.com/getfider/fider/app/services/email/emailmock""github.com/getfider/fider/app/tasks")@@ -406,3 +408,60 @@ func TestNotifyAboutUpdatedComment_UserAlreadyMentioned(t *testing.T) {Expect(addNewNotification).IsNil()}++func TestNotifyAboutNewCommentTask_EscapesAuthorNameAndTitleInEmail(t *testing.T) {+ RegisterT(t)+ bus.Init(emailmock.Service{})++ bus.AddHandler(func(ctx context.Context, c *cmd.AddNewNotification) error {+ return nil+ })++ bus.AddHandler(func(ctx context.Context, q *query.GetMentionNotifications) error {+ q.Result = []*entity.MentionNotification{}+ return nil+ })++ bus.AddHandler(func(ctx context.Context, q *query.GetActiveSubscribers) error {+ if q.Event.UserSettingsKeyName == "event_notification_new_comment" {+ q.Result = []*entity.User{+ mock.JonSnow,+ }+ } else {+ q.Result = []*entity.User{}+ }+ return nil+ })++ bus.AddHandler(func(ctx context.Context, c *cmd.TriggerWebhooks) error {+ return nil+ })++ author := *mock.AryaStark+ author.Name = "<a href=//example.com><h1>View new Update</a>"++ worker := mock.NewWorker()+ post := &entity.Post{+ ID: 1,+ Number: 1,+ Title: "Tom & Jerry <3 <b>bold</b>",+ Slug: "tom-jerry-3-bold",+ User: mock.JonSnow,+ }+ task := tasks.NotifyAboutNewComment(&entity.Comment{Content: "I agree"}, post)++ err := worker.+ OnTenant(mock.DemoTenant).+ AsUser(&author).+ WithBaseURL("http://domain.com").+ Execute(task)++ Expect(err).IsNil()+ Expect(emailmock.MessageHistory).HasLen(1)++ message := email.RenderMessage(context.Background(), emailmock.MessageHistory[0].TemplateName, email.NoReply, emailmock.MessageHistory[0].Props)+ Expect(message.Subject).Equals("[Demonstration] Tom & Jerry <3 <b>bold</b>")+ Expect(message.Body).ContainsSubstring("<strong><a href=//example.com><h1>View new Update</a></strong> left a comment on <strong>Tom & Jerry <3 <b>bold</b> (<a href='http://domain.com/posts/1/tom-jerry-3-bold'>#1</a>)</strong>.")+ Expect(strings.Contains(message.Body, "<h1>")).IsFalse()+ Expect(strings.Contains(message.Body, "<b>")).IsFalse()+}diff --git a/app/tasks/status_change_test.go b/app/tasks/status_change_test.goindex f3b8bc596..98a140c9a 100644--- a/app/tasks/status_change_test.go+++ b/app/tasks/status_change_test.go@@ -3,6 +3,7 @@ package tasks_testimport ("context""html/template"+ "strings""testing""time"@@ -17,6 +18,7 @@ import (. "github.com/getfider/fider/app/pkg/assert""github.com/getfider/fider/app/pkg/bus""github.com/getfider/fider/app/pkg/mock"+ "github.com/getfider/fider/app/services/email""github.com/getfider/fider/app/services/email/emailmock""github.com/getfider/fider/app/tasks")@@ -255,3 +257,61 @@ func TestNotifyAboutStatusChangeTask_Duplicate(t *testing.T) {"tenant_url": "http://domain.com",})}++func TestNotifyAboutStatusChangeTask_Duplicate_EscapesOriginalTitleInEmail(t *testing.T) {+ RegisterT(t)+ bus.Init(emailmock.Service{})++ bus.AddHandler(func(ctx context.Context, c *cmd.AddNewNotification) error {+ return nil+ })++ bus.AddHandler(func(ctx context.Context, q *query.GetActiveSubscribers) error {+ q.Result = []*entity.User{+ mock.AryaStark,+ }+ return nil+ })++ bus.AddHandler(func(ctx context.Context, c *cmd.TriggerWebhooks) error {+ return nil+ })++ worker := mock.NewWorker()+ post := &entity.Post{+ ID: 2,+ Number: 2,+ Title: "I need TypeScript",+ Slug: "i-need-typescript",+ User: mock.AryaStark,+ Status: enum.PostDuplicate,+ Response: &entity.PostResponse{+ RespondedAt: time.Now(),+ User: mock.JonSnow,+ Original: &entity.OriginalPost{+ Number: 1,+ Title: "<a href=//example.com><h1>View new Update</a> & more",+ Slug: "view-new-update-more",+ Status: enum.PostOpen,+ },+ },+ }++ task := tasks.NotifyAboutStatusChange(post, enum.PostOpen)++ err := worker.+ OnTenant(mock.DemoTenant).+ AsUser(mock.JonSnow).+ WithBaseURL("http://domain.com").+ Execute(task)++ Expect(err).IsNil()+ Expect(emailmock.MessageHistory).HasLen(1)++ escapedLink := "<a href='http://domain.com/posts/1/view-new-update-more'><a href=//example.com><h1>View new Update</a> & more</a>"+ Expect(emailmock.MessageHistory[0].Props["duplicate"]).Equals(escapedLink)++ message := email.RenderMessage(context.Background(), emailmock.MessageHistory[0].TemplateName, email.NoReply, emailmock.MessageHistory[0].Props)+ Expect(message.Body).ContainsSubstring("has been closed as a <strong>duplicate</strong> of " + escapedLink + ".")+ Expect(strings.Contains(message.Body, "<h1>")).IsFalse()+}diff --git a/app/tasks/tasks.go b/app/tasks/tasks.goindex 4448dfe6d..0b8d9e4ab 100644--- a/app/tasks/tasks.go+++ b/app/tasks/tasks.go@@ -3,6 +3,7 @@ package tasksimport ("context""fmt"+ "html""github.com/getfider/fider/app/models/entity""github.com/getfider/fider/app/models/enum"@@ -15,12 +16,19 @@ func describe(name string, job worker.Job) worker.Task {return worker.Task{Name: name, Job: job}}+// link returns an HTML anchor that displays its own URL. The result is+// rendered unescaped in email templates, so the URL is HTML-escaped here.func link(baseURL, path string, args ...any) string {- return fmt.Sprintf("<a href='%[1]s%[2]s'>%[1]s%[2]s</a>", baseURL, fmt.Sprintf(path, args...))+ url := html.EscapeString(baseURL + fmt.Sprintf(path, args...))+ return fmt.Sprintf("<a href='%[1]s'>%[1]s</a>", url)}+// linkWithText returns an HTML anchor with the given plain text as its label.+// The result is rendered unescaped in email templates, so both the URL and the+// text are HTML-escaped here. Callers must pass plain text, not HTML.func linkWithText(text, baseURL, path string, args ...any) string {- return fmt.Sprintf("<a href='%s%s'>%s</a>", baseURL, fmt.Sprintf(path, args...), text)+ url := html.EscapeString(baseURL + fmt.Sprintf(path, args...))+ return fmt.Sprintf("<a href='%s'>%s</a>", url, html.EscapeString(text))}func getActiveSubscribers(ctx context.Context, post *entity.Post, channel enum.NotificationChannel, event enum.NotificationEvent) ([]*entity.User, error) {diff --git a/views/email/change_status.html b/views/email/change_status.htmlindex 2f76e975f..fdf15af1c 100644--- a/views/email/change_status.html+++ b/views/email/change_status.html@@ -5,9 +5,9 @@<td style="padding:20px 30px 30px 30px;"><p style="padding-bottom:10px;border-bottom:1px solid #efefef;color:#1c262d;margin:0 0 15px 0;">{{ if .duplicate }}- {{ translate "email.change_status.duplicate" (dict "title" (.title | stripHtml) "postLink" .postLink "duplicate" .duplicate) | html }}+ {{ translate "email.change_status.duplicate" (dict "title" (.title | escapeHtml) "postLink" .postLink "duplicate" .duplicate) | html }}{{ else }}- {{ translate "email.change_status.others" (dict "title" (.title | stripHtml) "postLink" .postLink "status" (.status | lower)) | html }}+ {{ translate "email.change_status.others" (dict "title" (.title | escapeHtml) "postLink" .postLink "status" (.status | lower | escapeHtml)) | html }}{{ end }}</p><div style="margin:0;">diff --git a/views/email/delete_account_completed.html b/views/email/delete_account_completed.htmlindex 908a00792..1dfc9cddc 100644--- a/views/email/delete_account_completed.html+++ b/views/email/delete_account_completed.html@@ -4,7 +4,7 @@<tr><td style="padding:20px 30px 30px 30px;"><h2 style="color:#1c262d;margin:0 0 15px 0;padding:0;">{{ "email.greetings" | translate }}</h2>- <p style="color:#1c262d;margin:0 0 10px 0;">{{ translate "email.delete_account_completed.text" (dict "tenantName" (.tenantName | stripHtml) "subdomain" .subdomain) | html }}</p>+ <p style="color:#1c262d;margin:0 0 10px 0;">{{ translate "email.delete_account_completed.text" (dict "tenantName" (.tenantName | escapeHtml) "subdomain" (.subdomain | escapeHtml)) | html }}</p></td></tr>{{end}}diff --git a/views/email/delete_account_requested.html b/views/email/delete_account_requested.htmlindex 560581a44..90efbdf9f 100644--- a/views/email/delete_account_requested.html+++ b/views/email/delete_account_requested.html@@ -4,8 +4,8 @@<tr><td style="padding:20px 30px 30px 30px;"><h2 style="color:#1c262d;margin:0 0 15px 0;padding:0;">{{ "email.greetings" | translate }}</h2>- <p style="color:#1c262d;margin:0 0 10px 0;">{{ translate "email.delete_account_requested.text" (dict "tenantName" (.tenantName | stripHtml)) | html }}</p>- <p style="color:#1c262d;margin:0 0 20px 0;">{{ translate "email.delete_account_requested.scheduled" (dict "scheduledAt" .scheduledAt) | html }}</p>+ <p style="color:#1c262d;margin:0 0 10px 0;">{{ translate "email.delete_account_requested.text" (dict "tenantName" (.tenantName | escapeHtml)) | html }}</p>+ <p style="color:#1c262d;margin:0 0 20px 0;">{{ translate "email.delete_account_requested.scheduled" (dict "scheduledAt" (.scheduledAt | escapeHtml)) | html }}</p><p style="color:#1c262d;margin:0 0 10px 0;">{{ "email.delete_account_requested.cancel" | translate }}</p><p style="color:#1c262d;margin:0 0 20px 0;">{{ .cancelLink | html }}</p></td>diff --git a/views/email/delete_post.html b/views/email/delete_post.htmlindex fda258101..5a8eb4c54 100644--- a/views/email/delete_post.html+++ b/views/email/delete_post.html@@ -4,7 +4,7 @@<tr><td style="padding:20px 30px 30px 30px;"><p style="padding-bottom:10px;border-bottom:1px solid #efefef;color:#1c262d;margin:0 0 15px 0;">- {{ translate "email.delete_post.text" (dict "title" (.title | stripHtml)) | html }}+ {{ translate "email.delete_post.text" (dict "title" (.title | escapeHtml)) | html }}</p><div style="margin:0;">{{/* Sanitized HTML from markdown.Full. Do not render any other HTML here raw. */}}diff --git a/views/email/new_comment.html b/views/email/new_comment.htmlindex 199d06d45..589e13530 100644--- a/views/email/new_comment.html+++ b/views/email/new_comment.html@@ -4,7 +4,7 @@<tr><td style="padding:20px 30px 30px 30px;"><p style="padding-bottom:10px;border-bottom:1px solid #efefef;color:#1c262d;margin:0 0 15px 0;">- {{ translate .messageLocaleString (dict "userName" .userName "title" (.title | stripHtml) "postLink" .postLink) | html }}+ {{ translate .messageLocaleString (dict "userName" (.userName | escapeHtml) "title" (.title | escapeHtml) "postLink" .postLink) | html }}</p><div style="margin:0;">{{/* Sanitized HTML from markdown.Full. Do not render any other HTML here raw. */}}diff --git a/views/email/new_post.html b/views/email/new_post.htmlindex f53d46ee9..b545cd099 100644--- a/views/email/new_post.html+++ b/views/email/new_post.html@@ -4,7 +4,7 @@<tr><td style="padding:20px 30px 30px 30px;"><p style="padding-bottom:10px;border-bottom:1px solid #efefef;color:#1c262d;margin:0 0 15px 0;">- {{ translate "email.new_post.text" (dict "userName" (.userName | stripHtml) "title" (.title | stripHtml) "postLink" .postLink) | html }}+ {{ translate "email.new_post.text" (dict "userName" (.userName | escapeHtml) "title" (.title | escapeHtml) "postLink" .postLink) | html }}</p><div style="margin:0;">{{/* Sanitized HTML from markdown.Full. Do not render any other HTML here raw. */}}diff --git a/views/email/signin_email.html b/views/email/signin_email.htmlindex e884daf0e..ef23defab 100644--- a/views/email/signin_email.html+++ b/views/email/signin_email.html@@ -5,7 +5,7 @@<td style="padding:20px 30px 30px 30px;"><h2 style="color:#1c262d;margin:0 0 15px 0;padding:0;">{{ "email.greetings" | translate }}</h2><p style="color:#1c262d;margin:0 0 10px 0;">{{ "email.signin_email.text" | translate }}</p>- <p style="color:#1c262d;margin:0 0 20px 0;">{{ translate "email.signin_email.confirmation" (dict "siteName" (.siteName | stripHtml)) | html }}</p>+ <p style="color:#1c262d;margin:0 0 20px 0;">{{ translate "email.signin_email.confirmation" (dict "siteName" (.siteName | escapeHtml)) | html }}</p><table width="100%" cellpadding="0" cellspacing="0" border="0" style="margin:20px 0;"><tr>