Debian Codegraph @

server/server_template.go

raw
1 package server
2
3 import (
4 "bytes"
5 "context"
6 "embed"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "os"
11 "path/filepath"
12 "regexp"
13 "strings"
14 "text/template/parse"
15 "time"
16
17 "gopkg.in/yaml.v2"
18 "heckel.io/ntfy/v2/model"
19 "heckel.io/ntfy/v2/template/gotext"
20 "heckel.io/ntfy/v2/util"
21 "heckel.io/ntfy/v2/util/sprig"
22 )
23
24 var (
25 //go:embed templates
26 templatesFs embed.FS // Contains template config files (e.g. grafana.yml, github.yml, ...)
27 templatesDir = "templates"
28
29 templateNameRegex = regexp.MustCompile(`^[-_A-Za-z0-9]+$`)
30
31 // templatePrintfLargeSizeRegex matches a printf directive whose width or precision is a star
32 // (taken from an argument) or has four or more digits, i.e. is at least 1000. It deliberately
33 // scans the flag/width/precision characters after a % without requiring a well-formed
34 // directive: fmt pads even malformed ones (e.g. "%000 9999999#" emits 10 MB), so anything
35 // unrecognized must still be caught.
36 templatePrintfLargeSizeRegex = regexp.MustCompile(`%[-+# 0-9.*\[\]]*(\*|[0-9]{4})`)
37
38 // templateMaxExecutionTime is the wall-clock deadline for a single template render, a DoS guard
39 // (GHSA-rhwf-xgc9-m9fp). It is a var (not a const) solely so tests can raise it; it is never
40 // mutated in production.
41 templateMaxExecutionTime = 100 * time.Millisecond
42 )
43
44 const (
45 templateMaxOutputBytes = 1024 * 1024 // Maximum number of bytes a template can output, used to prevent DoS attacks
46 templateMaxTemplateBytes = 32 * 1024 // Maximum size of a template (inline or from a template file), used to prevent DoS attacks
47 templateFileExtension = ".yml" // Template files must end with this extension
48 )
49
50 func (s *Server) handleBodyAsTemplatedTextMessage(ctx context.Context, m *model.Message, template templateMode, body *util.PeekedReadCloser, priorityStr string) error {
51 body, err := util.Peek(body, max(s.config.MessageSizeLimit, jsonBodyBytesLimit))
52 if err != nil {
53 return err
54 } else if body.LimitReached {
55 return errHTTPEntityTooLargeJSONBody
56 }
57 peekedBody := strings.TrimSpace(string(body.PeekedBytes))
58 if template.FileMode() {
59 if err := s.renderTemplateFromFile(ctx, m, template.FileName(), peekedBody); err != nil {
60 return err
61 }
62 } else {
63 if err := s.renderTemplateFromParams(ctx, m, peekedBody, priorityStr); err != nil {
64 return err
65 }
66 }
67 if len(m.Title) > s.config.MessageSizeLimit || len(m.Message) > s.config.MessageSizeLimit {
68 return errHTTPBadRequestTemplateMessageTooLarge
69 }
70 return nil
71 }
72
73 // renderTemplateFromFile transforms the JSON message body according to a template from the filesystem.
74 // The template file must be in the templates directory, or in the configured template directory.
75 func (s *Server) renderTemplateFromFile(ctx context.Context, m *model.Message, templateName, peekedBody string) error {
76 if !templateNameRegex.MatchString(templateName) {
77 return errHTTPBadRequestTemplateFileNotFound
78 }
79 templateContent, _ := templatesFs.ReadFile(filepath.Join(templatesDir, templateName+templateFileExtension)) // Read from the embedded filesystem first
80 if s.config.TemplateDir != "" {
81 if b, _ := os.ReadFile(filepath.Join(s.config.TemplateDir, templateName+templateFileExtension)); len(b) > 0 {
82 templateContent = b
83 }
84 }
85 if len(templateContent) == 0 {
86 return errHTTPBadRequestTemplateFileNotFound
87 }
88 var tpl templateFile
89 if err := yaml.Unmarshal(templateContent, &tpl); err != nil {
90 return errHTTPBadRequestTemplateFileInvalid
91 }
92 var err error
93 if tpl.Message != nil {
94 if m.Message, err = s.renderTemplate(ctx, templateName+" (message)", *tpl.Message, peekedBody); err != nil {
95 return err
96 }
97 }
98 if tpl.Title != nil {
99 if m.Title, err = s.renderTemplate(ctx, templateName+" (title)", *tpl.Title, peekedBody); err != nil {
100 return err
101 }
102 }
103 if tpl.Priority != nil {
104 renderedPriority, err := s.renderTemplate(ctx, templateName+" (priority)", *tpl.Priority, peekedBody)
105 if err != nil {
106 return err
107 }
108 if m.Priority, err = util.ParsePriority(renderedPriority); err != nil {
109 return errHTTPBadRequestPriorityInvalid
110 }
111 }
112 return nil
113 }
114
115 // renderTemplateFromParams transforms the JSON message body according to the inline template in the
116 // message, title, and priority parameters.
117 func (s *Server) renderTemplateFromParams(ctx context.Context, m *model.Message, peekedBody string, priorityStr string) error {
118 var err error
119 if m.Message, err = s.renderTemplate(ctx, "priority query parameter", m.Message, peekedBody); err != nil {
120 return err
121 }
122 if m.Title, err = s.renderTemplate(ctx, "title query parameter", m.Title, peekedBody); err != nil {
123 return err
124 }
125 if priorityStr != "" {
126 renderedPriority, err := s.renderTemplate(ctx, "priority query parameter", priorityStr, peekedBody)
127 if err != nil {
128 return err
129 }
130 if m.Priority, err = util.ParsePriority(renderedPriority); err != nil {
131 return errHTTPBadRequestPriorityInvalid
132 }
133 }
134 return nil
135 }
136
137 // renderTemplate renders a template with the given JSON source data.
138 func (s *Server) renderTemplate(ctx context.Context, name, tpl, source string) (string, error) {
139 if len(tpl) > templateMaxTemplateBytes {
140 return "", errHTTPBadRequestTemplateTooLarge
141 }
142 var data any
143 if err := json.Unmarshal([]byte(source), &data); err != nil {
144 return "", errHTTPBadRequestTemplateMessageNotJSON
145 }
146 t, err := gotext.New("").Funcs(sprig.TxtFuncMap()).Funcs(gotext.FuncMap{"printf": templatePrintf}).Parse(tpl)
147 if err != nil {
148 return "", errHTTPBadRequestTemplateInvalid.Wrap("%s", err.Error())
149 }
150 if templateUsesDisallowedFeatures(t) {
151 return "", errHTTPBadRequestTemplateDisallowedFunctionCalls
152 }
153 // Bail out of runaway templates (GHSA-rhwf-xgc9-m9fp). The deadline starts here, after the body
154 // has already been read, so a slow upload is not counted against it. Deriving from the request
155 // context means a client disconnect aborts the render too.
156 execCtx, cancel := context.WithTimeout(ctx, templateMaxExecutionTime)
157 defer cancel()
158 var buf bytes.Buffer
159 limitWriter := util.NewLimitWriter(&buf, util.NewFixedLimiter(templateMaxOutputBytes))
160 if err := t.ExecuteContext(execCtx, limitWriter, data); err != nil {
161 if errors.Is(err, context.DeadlineExceeded) {
162 return "", errHTTPBadRequestTemplateExecutionTimeout
163 }
164 return "", errHTTPBadRequestTemplateExecuteFailed.Wrap("template %s: %s", name, err.Error())
165 }
166 return strings.TrimSpace(strings.ReplaceAll(buf.String(), "\\n", "\n")), nil // replace any remaining "\n" (those outside of template curly braces) with newlines
167 }
168
169 // templateUsesDisallowedFeatures reports whether the parsed template defines or invokes a
170 // sub-template ({{define}}/{{block}}/{{template}}) or uses the {{call}} builtin. None are useful for
171 // ntfy's JSON-data templates. Checking the parse tree (rather than the raw string) catches every
172 // syntactic form -- e.g. {{if call .x}} or {{$y := call .x}} -- that a regex would miss.
173 func templateUsesDisallowedFeatures(t *gotext.Template) bool {
174 if len(t.Templates()) > 1 { // {{define}}/{{block}} create additional associated templates
175 return true
176 }
177 return treeContainsDisallowedNode(t.Root)
178 }
179
180 // treeContainsDisallowedNode reports whether the parse tree contains a {{template}}/{{block}}
181 // invocation or a {{call}} builtin, descending into pipes and command arguments (where {{call}} can
182 // appear anywhere a function is allowed).
183 func treeContainsDisallowedNode(node parse.Node) bool {
184 switch n := node.(type) {
185 case *parse.ListNode:
186 if n == nil {
187 return false
188 }
189 for _, child := range n.Nodes {
190 if treeContainsDisallowedNode(child) {
191 return true
192 }
193 }
194 case *parse.ActionNode:
195 return treeContainsDisallowedNode(n.Pipe)
196 case *parse.RangeNode:
197 return treeContainsDisallowedNode(n.Pipe) || treeContainsDisallowedNode(n.List) || treeContainsDisallowedNode(n.ElseList)
198 case *parse.IfNode:
199 return treeContainsDisallowedNode(n.Pipe) || treeContainsDisallowedNode(n.List) || treeContainsDisallowedNode(n.ElseList)
200 case *parse.WithNode:
201 return treeContainsDisallowedNode(n.Pipe) || treeContainsDisallowedNode(n.List) || treeContainsDisallowedNode(n.ElseList)
202 case *parse.TemplateNode: // {{template}} or {{block}} invocation
203 return true
204 case *parse.ChainNode: // A term followed by field accesses, e.g. (call .x).y
205 return treeContainsDisallowedNode(n.Node)
206 case *parse.PipeNode:
207 if n == nil {
208 return false
209 }
210 for _, cmd := range n.Cmds {
211 if treeContainsDisallowedNode(cmd) {
212 return true
213 }
214 }
215 case *parse.CommandNode:
216 for _, arg := range n.Args {
217 if treeContainsDisallowedNode(arg) {
218 return true
219 }
220 }
221 case *parse.IdentifierNode: // a function name; {{call}} is the disallowed builtin
222 return n.Ident == "call"
223 }
224 return false
225 }
226
227 // templatePrintf is the template builtin printf, guarded against memory amplification: fmt
228 // allows widths and precisions up to 1e6 per verb, so a small template like
229 // {{printf "%999999d%999999d..." ...}} can allocate gigabytes inside a single fmt call -- and the
230 // executor's cancellation context is only checked between template nodes, never inside one.
231 // Widths and precisions of 1000 or more are therefore rejected, as is the star (*) form, which
232 // takes the width from an argument. Combined with the template size limit, this bounds a single
233 // render to a few MB. Registered via Funcs, which takes precedence over the builtin, and checked
234 // at call time so a format string assembled during execution is covered too.
235 func templatePrintf(format string, args ...any) (string, error) {
236 if templatePrintfLargeSizeRegex.MatchString(strings.ReplaceAll(format, "%%", "")) { // Strip escaped percent signs, they take no width
237 return "", errors.New("printf width or precision too large")
238 }
239 return fmt.Sprintf(format, args...), nil
240 }