| 1 |
# `template/gotext/` -- vendored `text/template` with context cancellation |
| 2 |
|
| 3 |
This directory is a **verbatim copy of Go's standard-library `text/template` package**, plus one |
| 4 |
small patch that adds context-aware execution (`ExecuteContext`). It exists for exactly one reason: |
| 5 |
to stop **user-supplied** message templates (`Template: yes`, see the [templating docs](https://ntfy.sh/docs/publish/#message-templating)) |
| 6 |
from burning CPU. |
| 7 |
|
| 8 |
- **Source:** Go stdlib `text/template` (+ `internal/fmtsort`), `$(go env GOROOT)/src` |
| 9 |
- **Version:** pinned in the repo-root [`.go-version`](../../.go-version); recorded in `GENERATED_FROM` |
| 10 |
- **Local modifications:** `patches/` (see [The patch](#the-patch)) |
| 11 |
- **Update mechanism:** Manual -- `make update-template`, then commit (never autorolled; see [Updating](#updating-when-bumping-the-go-toolchain)) |
| 12 |
|
| 13 |
## Why this exists |
| 14 |
|
| 15 |
ntfy lets users send a Go template that is rendered against a JSON body. Go's `text/template` |
| 16 |
**cannot be interrupted mid-execution** -- there is no context, no deadline, no cancellation |
| 17 |
([golang/go#31107](https://github.com/golang/go/issues/31107) proposed `ExecuteContext` but was |
| 18 |
declined, over a bundled context-*values* feature, not cancellation itself). So a crafted template |
| 19 |
with a tight or nested `{{range}}` (e.g. ranging over a large JSON array with a big loop body that |
| 20 |
writes no output) can run for tens of seconds on a single request. That is a CPU denial of service |
| 21 |
(GHSA-rhwf-xgc9-m9fp). |
| 22 |
|
| 23 |
There is no way to add an interrupt from the outside -- the executor's per-node `walk` loop is |
| 24 |
unexported. The only robust fix is to patch the executor itself. Rather than reach for fragile |
| 25 |
heuristics (guessing iteration counts, wrapping every function, etc.), we vendor the package and add |
| 26 |
the cancellation half of #31107 as a patch: `ExecuteContext(ctx, ...)` that aborts with `ctx.Err()` |
| 27 |
when `ctx` is canceled or its deadline passes. The check is a **single poll inside `walk`** of an |
| 28 |
atomic flag that a `context.AfterFunc` watcher flips -- so it bounds CPU for *any* template shape |
| 29 |
(cheap loops and expensive functions alike), it is exact (observed within one node), and it adds no |
| 30 |
measurable overhead. If #31107's cancellation half ever lands upstream, this fork can be deleted and |
| 31 |
the call site keeps compiling unchanged. |
| 32 |
|
| 33 |
The one user-facing execution site (`server/server_template.go` `renderTemplate`) wraps execution in |
| 34 |
`context.WithTimeout` and calls `ExecuteContext`, mapping `context.DeadlineExceeded` to a `400`. |
| 35 |
Trusted templates (operator config: Twilio, `cmd/serve.go`) keep using the standard library -- they |
| 36 |
are not user-supplied. |
| 37 |
|
| 38 |
## What's here |
| 39 |
|
| 40 |
| File | Origin | |
| 41 |
|------|--------| |
| 42 |
| `*.go` (`exec.go`, `funcs.go`, `template.go`, `option.go`, `helper.go`, `doc.go`) | verbatim from `$(go env GOROOT)/src/text/template/`, enumerated with `go list` so files added/removed upstream are picked up automatically | |
| 43 |
| `fmtsort/sort.go` | verbatim from `$(go env GOROOT)/src/internal/fmtsort/` -- `exec.go` needs it, and `internal/...` packages can't be imported from outside GOROOT, so it comes along | |
| 44 |
| `patches/0001-exec-context.patch` | our only real change (see below) | |
| 45 |
| `GENERATED_FROM` | the exact Go version `make update-template` last regenerated this copy from; provenance, written by that target | |
| 46 |
|
| 47 |
The Go toolchain version this copy is pinned to lives in the repo-root [`.go-version`](../../.go-version) |
| 48 |
file (the single source of truth, also consumed by CI and the `make` targets below). `GENERATED_FROM` |
| 49 |
must equal it -- `make check` fails otherwise (see below). |
| 50 |
|
| 51 |
We do **not** vendor `text/template/parse` -- it's a normal importable stdlib package and stays a |
| 52 |
plain import. |
| 53 |
|
| 54 |
## The patch |
| 55 |
|
| 56 |
`patches/` is a quilt-style ordered series (apply `0001-*`, then `0002-*`, ...). Today there is just |
| 57 |
`0001-exec-context.patch` -- small, purely additive, and touching only `exec.go`: |
| 58 |
|
| 59 |
- adds `ctx context.Context` and a shared `cancelled *atomic.Bool` to the executor `state` |
| 60 |
- adds `ExecuteContext` / `ExecuteTemplateContext`; `Execute` / `ExecuteTemplate` become |
| 61 |
`context.Background()` wrappers, so their behavior and cost are unchanged |
| 62 |
- when `ctx.Done() != nil`, arms one `context.AfterFunc` watcher that flips the flag; `walk` polls it |
| 63 |
per node and aborts via a `cancelError` that `errRecover` strips to the bare `ctx.Err()` |
| 64 |
(`errors.Is(err, context.DeadlineExceeded)`) |
| 65 |
|
| 66 |
The flag is a `*atomic.Bool` (not a value) because `walkTemplate` copies `state` for nested |
| 67 |
`{{template}}` invocations; a shared pointer keeps one flag across all copies and avoids `go vet` |
| 68 |
copylocks. `template.go` is unchanged -- the context is per-call, not stored on the `Template`. |
| 69 |
|
| 70 |
Two *mechanical* transforms are applied by `make update-template` with `sed`, **not** the patch -- |
| 71 |
renaming the package to `gotext`, and rewriting the `internal/fmtsort` import to |
| 72 |
`heckel.io/ntfy/v2/template/gotext/fmtsort`. Keeping them out of the patch means they apply to |
| 73 |
whatever files `go list` returns, so they survive upstream files being added or removed. (These two |
| 74 |
transforms are also the only difference between our patch and the upstream `text/template` diff.) |
| 75 |
|
| 76 |
Keeping the patch tiny (cancellation only, on one stable file) is deliberate: it makes re-basing |
| 77 |
onto a new Go release cheap. |
| 78 |
|
| 79 |
## Updating (when bumping the Go toolchain) |
| 80 |
|
| 81 |
The copy is **pinned to the Go version in the root `.go-version`**, so it's not frozen -- re-syncing |
| 82 |
on a Go bump pulls in all upstream fixes for free. `.go-version` is authoritative and hand-edited; to |
| 83 |
bump the toolchain: edit `.go-version`, install that toolchain |
| 84 |
(`go install golang.org/dl/<version>@latest && <version> download`), then re-sync: |
| 85 |
|
| 86 |
``` |
| 87 |
make update-template # copies the files from your GOROOT and re-applies patches/*.patch |
| 88 |
``` |
| 89 |
|
| 90 |
`make update-template` **errors** unless your local Go matches `.go-version` -- it validates against |
| 91 |
the pin, it never writes it. If the patch hunks no longer apply against the new release, refresh the |
| 92 |
patch as part of the bump. |
| 93 |
|
| 94 |
`make template-check` (wired into `make check`) has two layers: |
| 95 |
|
| 96 |
1. **Marker check (ungated, runs on any toolchain):** fails if `GENERATED_FROM` != `.go-version`, i.e. |
| 97 |
someone bumped the pin but forgot `make update-template` (or vice versa). This catches the common |
| 98 |
mistake locally, on any developer's Go. |
| 99 |
2. **Content check (gated to the pinned Go):** re-derives the copy from `GOROOT + patches` and diffs it |
| 100 |
against what's committed, catching hand-edits and patch problems. It no-ops on a non-pinned |
| 101 |
toolchain so it never fails spuriously. |
| 102 |
|
| 103 |
CI installs exactly `.go-version` (`go-version-file`), so both layers run there. `make release` |
| 104 |
additionally refuses to run off the pinned Go, so the content check is never skipped for a release. |
| 105 |
|
| 106 |
## License |
| 107 |
|
| 108 |
These files are copyright The Go Authors, under the BSD-3-Clause license (headers preserved in each |
| 109 |
file). That is compatible with ntfy's Apache-2.0 / GPLv2 licensing. |