From c114dd34aaee47d3a09cf3dc6ec32078b8fb695c Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Tue, 3 Nov 2026 14:33:38 +0100 Subject: [PATCH] feat: store bare template field aliases in canonical form on every copy write, check HTML bodies with html/template escaping rules, scope template branch variables, refuse selectors on text fields and unknown values, check campaign-level control arm copy, and read first-name usage from parsed field references --- docs/content/docs/api/reference/campaigns.mdx | 2 +- docs/content/docs/guides/expressions.mdx | 4 +- internal/app/advanced/service.go | 55 ++- internal/app/advanced/variant_copy_test.go | 69 +++ internal/app/advisor/detect_list.go | 45 +- internal/app/campaign/handlers.go | 1 + internal/app/campaign/template_copy.go | 18 +- internal/app/campaign/template_copy_test.go | 20 +- internal/app/sequence/handler.go | 5 +- internal/app/sequence/handler_test.go | 20 +- internal/models/advanced_outreach.go | 5 + internal/models/advanced_outreach_test.go | 16 +- internal/pkg/tmplvars/normalize.go | 395 +++++++++++++----- internal/pkg/tmplvars/normalize_test.go | 95 ++++- 14 files changed, 573 insertions(+), 177 deletions(-) create mode 100644 internal/app/advanced/variant_copy_test.go diff --git a/docs/content/docs/api/reference/campaigns.mdx b/docs/content/docs/api/reference/campaigns.mdx index 54fe3045b..2e0353aac 100644 --- a/docs/content/docs/api/reference/campaigns.mdx +++ b/docs/content/docs/api/reference/campaigns.mdx @@ -1425,7 +1425,7 @@ All fields optional. } ``` -`subject`, `body_plain` and `body_html` are checked before anything is saved, on a running campaign too. Copy that would not render as written answers `400` with `code: "invalid_template"` and a `message` naming the field, the line and the problem: an `{{if}}` with no `{{end}}`, an unknown function, an unknown sender field, or a bare name that is not a built-in field. Built-in fields are accepted as `{{.FirstName}}` or in their snake_case, camelCase and lowercase spellings (`{{first_name}}`); see [personalization](/guides/expressions/). +`subject`, `body_plain` and `body_html` are checked before anything is saved, on a running campaign too. Copy that would not render as written answers `400` with `code: "invalid_template"` and a `message` naming the field, the line and the problem: an `{{if}}` with no `{{end}}`, an unknown function, an unknown sender field, or a bare name that is not a built-in field. Built-in fields are accepted as `{{.FirstName}}` or in their snake_case, camelCase and lowercase spellings. A spelling without the dot is saved in canonical form (`{{first_name}}` is stored and returned as `{{.FirstName}}`), as are sender fields; see [personalization](/guides/expressions/). The same applies to campaign creation with `steps` and to A/B variants. A step's control arm (`is_control` with a `step_id`) sends the step's copy, so its own copy is not checked. ### Response diff --git a/docs/content/docs/guides/expressions.mdx b/docs/content/docs/guides/expressions.mdx index a277bec7f..e4cf450e1 100644 --- a/docs/content/docs/guides/expressions.mdx +++ b/docs/content/docs/guides/expressions.mdx @@ -74,7 +74,7 @@ Hi {{.FirstName}}, I noticed {{.Company}} is hiring and wanted to reach out. ``` -Campaign copy also accepts the snake_case, camelCase and lowercase spellings of every built-in field, with or without the dot: `{{first_name}}`, `{{.firstName}}`, `{{firstname}}`, `{{last_name}}`, `{{email}}`, `{{company}}`, `{{company_name}}`, `{{phone}}`, `{{unsubscribe_link}}`, and `{{.Sender.first_name}}` for sender fields. They work inside conditions and helpers as well (`{{if first_name}}`, `{{first_name | default "there"}}`). A contact's own custom field with one of these names keeps its value. `{{.FIRSTNAME}}` is not one of them. +Campaign copy also accepts the snake_case, camelCase and lowercase spellings of every built-in field, with or without the dot: `{{first_name}}`, `{{.firstName}}`, `{{firstname}}`, `{{last_name}}`, `{{email}}`, `{{company}}`, `{{company_name}}`, `{{phone}}`, `{{unsubscribe_link}}`, and `{{.Sender.first_name}}` for sender fields. They work inside conditions and helpers as well (`{{if first_name}}`, `{{first_name | default "there"}}`). A spelling without the dot is saved in canonical form, so `{{first_name}}` is stored as `{{.FirstName}}` and always reads the built-in field, and sender fields are saved under their canonical names. A dotted spelling such as `{{.first_name}}` is kept as written, and a contact's own custom field with that name keeps its value. `{{.FIRSTNAME}}` is not one of them. **Custom fields** work the same way with a dot: `{{.industry}}`, `{{.account_owner}}`. Names containing spaces or dashes also work as written (`{{if .job title}}...{{end}}`) and resolve everywhere, including inside conditions and helpers, because Warmbly rewrites them to an `index` lookup for you. @@ -94,7 +94,7 @@ Values come from the **mailbox actually sending that message**, including campai `{{.Sender.Email}}` is the recipient-visible From address, including a configured send-as alias. `{{.Sender.MailboxEmail}}` is the underlying connected mailbox address. `{{.Sender.ReplyTo}}` is the explicit Reply-To header; it is empty when replies simply go to the sender. -Prefix each name below with `.Sender.`, for example `{{.Sender.Provider}}`. The names are written as shown; campaign copy also accepts their snake_case, camelCase and lowercase spellings (`{{.Sender.first_name}}`), and any other capitalization is refused: +Prefix each name below with `.Sender.`, for example `{{.Sender.Provider}}`. The names are written as shown; campaign copy also accepts their snake_case, camelCase and lowercase spellings (`{{.Sender.first_name}}`, saved as `{{.Sender.FirstName}}`), and any other capitalization is refused. A sender field is text, a flag or a number, so a selector after it (`{{.Sender.Email.Domain}}`) is refused too: | Details | Fields | | --- | --- | diff --git a/internal/app/advanced/service.go b/internal/app/advanced/service.go index cd8efb626..feca027b0 100644 --- a/internal/app/advanced/service.go +++ b/internal/app/advanced/service.go @@ -366,13 +366,12 @@ func (s *service) CreateABVariant(ctx context.Context, campaignID uuid.UUID, req if req == nil || strings.TrimSpace(req.Name) == "" { return nil, errx.New(errx.BadRequest, "variant name is required") } - if err := tmplvars.CheckCopy( - tmplvars.Part{Name: "variant subject", Text: req.Subject}, - tmplvars.Part{Name: "variant body", Text: req.BodyHTML}, - tmplvars.Part{Name: "variant plain-text body", Text: req.BodyPlain}, - ); err != nil { - return nil, errx.InvalidTemplate(err) + if models.VariantSendsOwnCopy(req.SequenceID, req.IsControl) { + if err := checkVariantCopy(req.Subject, req.BodyHTML, req.BodyPlain); err != nil { + return nil, errx.InvalidTemplate(err) + } } + tmplvars.CanonicalizeAll(&req.Subject, &req.BodyHTML, &req.BodyPlain) out, err := s.repo.CreateABVariant(ctx, campaignID, req) if err != nil { return nil, toErrx(err) @@ -381,14 +380,17 @@ func (s *service) CreateABVariant(ctx context.Context, campaignID uuid.UUID, req } func (s *service) UpdateABVariant(ctx context.Context, campaignID, variantID uuid.UUID, req *models.UpdateCampaignABVariantRequest) (*models.CampaignABVariant, *errx.Error) { - if req != nil { - if err := tmplvars.CheckCopy( - tmplvars.Part{Name: "variant subject", Text: deref(req.Subject)}, - tmplvars.Part{Name: "variant body", Text: deref(req.BodyHTML)}, - tmplvars.Part{Name: "variant plain-text body", Text: deref(req.BodyPlain)}, - ); err != nil { - return nil, errx.InvalidTemplate(err) + if req != nil && (req.Subject != nil || req.BodyHTML != nil || req.BodyPlain != nil || req.IsControl != nil) { + sendsOwn, xerr := s.variantSendsOwnCopy(ctx, campaignID, variantID, req.IsControl) + if xerr != nil { + return nil, xerr } + if sendsOwn { + if err := checkVariantCopy(deref(req.Subject), deref(req.BodyHTML), deref(req.BodyPlain)); err != nil { + return nil, errx.InvalidTemplate(err) + } + } + tmplvars.CanonicalizeAll(req.Subject, req.BodyHTML, req.BodyPlain) } out, err := s.repo.UpdateABVariant(ctx, campaignID, variantID, req) if err != nil { @@ -397,6 +399,33 @@ func (s *service) UpdateABVariant(ctx context.Context, campaignID, variantID uui return out, nil } +func checkVariantCopy(subject, bodyHTML, bodyPlain string) error { + return tmplvars.CheckCopy( + tmplvars.Part{Name: "variant subject", Text: subject}, + tmplvars.Part{Name: "variant body", Text: bodyHTML, HTML: true}, + tmplvars.Part{Name: "variant plain-text body", Text: bodyPlain}, + ) +} + +// variantSendsOwnCopy reads whether the variant, with isControl applied, sends its own copy. +// A variant that is not found is checked, and the update reports the miss. +func (s *service) variantSendsOwnCopy(ctx context.Context, campaignID, variantID uuid.UUID, isControl *bool) (bool, *errx.Error) { + variants, err := s.repo.ListABVariants(ctx, campaignID) + if err != nil { + return false, toErrx(err) + } + for _, v := range variants { + if v.ID == variantID { + control := v.IsControl + if isControl != nil { + control = *isControl + } + return models.VariantSendsOwnCopy(v.SequenceID, control), nil + } + } + return true, nil +} + func deref(s *string) string { if s == nil { return "" diff --git a/internal/app/advanced/variant_copy_test.go b/internal/app/advanced/variant_copy_test.go new file mode 100644 index 000000000..f3a134bc6 --- /dev/null +++ b/internal/app/advanced/variant_copy_test.go @@ -0,0 +1,69 @@ +package advanced + +import ( + "context" + "testing" + + "github.com/google/uuid" + "github.com/warmbly/warmbly/internal/models" + "github.com/warmbly/warmbly/internal/repository" +) + +type variantRepo struct { + repository.AdvancedOutreachRepository + rows []models.CampaignABVariant + created *models.CreateCampaignABVariantRequest + updated *models.UpdateCampaignABVariantRequest +} + +func (r *variantRepo) ListABVariants(context.Context, uuid.UUID) ([]models.CampaignABVariant, error) { + return r.rows, nil +} + +func (r *variantRepo) CreateABVariant(_ context.Context, _ uuid.UUID, req *models.CreateCampaignABVariantRequest) (*models.CampaignABVariant, error) { + r.created = req + return &models.CampaignABVariant{}, nil +} + +func (r *variantRepo) UpdateABVariant(_ context.Context, _, _ uuid.UUID, req *models.UpdateCampaignABVariantRequest) (*models.CampaignABVariant, error) { + r.updated = req + return &models.CampaignABVariant{}, nil +} + +func TestVariantCopyIsCheckedUnlessItIsAStepControlArm(t *testing.T) { + broken := "{{if .Company}}x" + step := uuid.New() + ctx, campaign := context.Background(), uuid.New() + + repo := &variantRepo{} + svc := &service{repo: repo} + if _, xerr := svc.CreateABVariant(ctx, campaign, &models.CreateCampaignABVariantRequest{Name: "ctl", SequenceID: &step, IsControl: true, BodyPlain: broken}); xerr != nil { + t.Fatalf("a step's control arm never sends its copy: %v", xerr) + } + for _, req := range []*models.CreateCampaignABVariantRequest{ + {Name: "campaign control", IsControl: true, BodyPlain: broken}, + {Name: "B", SequenceID: &step, Subject: broken}, + } { + if _, xerr := svc.CreateABVariant(ctx, campaign, req); xerr == nil || xerr.Identifier != "invalid_template" { + t.Errorf("%s: got %v, want invalid_template", req.Name, xerr) + } + } + + if _, xerr := svc.CreateABVariant(ctx, campaign, &models.CreateCampaignABVariantRequest{Name: "B", Subject: "Hi {{first_name}}"}); xerr != nil || repo.created.Subject != "Hi {{.FirstName}}" { + t.Fatalf("a bare alias should be stored canonical: %v %+v", xerr, repo.created) + } + + id := uuid.New() + repo.rows = []models.CampaignABVariant{{ID: id, SequenceID: &step, IsControl: true}} + if _, xerr := svc.UpdateABVariant(ctx, campaign, id, &models.UpdateCampaignABVariantRequest{BodyPlain: &broken}); xerr != nil { + t.Fatalf("updating a step's control arm copy: %v", xerr) + } + off := false + if _, xerr := svc.UpdateABVariant(ctx, campaign, id, &models.UpdateCampaignABVariantRequest{BodyPlain: &broken, IsControl: &off}); xerr == nil { + t.Fatal("turning the control off makes it send its copy, so the copy is checked") + } + plain := "{{company_name}}" + if _, xerr := svc.UpdateABVariant(ctx, campaign, id, &models.UpdateCampaignABVariantRequest{BodyPlain: &plain, IsControl: &off}); xerr != nil || *repo.updated.BodyPlain != "{{.Company}}" { + t.Fatalf("a bare alias should be stored canonical on update: %v", xerr) + } +} diff --git a/internal/app/advisor/detect_list.go b/internal/app/advisor/detect_list.go index 28d7ae1f8..e5cdb9291 100644 --- a/internal/app/advisor/detect_list.go +++ b/internal/app/advisor/detect_list.go @@ -200,7 +200,7 @@ func detectMissingPersonalizationData(s *repository.AdvisorSnapshot) []Finding { if st.CampaignID != cl.Campaign.ID { continue } - if usesFirstName(st.Subject + st.BodyPlain + st.BodyHTML) { + if usesFirstName(st.Subject, st.BodyPlain, st.BodyHTML) { uses = true break } @@ -279,44 +279,13 @@ func detectUnsubscribedEnrolled(s *repository.AdvisorSnapshot) []Finding { return out } -// usesFirstName reports whether a template action in the copy names the first -// name, in any spelling the renderer accepts (`.FirstName`, `first_name`, `firstName`). -func usesFirstName(text string) bool { - for _, action := range tmplvars.ActionPattern.FindAllString(text, -1) { - for _, form := range []string{"firstname", "first_name"} { - if indexFold(action, form) >= 0 { - return true - } +// usesFirstName reports whether any part reads the contact's first name, in +// any spelling the renderer accepts (`.FirstName`, `first_name`, `firstName`). +func usesFirstName(parts ...string) bool { + for _, p := range parts { + if tmplvars.References(p)["FirstName"] { + return true } } return false } - -// indexFold is a case-insensitive substring search that avoids allocating a -// lowered copy of every email body on every run. -func indexFold(haystack, needle string) int { - n, h := len(needle), len(haystack) - if n == 0 || n > h { - return -1 - } - for i := 0; i+n <= h; i++ { - match := true - for j := 0; j < n; j++ { - a, b := haystack[i+j], needle[j] - if 'A' <= a && a <= 'Z' { - a += 'a' - 'A' - } - if 'A' <= b && b <= 'Z' { - b += 'a' - 'A' - } - if a != b { - match = false - break - } - } - if match { - return i - } - } - return -1 -} diff --git a/internal/app/campaign/handlers.go b/internal/app/campaign/handlers.go index 59c211681..4919b211d 100644 --- a/internal/app/campaign/handlers.go +++ b/internal/app/campaign/handlers.go @@ -50,6 +50,7 @@ func (s *campaignService) Create(ctx context.Context, userID string, orgID *uuid if err := checkCreateCopy(data); err != nil { return nil, errx.InvalidTemplate(err) } + canonicalizeCreateCopy(data) // Daily creation throttle (config.DailyThrottleNewCampaigns). Caps // per-day new-campaign rate per org so an unlimited plan can't be diff --git a/internal/app/campaign/template_copy.go b/internal/app/campaign/template_copy.go index 326eb91c4..9957eb1c4 100644 --- a/internal/app/campaign/template_copy.go +++ b/internal/app/campaign/template_copy.go @@ -11,7 +11,7 @@ import ( func stepCopy(owner, subject, bodyHTML, bodyPlain string) []tmplvars.Part { return []tmplvars.Part{ {Name: owner + " subject", Text: subject}, - {Name: owner + " body", Text: bodyHTML}, + {Name: owner + " body", Text: bodyHTML, HTML: true}, {Name: owner + " plain-text body", Text: bodyPlain}, } } @@ -28,11 +28,23 @@ func checkCreateCopy(data *models.CreateCampaign) error { return tmplvars.CheckCopy(parts...) } -// checkActiveVariantCopy refuses a start while an active variant's copy would not render; a control arm sends the step's copy. +// canonicalizeCreateCopy stores the new campaign's copy in canonical form. +func canonicalizeCreateCopy(data *models.CreateCampaign) { + for i := range data.Sequences { + seq := &data.Sequences[i] + tmplvars.CanonicalizeAll(&seq.Subject, &seq.BodyHTML, &seq.BodyPlain) + } + for i := range data.Variants { + v := &data.Variants[i] + tmplvars.CanonicalizeAll(&v.Subject, &v.BodyHTML, &v.BodyPlain) + } +} + +// checkActiveVariantCopy refuses a start while an active variant that sends its own copy would not render. func checkActiveVariantCopy(variants []models.CampaignABVariant) error { var parts []tmplvars.Part for _, v := range variants { - if v.IsActive && !v.IsControl { + if v.IsActive && models.VariantSendsOwnCopy(v.SequenceID, v.IsControl) { parts = append(parts, stepCopy(fmt.Sprintf("variant %q", v.Name), v.Subject, v.BodyHTML, v.BodyPlain)...) } } diff --git a/internal/app/campaign/template_copy_test.go b/internal/app/campaign/template_copy_test.go index dc9bb2f54..ef3f1cc17 100644 --- a/internal/app/campaign/template_copy_test.go +++ b/internal/app/campaign/template_copy_test.go @@ -4,6 +4,7 @@ import ( "strings" "testing" + "github.com/google/uuid" "github.com/warmbly/warmbly/internal/models" ) @@ -29,9 +30,10 @@ func TestCheckCreateCopyNamesTheBrokenStepAndVariant(t *testing.T) { func TestCheckActiveVariantCopySkipsInactiveAndControl(t *testing.T) { broken := "{{if .Company}}x" + step := uuid.New() variants := []models.CampaignABVariant{ {Name: "off", BodyPlain: broken, IsActive: false}, - {Name: "control", BodyPlain: broken, IsActive: true, IsControl: true}, + {Name: "control", BodyPlain: broken, IsActive: true, IsControl: true, SequenceID: &step}, {Name: "ok", Subject: "Hi {{first_name}}", IsActive: true}, } if err := checkActiveVariantCopy(variants); err != nil { @@ -41,4 +43,20 @@ func TestCheckActiveVariantCopySkipsInactiveAndControl(t *testing.T) { if err := checkActiveVariantCopy(variants); err == nil || !strings.Contains(err.Error(), `variant "B" body`) { t.Fatalf("got %v, want the broken active variant named", err) } + // A campaign-level control arm sends its own copy, so it is checked. + campaignControl := []models.CampaignABVariant{{Name: "campaign control", Subject: broken, IsActive: true, IsControl: true}} + if err := checkActiveVariantCopy(campaignControl); err == nil { + t.Fatal("a campaign-level control arm's broken copy should be refused") + } +} + +func TestCanonicalizeCreateCopy(t *testing.T) { + data := &models.CreateCampaign{ + Sequences: []models.CreateSequenceInput{{Subject: "Hi {{first_name}}", BodyPlain: "{{.first_name}}"}}, + Variants: []models.CreateCampaignABVariantRequest{{Name: "B", BodyHTML: "

{{company_name}}

"}}, + } + canonicalizeCreateCopy(data) + if data.Sequences[0].Subject != "Hi {{.FirstName}}" || data.Sequences[0].BodyPlain != "{{.first_name}}" || data.Variants[0].BodyHTML != "

{{.Company}}

" { + t.Fatalf("got %+v", data) + } } diff --git a/internal/app/sequence/handler.go b/internal/app/sequence/handler.go index a553caaec..32440c5f4 100644 --- a/internal/app/sequence/handler.go +++ b/internal/app/sequence/handler.go @@ -26,6 +26,9 @@ func (s *sequenceService) Update(ctx context.Context, orgID, campaignID, sequenc if err := checkCopy(data); err != nil { return nil, errx.InvalidTemplate(err) } + if data != nil { + tmplvars.CanonicalizeAll(data.Subject, data.BodyHTML, data.BodyPlain) + } s.deriveBodyHTML(ctx, orgID, campaignID, sequenceID, data) // Branch routing is resolved (and made safe against deleted/dangling targets // and loops) at schedule time in the repository's finder; the repository also @@ -45,7 +48,7 @@ func checkCopy(data *models.UpdateSequence) error { val *string }{{"subject", data.Subject}, {"body", data.BodyHTML}, {"plain-text body", data.BodyPlain}} { if f.val != nil { - parts = append(parts, tmplvars.Part{Name: f.name, Text: *f.val}) + parts = append(parts, tmplvars.Part{Name: f.name, Text: *f.val, HTML: f.val == data.BodyHTML}) } } return tmplvars.CheckCopy(parts...) diff --git a/internal/app/sequence/handler_test.go b/internal/app/sequence/handler_test.go index ffe4be7e9..ce5c902ed 100644 --- a/internal/app/sequence/handler_test.go +++ b/internal/app/sequence/handler_test.go @@ -57,8 +57,9 @@ func TestUpdateAcceptsAliasesAndCustomFields(t *testing.T) { if _, xerr := NewService(repo).Update(context.Background(), "org", "c", "s", &models.UpdateSequence{BodyHTML: &body}); xerr != nil { t.Fatalf("valid copy refused: %v", xerr) } - if repo.saved == nil || *repo.saved.BodyHTML != body { - t.Fatal("copy must be stored as written, not rewritten") + want := `

Hi {{.FirstName}}, {{if .company_name}}at {{.company_name}}{{end}} {{.job title}} {{.anything_custom | default "x"}}

` + if repo.saved == nil || *repo.saved.BodyHTML != want { + t.Fatalf("only the bare alias is stored in canonical form, got %q", *repo.saved.BodyHTML) } } @@ -69,7 +70,8 @@ func TestUpdateDerivesHTMLForPlainOnlyCopy(t *testing.T) { if _, xerr := NewService(repo).Update(context.Background(), "org", "c", id.String(), &models.UpdateSequence{BodyPlain: &plain}); xerr != nil { t.Fatalf("valid plain-only copy refused: %v", xerr) } - if repo.saved == nil || repo.saved.BodyHTML == nil || *repo.saved.BodyHTML != mailhtml.FromText(plain) { + canonical := "Hi {{.FirstName}},\n\nWorth a chat?" + if repo.saved == nil || *repo.saved.BodyPlain != canonical || repo.saved.BodyHTML == nil || *repo.saved.BodyHTML != mailhtml.FromText(canonical) { t.Fatalf("plain-only copy must store HTML derived from it, got %+v", repo.saved) } broken := "Hi {{if .Company}}" @@ -78,3 +80,15 @@ func TestUpdateDerivesHTMLForPlainOnlyCopy(t *testing.T) { t.Fatal("broken plain-only copy must be refused before any HTML is derived or saved") } } + +func TestUpdateRefusesEscaperBeforePipeInHTMLOnly(t *testing.T) { + body := `{{html .FirstName | printf "%s"}}` + repo := &recordingRepo{} + if _, xerr := NewService(repo).Update(context.Background(), "org", "c", "s", &models.UpdateSequence{BodyHTML: &body}); xerr == nil || xerr.Identifier != "invalid_template" { + t.Fatalf("an HTML body the HTML renderer refuses should be refused, got %v", xerr) + } + repo = &recordingRepo{} + if _, xerr := NewService(repo).Update(context.Background(), "org", "c", "s", &models.UpdateSequence{Subject: &body}); xerr != nil { + t.Fatalf("the same text in a plain subject renders, got %v", xerr) + } +} diff --git a/internal/models/advanced_outreach.go b/internal/models/advanced_outreach.go index 3841a796a..0d98e1aa9 100644 --- a/internal/models/advanced_outreach.go +++ b/internal/models/advanced_outreach.go @@ -750,6 +750,11 @@ type CampaignABVariant struct { UpdatedAt time.Time `json:"updated_at"` } +// VariantSendsOwnCopy is false only for a step's control arm, which sends the step's copy. +func VariantSendsOwnCopy(sequenceID *uuid.UUID, isControl bool) bool { + return !isControl || sequenceID == nil +} + type CreateCampaignABVariantRequest struct { Name string `json:"name" binding:"required"` SequenceID *uuid.UUID `json:"step_id,omitempty"` diff --git a/internal/models/advanced_outreach_test.go b/internal/models/advanced_outreach_test.go index 2bdcd0c80..ff960a07d 100644 --- a/internal/models/advanced_outreach_test.go +++ b/internal/models/advanced_outreach_test.go @@ -1,6 +1,10 @@ package models -import "testing" +import ( + "testing" + + "github.com/google/uuid" +) // The content-score floor reaches the API as a plain integer. Left unclamped, a // floor above 100 flags every campaign forever and a floor at or below 0 is a @@ -110,3 +114,13 @@ func TestNilIntentListStaysNilThroughNormalize(t *testing.T) { t.Error("Normalize turned an unset list into an empty one, which means none") } } + +func TestVariantSendsOwnCopy(t *testing.T) { + step := uuid.New() + if VariantSendsOwnCopy(&step, true) { + t.Error("a step's control arm sends the step's copy") + } + if !VariantSendsOwnCopy(nil, true) || !VariantSendsOwnCopy(&step, false) || !VariantSendsOwnCopy(nil, false) { + t.Error("every other variant sends its own copy") + } +} diff --git a/internal/pkg/tmplvars/normalize.go b/internal/pkg/tmplvars/normalize.go index c6e772278..5dee99ec3 100644 --- a/internal/pkg/tmplvars/normalize.go +++ b/internal/pkg/tmplvars/normalize.go @@ -3,6 +3,8 @@ package tmplvars import ( "errors" "fmt" + htmltemplate "html/template" + "maps" "regexp" "sort" "strings" @@ -24,6 +26,8 @@ var FormLinkMarker = regexp.MustCompile(`\{\{\s*form_link:([a-z0-9]{1,64})\s*\}\ // a valid selector and is rewritten to `(index . "key")`. var spacedFieldRefAt = regexp.MustCompile(`^\.[A-Za-z0-9_]+(?:[ \-]+[A-Za-z0-9_]+)+`) +var htmlComment = regexp.MustCompile(`(?s)`) + // builtinFuncs are text/template's own functions, which a bare name may call. var builtinFuncs = map[string]bool{ "and": true, "call": true, "html": true, "index": true, "slice": true, "js": true, "len": true, @@ -36,6 +40,16 @@ func isFunc(name string) bool { return ok || builtinFuncs[name] } +// mode is what the walker's rewrites are for. +type mode int + +const ( + // forRender keeps a bare alias's spelling, so a custom field of that name wins. + forRender mode = iota + // forStore writes a bare alias as its canonical field, which every release renders. + forStore +) + // Normalize rewrites the accepted spellings of campaign copy into the form the // engine compiles: spaced and dashed custom-field keys become index calls, a // bare built-in name ({{first_name}}) becomes a field of the root, and Sender @@ -43,17 +57,65 @@ func isFunc(name string) bool { // are never touched. The error names a reference that can never resolve; the // returned source is usable either way, so a renderer may ignore it. func Normalize(src string) (string, error) { - if !strings.Contains(src, "{{") { - return src, nil + w, rewritten, _ := analyze(src, forRender) + if w == nil { + return rewritten, nil // the compiler reports a syntax error itself } - src = ActionPattern.ReplaceAllStringFunc(src, rewriteSpacedInAction) + return applyEdits(rewritten, w.edits), w.err +} + +// Canonicalize is the copy to store for src: bare built-in aliases become their +// canonical field ({{first_name}} is {{.FirstName}}) and Sender fields take +// their canonical names, so the previous release renders it too. Dotted aliases +// and everything outside actions are kept as written. +func Canonicalize(src string) string { + w, _, spans := analyze(src, forStore) + if w == nil || w.err != nil || len(w.edits) == 0 { + return src + } + edits := make([]edit, 0, len(w.edits)) + for _, e := range w.edits { + start, ok1 := toOriginal(e.start, spans) + end, ok2 := toOriginal(e.end, spans) + if ok1 && ok2 { + edits = append(edits, edit{start, end, e.text}) + } + } + return applyEdits(src, edits) +} + +// CanonicalizeAll canonicalises each non-nil copy field in place. +func CanonicalizeAll(fields ...*string) { + for _, f := range fields { + if f != nil { + *f = Canonicalize(*f) + } + } +} + +// References lists the canonical built-in fields src reads from the contact. +func References(src string) map[string]bool { + w, _, _ := analyze(src, forRender) + if w == nil { + return nil + } + return w.refs +} + +// analyze parses src with spaced references rewritten and form-link markers +// blanked, and walks it. A nil walker means src does not parse. +func analyze(src string, m mode) (*walker, string, []span) { + if !strings.Contains(src, "{{") { + return nil, src, nil + } + rewritten, spans := rewriteSpaced(src) tree := parse.New("normalize") tree.Mode = parse.SkipFuncCheck trees := map[string]*parse.Tree{} - if _, err := tree.Parse(src, "", "", trees); err != nil { - return src, nil // the compiler reports the syntax error itself + if _, err := tree.Parse(maskMarkers(rewritten), "", "", trees); err != nil { + return nil, rewritten, spans } - w := &walker{src: src, vars: map[string]scope{"$": scopeRoot}} + w := &walker{src: rewritten, mode: m, vars: map[string]scope{"$": scopeRoot}, refs: map[string]bool{}} names := make([]string, 0, len(trees)) for name := range trees { names = append(names, name) @@ -64,7 +126,21 @@ func Normalize(src string) (string, error) { w.node(t.Root, scopeRoot) } } - return w.apply(), w.err + return w, rewritten, spans +} + +// maskMarkers blanks each form-link marker, keeping offsets and line breaks. +func maskMarkers(src string) string { + return FormLinkMarker.ReplaceAllStringFunc(src, blank) +} + +func blank(s string) string { + return strings.Map(func(r rune) rune { + if r == '\n' { + return r + } + return ' ' + }, s) } // Check reports whether campaign copy compiles as written, naming the problem @@ -73,10 +149,7 @@ func Check(src string) error { if src == "" { return nil } - // A marker is dropped for the check, keeping its line breaks so line numbers stay true. - norm, err := Normalize(FormLinkMarker.ReplaceAllStringFunc(src, func(m string) string { - return strings.Repeat("\n", strings.Count(m, "\n")) - })) + norm, err := Normalize(maskMarkers(src)) if err != nil { return err } @@ -86,13 +159,49 @@ func Check(src string) error { return nil } -// Part is one named piece of copy to check. -type Part struct{ Name, Text string } +// CheckHTML reports an HTML body the HTML renderer refuses although it parses: +// a predefined escaper (html, urlquery) placed before a pipe. +func CheckHTML(src string) error { + if !strings.Contains(src, "{{") { + return nil + } + // Comments are shielded as the renderer shields them: a comment holding an action renders as text. + src = htmlComment.ReplaceAllStringFunc(src, func(c string) string { + if strings.Contains(c, "{{") { + return " " + c[4:len(c)-3] + " " + } + return blank(c) + }) + norm, err := Normalize(maskMarkers(src)) + if err != nil { + return nil // Check reports it + } + t, err := tmplfuncs.CompileHTML("copy", norm) + if err != nil { + return nil // Check reports it + } + _, err = tmplfuncs.Execute(t, map[string]any{}) + var he *htmltemplate.Error + if errors.As(err, &he) && he.ErrorCode == htmltemplate.ErrPredefinedEscaper { + return fmt.Errorf("line %d: %s", he.Line, he.Description) + } + return nil +} + +// Part is one named piece of copy to check; HTML marks a body rendered as HTML. +type Part struct { + Name, Text string + HTML bool +} // CheckCopy checks each part in order and reports the first problem with its part's name. func CheckCopy(parts ...Part) error { for _, p := range parts { - if err := Check(p.Text); err != nil { + err := Check(p.Text) + if err == nil && p.HTML { + err = CheckHTML(p.Text) + } + if err != nil { return fmt.Errorf("the %s has a template error: %w", p.Name, err) } } @@ -104,6 +213,43 @@ type edit struct { text string } +// span is one spaced-reference rewrite: [origStart, origEnd) became [newStart, newEnd). +type span struct{ origStart, origEnd, newStart, newEnd int } + +// toOriginal maps an offset in the rewritten source back to src; false inside a rewrite. +func toOriginal(pos int, spans []span) (int, bool) { + delta := 0 + for _, s := range spans { + if pos <= s.newStart { + break + } + if pos < s.newEnd { + return 0, false + } + delta += (s.newEnd - s.newStart) - (s.origEnd - s.origStart) + } + return pos - delta, true +} + +func applyEdits(src string, edits []edit) string { + if len(edits) == 0 { + return src + } + sort.Slice(edits, func(i, j int) bool { return edits[i].start < edits[j].start }) + var b strings.Builder + last := 0 + for _, e := range edits { + if e.start < last { + continue + } + b.WriteString(src[last:e.start]) + b.WriteString(e.text) + last = e.end + } + b.WriteString(src[last:]) + return b.String() +} + // scope is what a dot or a variable holds, as far as the walker can tell. type scope int @@ -114,15 +260,18 @@ const ( ) type walker struct { - src string - edits []edit - err error - vars map[string]scope + src string + mode mode + edits []edit + err error + vars map[string]scope + assigned []string // variables reassigned with =, in walk order + refs map[string]bool } func (w *walker) fail(pos int, format string, args ...any) { if w.err == nil { - line := strings.Count(w.src[:min(pos, len(w.src))], "\n") + 1 + line := strings.Count(w.src[:min(max(pos, 0), len(w.src))], "\n") + 1 w.err = fmt.Errorf("line %d: %s", line, fmt.Sprintf(format, args...)) } } @@ -139,24 +288,38 @@ func (w *walker) node(n parse.Node, dot scope) { case *parse.ActionNode: w.pipe(x.Pipe, dot, false) case *parse.IfNode: - w.pipe(x.Pipe, dot, false) - w.node(x.List, dot) - w.node(x.ElseList, dot) - case *parse.RangeNode: - w.pipe(x.Pipe, dot, true) - w.node(x.List, scopeOther) - w.node(x.ElseList, dot) + w.structure(&x.BranchNode, dot, func(scope) scope { return dot }, false) case *parse.WithNode: - inner := w.pipe(x.Pipe, dot, false) - w.node(x.List, inner) - w.node(x.ElseList, dot) + w.structure(&x.BranchNode, dot, func(v scope) scope { return v }, false) + case *parse.RangeNode: + w.structure(&x.BranchNode, dot, func(scope) scope { return scopeOther }, true) case *parse.TemplateNode: w.pipe(x.Pipe, dot, false) } } -// pipe visits a pipeline, records what its declared variables hold, and -// returns what the pipeline evaluates to. +// structure walks an if, with or range. Variables declared inside it end with +// it; the body and the else branch start from the same bindings; a variable +// either branch reassigns is unknown afterwards. +func (w *walker) structure(b *parse.BranchNode, dot scope, bodyDot func(scope) scope, ranged bool) { + outer, mark := w.vars, len(w.assigned) + w.vars = maps.Clone(outer) + value := w.pipe(b.Pipe, dot, ranged) + declared := w.vars + w.vars = maps.Clone(declared) + w.node(b.List, bodyDot(value)) + w.vars = maps.Clone(declared) + w.node(b.ElseList, dot) + w.vars = outer + for _, name := range w.assigned[mark:] { + if _, ok := outer[name]; ok { + outer[name] = scopeOther + } + } +} + +// pipe visits a pipeline, records what its variables hold, and returns what +// the pipeline evaluates to. func (w *walker) pipe(p *parse.PipeNode, dot scope, ranged bool) scope { if p == nil { return scopeOther @@ -167,22 +330,26 @@ func (w *walker) pipe(p *parse.PipeNode, dot scope, ranged bool) scope { } } value := w.valueOf(p, dot) + if ranged { + value = scopeOther + } for _, v := range p.Decl { - if ranged { - w.vars[v.Ident[0]] = scopeOther - } else { - w.vars[v.Ident[0]] = value + w.vars[v.Ident[0]] = value + if p.IsAssign { + w.assigned = append(w.assigned, v.Ident[0]) } } return value } -// valueOf is what a pipeline of one bare operand holds; anything else is scopeOther. +// valueOf is what a pipeline of one operand holds; anything else is scopeOther. func (w *walker) valueOf(p *parse.PipeNode, dot scope) scope { if len(p.Cmds) != 1 || len(p.Cmds[0].Args) != 1 { return scopeOther } switch x := p.Cmds[0].Args[0].(type) { + case *parse.PipeNode: + return w.valueOf(x, dot) case *parse.DotNode: return dot case *parse.IdentifierNode: @@ -211,41 +378,39 @@ func (w *walker) arg(n parse.Node, calls bool, dot scope) { case *parse.PipeNode: w.pipe(x, dot, false) case *parse.IdentifierNode: - w.identifier(x, calls) + w.identifier(x, calls, dot) case *parse.FieldNode: w.fields(int(x.Pos), "."+strings.Join(x.Ident, "."), "", dot, x.Ident) case *parse.VariableNode: - name := x.Ident[0] - held, known := w.vars[name] - if len(x.Ident) == 1 { - return + if len(x.Ident) > 1 { + w.fields(int(x.Pos), strings.Join(x.Ident, "."), x.Ident[0], w.vars[x.Ident[0]], x.Ident[1:]) } - if !known || held == scopeOther { - w.fail(int(x.Pos), "fields of %s cannot be checked; refer to the field directly, like {{.Sender.Email}}", name) - return - } - w.fields(int(x.Pos), strings.Join(x.Ident, "."), name, held, x.Ident[1:]) case *parse.ChainNode: switch inner := x.Node.(type) { case *parse.IdentifierNode: - if topNames[inner.Ident] == SenderField { - text := inner.Ident + "." + strings.Join(x.Field, ".") - w.fields(int(inner.Pos), text, "$", scopeRoot, append([]string{inner.Ident}, x.Field...)) + if _, builtin := topNames[inner.Ident]; !builtin { + w.identifier(inner, false, dot) return } - w.identifier(inner, false) + head := "$" + if dot == scopeRoot { + head = "" + } + text := inner.Ident + "." + strings.Join(x.Field, ".") + w.fields(int(inner.Pos), text, head, scopeRoot, append([]string{inner.Ident}, x.Field...)) case *parse.PipeNode: w.pipe(inner, dot, false) } } } -func (w *walker) identifier(x *parse.IdentifierNode, calls bool) { +func (w *walker) identifier(x *parse.IdentifierNode, calls bool, dot scope) { if isFunc(x.Ident) { return } pos := int(x.Pos) - if _, ok := topNames[x.Ident]; !ok || calls { + canonical, ok := topNames[x.Ident] + if !ok || calls { if calls { w.fail(pos, "function %q is not defined", x.Ident) return @@ -253,43 +418,69 @@ func (w *walker) identifier(x *parse.IdentifierNode, calls bool) { w.fail(pos, "%s", unknownVariable(x.Ident)) return } - if strings.HasPrefix(w.src[pos:], x.Ident) { - // The alias spelling is kept, so a custom field of that name still wins. - w.edits = append(w.edits, edit{pos, pos + len(x.Ident), "$." + x.Ident}) + w.refs[canonical] = true + if !strings.HasPrefix(w.src[pos:], x.Ident) { + return } + prefix := "$." + if dot == scopeRoot { + prefix = "." + } + name := x.Ident // the alias spelling, so a custom field of that name still wins + if w.mode == forStore { + name = canonical + } + w.edits = append(w.edits, edit{pos, pos + len(x.Ident), prefix + name}) } // fields checks a selector chain on a value held in scope and canonicalises the // part that reaches into Sender, whose field set is fixed. text is the chain as // written, head the variable it starts from ("" for dot). func (w *walker) fields(pos int, text, head string, held scope, idents []string) { - var sender []string - prefix := head - switch held { - case scopeRoot: - if len(idents) < 2 || topNames[idents[0]] != SenderField { - return - } - sender, prefix = idents[1:], head+"."+SenderField - case scopeSender: - sender = idents - default: - return - } start := w.locate(pos, text) if start < 0 { - return + start = pos } - field, ok := senderNames[sender[0]] + switch held { + case scopeRoot: + canonical, builtin := topNames[idents[0]] + if builtin { + w.refs[canonical] = true + } + if builtin && canonical == SenderField { + if len(idents) > 1 { + w.sender(start, text, head+"."+SenderField, idents[1:]) + } + return + } + // Every other field of the data is text, which has no fields. + if len(idents) > 1 { + w.fail(start, "field %s has no field %q", idents[0], idents[1]) + } + case scopeSender: + w.sender(start, text, head, idents) + default: + what := "this value" + if head != "" { + what = head + } + w.fail(start, "fields of %s cannot be checked; refer to the field directly, like {{.Sender.Email}}", what) + } +} + +// sender checks the selectors after a Sender value and canonicalises the field +// name; prefix is the canonical way to reach that value. +func (w *walker) sender(start int, text, prefix string, fields []string) { + field, ok := senderNames[fields[0]] if !ok { - w.fail(start, "unknown sender field %q; the sender fields are %s", sender[0], senderList) + w.fail(start, "unknown sender field %q; the sender fields are %s", fields[0], senderList) return } - if len(sender) > 1 { - w.fail(start, "sender field %s has no field %q", field, sender[1]) + if len(fields) > 1 { + w.fail(start, "sender field %s has no field %q", field, fields[1]) return } - if rewritten := prefix + "." + field; rewritten != text { + if rewritten := prefix + "." + field; rewritten != text && strings.HasPrefix(w.src[start:], text) { w.edits = append(w.edits, edit{start, start + len(text), rewritten}) } } @@ -305,42 +496,35 @@ func (w *walker) locate(pos int, text string) int { return -1 } -func (w *walker) apply() string { - if len(w.edits) == 0 { - return w.src - } - sort.Slice(w.edits, func(i, j int) bool { return w.edits[i].start < w.edits[j].start }) - var b strings.Builder - last := 0 - for _, e := range w.edits { - if e.start < last { - continue - } - b.WriteString(w.src[last:e.start]) - b.WriteString(e.text) - last = e.end - } - b.WriteString(w.src[last:]) - return b.String() -} - func unknownVariable(name string) string { return fmt.Sprintf("unknown variable %q: write a contact field with a leading dot, like {{.%s}}; the built-in fields are %s", name, name, canonicalList) } -// rewriteSpacedInAction rewrites `.job title` and `.first-name` inside one -// action to `(index . "key")`, skipping string literals. -func rewriteSpacedInAction(action string) string { +// rewriteSpaced rewrites `.job title` and `.first-name` inside each action to +// `(index . "key")`, skipping string literals, and reports where it did. +func rewriteSpaced(src string) (string, []span) { var b strings.Builder - b.Grow(len(action)) + b.Grow(len(src)) + var spans []span + last := 0 + for _, loc := range ActionPattern.FindAllStringIndex(src, -1) { + b.WriteString(src[last:loc[0]]) + rewriteSpacedInAction(&b, src, loc[0], loc[1], &spans) + last = loc[1] + } + b.WriteString(src[last:]) + return b.String(), spans +} + +func rewriteSpacedInAction(b *strings.Builder, src string, from, to int, spans *[]span) { var quote byte // 0 = not in a string literal; '"' or '`' otherwise - for i := 0; i < len(action); { - c := action[i] + for i := from; i < to; { + c := src[i] switch { case quote != 0: b.WriteByte(c) - if c == '\\' && quote == '"' && i+1 < len(action) { - b.WriteByte(action[i+1]) // keep an escaped char verbatim + if c == '\\' && quote == '"' && i+1 < to { + b.WriteByte(src[i+1]) // keep an escaped char verbatim i += 2 continue } @@ -354,9 +538,11 @@ func rewriteSpacedInAction(action string) string { i++ case c == '.': // A nested struct selector must not consume the following function argument. - fieldStart := i == 0 || strings.ContainsRune("{( \t\r\n", rune(action[i-1])) - if m := spacedFieldRefAt.FindString(action[i:]); fieldStart && m != "" { - b.WriteString(`(index . "` + m[1:] + `")`) + fieldStart := i == from || strings.ContainsRune("{( \t\r\n", rune(src[i-1])) + if m := spacedFieldRefAt.FindString(src[i:to]); fieldStart && m != "" { + repl := `(index . "` + m[1:] + `")` + *spans = append(*spans, span{i, i + len(m), b.Len(), b.Len() + len(repl)}) + b.WriteString(repl) i += len(m) continue } @@ -367,5 +553,4 @@ func rewriteSpacedInAction(action string) string { i++ } } - return b.String() } diff --git a/internal/pkg/tmplvars/normalize_test.go b/internal/pkg/tmplvars/normalize_test.go index 33ff69c9c..9b629a4d5 100644 --- a/internal/pkg/tmplvars/normalize_test.go +++ b/internal/pkg/tmplvars/normalize_test.go @@ -8,27 +8,29 @@ import ( func TestNormalize(t *testing.T) { cases := []struct{ name, in, want string }{ {"canonical untouched", "Hi {{.FirstName}}", "Hi {{.FirstName}}"}, - {"bare snake", "Hi {{first_name}}", "Hi {{$.first_name}}"}, - {"bare camel", "Hi {{ firstName }}", "Hi {{ $.firstName }}"}, - {"bare lowercase", "{{company}} / {{company_name}}", "{{$.company}} / {{$.company_name}}"}, + {"bare snake", "Hi {{first_name}}", "Hi {{.first_name}}"}, + {"bare camel", "Hi {{ firstName }}", "Hi {{ .firstName }}"}, + {"bare lowercase", "{{company}} / {{company_name}}", "{{.company}} / {{.company_name}}"}, {"dotted alias is a field already", "{{.first_name}}", "{{.first_name}}"}, - {"bare in if", "{{if first_name}}x{{end}}", "{{if $.first_name}}x{{end}}"}, - {"bare in pipe", `{{first_name | default "there"}}`, `{{$.first_name | default "there"}}`}, - {"bare as argument", `{{default "there" first_name}}`, `{{default "there" $.first_name}}`}, - {"bare in eq", `{{if eq company "Acme"}}y{{end}}`, `{{if eq $.company "Acme"}}y{{end}}`}, + {"bare in if", "{{if first_name}}x{{end}}", "{{if .first_name}}x{{end}}"}, + {"bare in pipe", `{{first_name | default "there"}}`, `{{.first_name | default "there"}}`}, + {"bare as argument", `{{default "there" first_name}}`, `{{default "there" .first_name}}`}, + {"bare in eq", `{{if eq company "Acme"}}y{{end}}`, `{{if eq .company "Acme"}}y{{end}}`}, {"literal braces outside actions", "Use first_name or {first_name} in text", "Use first_name or {first_name} in text"}, {"string literal untouched", `{{default "first_name" .X}}`, `{{default "first_name" .X}}`}, {"spaced custom field", "{{.job title}}", `{{(index . "job title")}}`}, {"sender alias", "{{.Sender.first_name}}", "{{.Sender.FirstName}}"}, - {"sender bare", "{{sender.first_name}}", "{{$.Sender.FirstName}}"}, + {"sender bare", "{{sender.first_name}}", "{{.Sender.FirstName}}"}, {"sender variable", "{{$.sender.signature_html}}", "{{$.Sender.SignatureHTML}}"}, {"function untouched", "{{upper .FirstName}}", "{{upper .FirstName}}"}, - {"unsubscribe alias", "{{unsubscribe_link}}", "{{$.unsubscribe_link}}"}, + {"unsubscribe alias", "{{unsubscribe_link}}", "{{.unsubscribe_link}}"}, {"sender through a variable", "{{$s := .Sender}}{{$s.first_name}}", "{{$s := .Sender}}{{$s.FirstName}}"}, {"sender through with", "{{with .sender}}{{.signature_html}}{{end}}", "{{with .sender}}{{.SignatureHTML}}{{end}}"}, {"sender through root variable", "{{$r := .}}{{$r.Sender.email}}", "{{$r := .}}{{$r.Sender.Email}}"}, {"range element untouched", "{{range .Sender.Tags}}{{.}}{{end}}", "{{range .Sender.Tags}}{{.}}{{end}}"}, {"range variables untouched", "{{range $k, $v := .}}{{$k}}={{$v}}{{end}}", "{{range $k, $v := .}}{{$k}}={{$v}}{{end}}"}, + {"bare inside with uses the root", "{{with .Sender}}{{first_name}}{{end}}", "{{with .Sender}}{{$.first_name}}{{end}}"}, + {"sender through parentheses", "{{with (.Sender)}}{{.first_name}}{{end}}", "{{with (.Sender)}}{{.FirstName}}{{end}}"}, } for _, tc := range cases { got, err := Normalize(tc.in) @@ -52,6 +54,9 @@ func TestCheckRefusesWhatCannotRender(t *testing.T) { {"{{$s := .Sender}}{{$s.Bogus}}", `unknown sender field "Bogus"`}, {"{{with .Sender}}{{.Bogus}}{{end}}", `unknown sender field "Bogus"`}, {"{{range $k, $v := .}}{{$v.x}}{{end}}", "fields of $v cannot be checked"}, + {"{{.FirstName.Bogus}}", `field FirstName has no field "Bogus"`}, + {"{{first_name.Bogus}}", `field first_name has no field "Bogus"`}, + {`{{with .Sender | default .Sender}}{{.first_name}}{{end}}`, "fields of this value cannot be checked"}, } for _, tc := range cases { err := Check(tc.in) @@ -100,3 +105,75 @@ func TestAddAliasesLetsCustomFieldWin(t *testing.T) { t.Fatalf("got %v", data) } } + +func TestCheckScopesBranchVariables(t *testing.T) { + for _, ok := range []string{ + "{{$s := .Sender}}{{if .Company}}{{$s = .Company}}{{else}}{{$s.Email}}{{end}}", + "{{$s := .Sender}}{{if .X}}{{$s := .Other}}{{else}}{{$s.first_name}}{{end}}{{$s.Email}}", + "{{$s := .Sender}}{{with .Company}}{{$s := .}}{{else}}{{$s.Email}}{{end}}{{$s.Name}}", + "{{$s := .Sender}}{{range .Sender.Tags}}{{$s := .}}{{$s}}{{end}}{{$s.Name}}", + } { + if err := Check(ok); err != nil { + t.Errorf("%q: unexpected error %v", ok, err) + } + } + // A reassignment in a branch leaves the variable unknown after the structure. + if err := Check("{{$s := .Sender}}{{if .Company}}{{$s = .Company}}{{end}}{{$s.Email}}"); err == nil { + t.Error("a field of a variable a branch reassigned should be refused") + } +} + +func TestCanonicalizeStoresBareAliasesInCanonicalForm(t *testing.T) { + cases := []struct{ in, want string }{ + {"Hi {{first_name}}", "Hi {{.FirstName}}"}, + {"{{ company_name }} and {{companyName}}", "{{ .Company }} and {{.Company}}"}, + {`{{if first_name}}{{first_name | default "there"}}{{end}}`, `{{if .FirstName}}{{.FirstName | default "there"}}{{end}}`}, + {"{{with .Sender}}{{first_name}} / {{.first_name}}{{end}}", "{{with .Sender}}{{$.FirstName}} / {{.FirstName}}{{end}}"}, + {"{{.first_name}} {{.firstName}}", "{{.first_name}} {{.firstName}}"}, + {"{{sender.email}}", "{{.Sender.Email}}"}, + {"{{.job title}} {{first_name}} {{.dept-name}} {{last_name}}", "{{.job title}} {{.FirstName}} {{.dept-name}} {{.LastName}}"}, + {"first_name {first_name} {{form_link:abc123}} {{first_name}}", "first_name {first_name} {{form_link:abc123}} {{.FirstName}}"}, + {"{{if .X}}broken {{first_name}}", "{{if .X}}broken {{first_name}}"}, + {"no actions", "no actions"}, + } + for _, tc := range cases { + if got := Canonicalize(tc.in); got != tc.want { + t.Errorf("%q: got %q, want %q", tc.in, got, tc.want) + } + } +} + +func TestCheckHTMLRefusesEscaperBeforePipe(t *testing.T) { + if err := CheckHTML(`

{{html .FirstName | printf "%s"}}

`); err == nil { + t.Error("an html escaper before a pipe should be refused in an HTML body") + } + for _, ok := range []string{"", "

Hi {{.FirstName}}

", `x`, "

{{.missing}}

", `

{{.FirstName | html}}

`} { + if err := CheckHTML(ok); err != nil { + t.Errorf("%q: unexpected error %v", ok, err) + } + } + if err := CheckCopy(Part{Name: "body", Text: `{{urlquery .X | printf "%s"}}`, HTML: true}); err == nil || !strings.Contains(err.Error(), "the body") { + t.Errorf("CheckCopy should run the HTML check on an HTML part: %v", err) + } +} + +func TestReferences(t *testing.T) { + cases := []struct { + in string + want bool + }{ + {"Hi {{.FirstName}}", true}, + {"Hi {{first_name}}", true}, + {`{{.firstName | default "there"}}`, true}, + {`{{$.first_name}}`, true}, + {`{{printf "firstname"}}`, false}, + {"{{.firstname_source}}", false}, + {"{{.Sender.FirstName}}", false}, + {"firstname in prose", false}, + } + for _, tc := range cases { + if got := References(tc.in)["FirstName"]; got != tc.want { + t.Errorf("%q: got %v, want %v", tc.in, got, tc.want) + } + } +}