Files

310 lines
8.9 KiB
Go

package service
import (
"bytes"
"encoding/json"
"encoding/xml"
"fmt"
"regexp"
"strings"
"text/template"
"text/template/parse"
)
// apiContext is the place of an API sender request a template writes to. The
// values a template inserts are escaped for that place.
type apiContext int
const (
// apiContextPlain is a body of an unknown kind, values go in as they are
apiContextPlain apiContext = iota
// apiContextJSON is a JSON body, values are escaped for a JSON string
apiContextJSON
// apiContextURL is the request URL or a form body
apiContextURL
// apiContextXML is an XML body
apiContextXML
// apiContextHeader is a header key or value
apiContextHeader
)
// names of the functions that escape for a place. They are added to the end
// of a template action by escapeAPITemplate.
const (
apiEscapeJSONFunc = "apiEscapeJSON"
apiEscapeURLFunc = "apiEscapeURL"
apiEscapeXMLFunc = "apiEscapeXML"
apiEscapeHeaderFunc = "apiEscapeHeader"
)
// apiRecipientFields are the template values that hold data of a recipient.
// It comes from an import or a directory, not from the operator. The content
// of the message counts too, it is rendered with the same data.
var apiRecipientFields = map[string]bool{
"FirstName": true, "LastName": true, "Email": true, "To": true, "Phone": true,
"ExtraIdentifier": true, "Position": true, "Department": true, "City": true,
"Country": true, "Misc": true, "RandomRecipient": true,
"Content": true, "ContentRaw": true,
}
// apiTemplateAction matches one template action
var apiTemplateAction = regexp.MustCompile(`(?s)\{\{.*?\}\}`)
// jsonStringBody returns s as the inside of a JSON string, without the quotes
func jsonStringBody(s string) (string, error) {
var buf bytes.Buffer
encoder := json.NewEncoder(&buf)
encoder.SetEscapeHTML(false)
if err := encoder.Encode(s); err != nil {
return "", err
}
// Encode adds a newline and the quotes
out := strings.TrimSpace(buf.String())
return out[1 : len(out)-1], nil
}
// apiString is the text a template prints for a value. A value that is not
// set prints the same text as without an escape function.
func apiString(v any) string {
if v == nil {
return "<no value>"
}
return fmt.Sprint(v)
}
// apiEscapeFuncs are the escape functions, added to the functions of every
// API sender template
func apiEscapeFuncs() template.FuncMap {
return template.FuncMap{
apiEscapeJSONFunc: func(v any) (string, error) {
return jsonStringBody(apiString(v))
},
apiEscapeURLFunc: func(v any) string {
s := template.URLQueryEscaper(apiString(v))
// alone in a path these would step out of the folder
if s == "." || s == ".." {
return strings.ReplaceAll(s, ".", "%2E")
}
return s
},
apiEscapeXMLFunc: func(v any) (string, error) {
var buf bytes.Buffer
if err := xml.EscapeText(&buf, []byte(apiString(v))); err != nil {
return "", err
}
return buf.String(), nil
},
// a header can not hold a line break or another control character
apiEscapeHeaderFunc: func(v any) string {
return strings.Map(func(r rune) rune {
if r < 0x20 || r == 0x7f {
return -1
}
return r
}, apiString(v))
},
}
}
// apiBodyContext tells what kind of body an API sender sends, from its
// content type header and else from how the body starts
func apiBodyContext(contentType string, body string) apiContext {
contentType = strings.ToLower(contentType)
switch {
case strings.Contains(contentType, "json"):
return apiContextJSON
case strings.Contains(contentType, "x-www-form-urlencoded"):
return apiContextURL
case strings.Contains(contentType, "xml"):
return apiContextXML
}
// the text of the body that is not a template action
start := strings.TrimSpace(apiTemplateAction.ReplaceAllString(body, ""))
switch {
case strings.HasPrefix(start, "{"), strings.HasPrefix(start, "["):
return apiContextJSON
case strings.HasPrefix(start, "<"):
return apiContextXML
}
return apiContextPlain
}
// parseAPITemplate parses an API sender template and makes every value it
// inserts escaped for the place ctx
func parseAPITemplate(name string, text string, funcs template.FuncMap, ctx apiContext) (*template.Template, error) {
t, err := template.New(name).Funcs(funcs).Funcs(apiEscapeFuncs()).Parse(text)
if err != nil {
return nil, err
}
for _, each := range t.Templates() {
if each.Tree != nil && each.Tree.Root != nil {
escapeAPINode(each.Tree.Root, ctx)
}
}
return t, nil
}
// escapeAPINode walks a parsed template and adds the escape function of ctx
// to the end of every action that prints a value
func escapeAPINode(node parse.Node, ctx apiContext) {
switch n := node.(type) {
case *parse.ListNode:
if n == nil {
return
}
for _, each := range n.Nodes {
escapeAPINode(each, ctx)
}
case *parse.ActionNode:
// an action that only sets a variable prints nothing
if len(n.Pipe.Decl) > 0 {
return
}
if name := apiEscapeFor(n.Pipe, ctx); name != "" {
n.Pipe.Cmds = append(n.Pipe.Cmds, &parse.CommandNode{
NodeType: parse.NodeCommand,
Args: []parse.Node{parse.NewIdentifier(name).SetPos(n.Pos)},
})
}
case *parse.IfNode:
escapeAPINode(n.List, ctx)
escapeAPINode(n.ElseList, ctx)
case *parse.RangeNode:
escapeAPINode(n.List, ctx)
escapeAPINode(n.ElseList, ctx)
case *parse.WithNode:
escapeAPINode(n.List, ctx)
escapeAPINode(n.ElseList, ctx)
}
}
// apiEscapeFor returns the escape function an action needs in ctx, or an
// empty name when its value goes in as it is
func apiEscapeFor(pipe *parse.PipeNode, ctx apiContext) string {
switch ctx {
case apiContextJSON:
// Content is escaped for JSON when it is made, and ContentRaw is the
// same content left as it is on purpose. A custom field is written
// by the operator and may hold a piece of JSON.
if apiPipeReadsOnly(pipe, apiJSONAsWritten) {
return ""
}
return apiEscapeJSONFunc
case apiContextHeader:
return apiEscapeHeaderFunc
case apiContextURL, apiContextXML:
// a value of the operator, such as a custom field with a whole URL
// or a piece of markup, goes in as written. Only what can hold data
// of the recipient is escaped, and not a second time.
if !apiPipeHasRecipientData(pipe) {
return ""
}
last := apiLastFunc(pipe)
if ctx == apiContextURL {
if last == "urlEscape" {
return ""
}
return apiEscapeURLFunc
}
// ContentRaw alone is the content as it is on purpose, as in JSON
if last == "htmlEscape" || apiPipeReadsOnly(pipe, apiXMLAsWritten) {
return ""
}
return apiEscapeXMLFunc
}
return ""
}
// values that go into a JSON or XML body as they are
var (
apiJSONAsWritten = map[string]bool{
"Content": true, "ContentRaw": true,
"CustomField1": true, "CustomField2": true, "CustomField3": true, "CustomField4": true,
}
apiXMLAsWritten = map[string]bool{"ContentRaw": true}
)
// apiPipeReadsOnly reports whether an action reads values of the template
// data, and only ones named in allowed, such as {{.Content}} or
// {{$.Content | printf "%s"}}
func apiPipeReadsOnly(pipe *parse.PipeNode, allowed map[string]bool) bool {
found := false
var only func(node parse.Node) bool
only = func(node parse.Node) bool {
switch n := node.(type) {
case *parse.FieldNode:
found = true
return len(n.Ident) > 0 && allowed[n.Ident[0]]
case *parse.VariableNode:
// $.Content reads a value of the data, any other variable may
// hold anything
found = true
return len(n.Ident) > 1 && n.Ident[0] == "$" && allowed[n.Ident[1]]
case *parse.DotNode:
return false
case *parse.ChainNode:
return only(n.Node)
case *parse.PipeNode:
for _, cmd := range n.Cmds {
for _, arg := range cmd.Args {
if !only(arg) {
return false
}
}
}
}
return true
}
return only(pipe) && found
}
// apiLastFunc returns the name of the function the action ends with
func apiLastFunc(pipe *parse.PipeNode) string {
if len(pipe.Cmds) == 0 {
return ""
}
last := pipe.Cmds[len(pipe.Cmds)-1]
if len(last.Args) == 0 {
return ""
}
if ident, ok := last.Args[0].(*parse.IdentifierNode); ok {
return ident.Ident
}
return ""
}
// apiPipeHasRecipientData reports whether an action can print data of the
// recipient: it names a recipient field, or reads the whole data or a
// variable, which may hold one
func apiPipeHasRecipientData(pipe *parse.PipeNode) bool {
for _, cmd := range pipe.Cmds {
for _, arg := range cmd.Args {
if apiNodeHasRecipientData(arg) {
return true
}
}
}
return false
}
func apiNodeHasRecipientData(node parse.Node) bool {
switch n := node.(type) {
case *parse.FieldNode:
return len(n.Ident) > 0 && apiRecipientFields[n.Ident[0]]
case *parse.VariableNode:
// $.FirstName reads a field of the data, any other variable may
// hold anything
if len(n.Ident) > 1 && n.Ident[0] == "$" {
return apiRecipientFields[n.Ident[1]]
}
return true
case *parse.DotNode:
return true
case *parse.ChainNode:
return apiNodeHasRecipientData(n.Node)
case *parse.PipeNode:
return apiPipeHasRecipientData(n)
}
return false
}