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.
```
{{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) + } + } +}