Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ All notable changes to this project will be documented in this file.
- **Improvement**: Building a segment takes the same time for each batch of contacts, however far the build has gone, instead of slowing down as it goes (#571). On a workspace with hundreds of thousands of contacts, the daily update of segments with relative dates no longer keeps the database busy for over an hour. Contacts created or deleted during a build no longer make it skip or repeat others.

- **Security**: Liquid outputs (`{{ }}`, `echo`, `cycle`) in the HTML of emails are HTML-escaped, so a value of the data, such as a contact field filled in a public form, can no longer add markup or links to an email. Data meant to be HTML, such as a feed that holds an HTML block, needs the new `raw` filter: `{{ global_feed.html | raw }}`; so does a value written into CSS (`mj-style`, a `<style>`) or a script, for data you trust only. Outputs already escaped with `escape` are not escaped twice, also through `newline_to_br`, `strip` or `truncate`; the text of a `capture` is not escaped; the subject and the text version are not escaped. A filter that writes HTML from the data, such as `{{ bio | newline_to_br }}`, now shows its `<br />` as text: write `{{ bio | escape | newline_to_br }}`. In the safe-mjml engine, escaped text placed between components can no longer become a component.
- **Security**: A template preview, creation or update whose request is larger than 1 MB is refused (413), and the Liquid of one email stops after 10 seconds or a fixed amount of work for all its blocks together, where each block had its own limits.
- **Fix**: Liquid's `url_decode` filter keeps a value that holds a lone `%` (as in `50%`) instead of rendering nothing, and `escape` writes quotes as `&quot;`. Notifuse renders Liquid with liquidgo v5.11.3.
- **Fix**: In Liquid, `{{ list[-1] }}` reads the last item of a list, a `{% comment -%}` no longer removes the space after its `{% endcomment %}`, and `{{ list['1'] }}` (an index in quotes) reads nothing, as in Shopify Liquid; `{{ order.items.0.sku }}` still reads the first item.

Expand Down
40 changes: 31 additions & 9 deletions internal/http/template_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,16 +120,42 @@ func (h *TemplateHandler) handleGet(w http.ResponseWriter, r *http.Request) {
})
}

// maxTemplateRequestBytes bounds the body of templates.create, templates.update and
// templates.compile. A template of the gallery weighs 18 to 23 KB per language, and 136 KB
// with all its languages; a larger body is refused before it is parsed, since a template is
// compiled again at every send and its cost grows with its size.
const maxTemplateRequestBytes = 1 << 20

// decodeTemplateRequest decodes a template request body of at most maxTemplateRequestBytes
// into v. It answers the request and returns false when the body is too large (413) or is
// not valid JSON (400, with the decoder's message when detailed is true).
func (h *TemplateHandler) decodeTemplateRequest(w http.ResponseWriter, r *http.Request, v interface{}, detailed bool) bool {
err := json.NewDecoder(middleware.MaxBytesReader(w, r, maxTemplateRequestBytes)).Decode(v)
if err == nil {
return true
}
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
WriteJSONError(w, fmt.Sprintf("Request body too large: a template request is limited to %d bytes", maxTemplateRequestBytes), http.StatusRequestEntityTooLarge)
return false
}
h.logger.WithField("error", err.Error()).Error("Failed to decode request body")
if detailed {
WriteJSONError(w, err.Error(), http.StatusBadRequest)
} else {
WriteJSONError(w, "Invalid request body", http.StatusBadRequest)
}
return false
}

func (h *TemplateHandler) handleCreate(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
WriteJSONError(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}

var req domain.CreateTemplateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
h.logger.WithField("error", err.Error()).Error("Failed to decode request body")
WriteJSONError(w, "Invalid request body", http.StatusBadRequest)
if !h.decodeTemplateRequest(w, r, &req, false) {
return
}

Expand Down Expand Up @@ -179,9 +205,7 @@ func (h *TemplateHandler) handleUpdate(w http.ResponseWriter, r *http.Request) {
}

var req domain.UpdateTemplateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
h.logger.WithField("error", err.Error()).Error("Failed to decode request body")
WriteJSONError(w, "Invalid request body", http.StatusBadRequest)
if !h.decodeTemplateRequest(w, r, &req, false) {
return
}

Expand Down Expand Up @@ -270,9 +294,7 @@ func (h *TemplateHandler) handleCompile(w http.ResponseWriter, r *http.Request)
}

var req domain.CompileTemplateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
h.logger.WithField("error", err.Error()).Error("Failed to decode compile request body")
WriteJSONError(w, err.Error(), http.StatusBadRequest)
if !h.decodeTemplateRequest(w, r, &req, true) {
return
}

Expand Down
34 changes: 34 additions & 0 deletions internal/http/template_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -1397,3 +1398,36 @@ func TestTemplateHandler_HandleDelete_ErrorMapping(t *testing.T) {
})
}
}

// A template request body over 1 MiB is refused with 413 before it is parsed, on the three
// endpoints that take a template, and the service is never called. A body just under the limit
// is decoded and goes on to the request's own validation.
func TestTemplateHandler_RequestBodyLimit(t *testing.T) {
const limit = 1 << 20
_, _, serverURL, secretKey, cleanup := setupTemplateHandlerTest(t)
defer cleanup()
token := createTestToken(secretKey)

// bodyOf is a JSON object of exactly size bytes, with a name the requests do not read.
bodyOf := func(size int) string {
head, tail := `{"workspace_id":"workspace123","padding":"`, `"}`
return head + strings.Repeat("a", size-len(head)-len(tail)) + tail
}

for _, endpoint := range []string{"templates.create", "templates.update", "templates.compile"} {
t.Run(endpoint+" over the limit", func(t *testing.T) {
resp := sendRequest(t, http.MethodPost, serverURL+"/api/"+endpoint, token, bodyOf(limit+1))
defer func() { _ = resp.Body.Close() }()
assert.Equal(t, http.StatusRequestEntityTooLarge, resp.StatusCode)
var body map[string]interface{}
require.NoError(t, json.NewDecoder(resp.Body).Decode(&body))
assert.Contains(t, body["error"], "Request body too large")
})
t.Run(endpoint+" at the limit", func(t *testing.T) {
resp := sendRequest(t, http.MethodPost, serverURL+"/api/"+endpoint, token, bodyOf(limit))
defer func() { _ = resp.Body.Close() }()
// The request is decoded and fails its own validation, which a padding-only body does.
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
})
}
}
39 changes: 39 additions & 0 deletions openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -4155,6 +4155,19 @@
}
}
},
"413": {
"description": "The request body is larger than 1 MiB (1,048,576 bytes), the limit of a template request.\nA template of the gallery weighs about 20 KB per language.\n",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"example": {
"error": "Request body too large: a template request is limited to 1048576 bytes"
}
}
}
},
"500": {
"description": "Internal server error",
"content": {
Expand Down Expand Up @@ -4248,6 +4261,19 @@
}
}
},
"413": {
"description": "The request body is larger than 1 MiB (1,048,576 bytes), the limit of a template request.\nA template of the gallery weighs about 20 KB per language.\n",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"example": {
"error": "Request body too large: a template request is limited to 1048576 bytes"
}
}
}
},
"500": {
"description": "Internal server error",
"content": {
Expand Down Expand Up @@ -4404,6 +4430,19 @@
}
}
},
"413": {
"description": "The request body is larger than 1 MiB (1,048,576 bytes), the limit of a template request.\nA template of the gallery weighs about 20 KB per language.\n",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"example": {
"error": "Request body too large: a template request is limited to 1048576 bytes"
}
}
}
},
"500": {
"description": "Internal server error",
"content": {
Expand Down
30 changes: 30 additions & 0 deletions openapi/paths/templates.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,16 @@
invalidId:
value:
error: id must contain only letters, numbers, underscores, and hyphens
'413':
description: |
The request body is larger than 1 MiB (1,048,576 bytes), the limit of a template request.
A template of the gallery weighs about 20 KB per language.
content:
application/json:
schema:
$ref: '../components/schemas/common.yaml#/ErrorResponse'
example:
error: 'Request body too large: a template request is limited to 1048576 bytes'
'401':
description: Unauthorized - invalid or missing authentication token
content:
Expand Down Expand Up @@ -312,6 +322,16 @@
summary: The update is in the other editor mode
value:
error: "cannot change editor mode: template was created in 'code' mode and its mode can't be changed; create a new template in 'visual' mode and copy the content with Import or Export MJML"
'413':
description: |
The request body is larger than 1 MiB (1,048,576 bytes), the limit of a template request.
A template of the gallery weighs about 20 KB per language.
content:
application/json:
schema:
$ref: '../components/schemas/common.yaml#/ErrorResponse'
example:
error: 'Request body too large: a template request is limited to 1048576 bytes'
'401':
description: Unauthorized - invalid or missing authentication token
content:
Expand Down Expand Up @@ -425,6 +445,16 @@
$ref: '../components/schemas/common.yaml#/ErrorResponse'
example:
error: "Compilation failed: Invalid MJML syntax"
'413':
description: |
The request body is larger than 1 MiB (1,048,576 bytes), the limit of a template request.
A template of the gallery weighs about 20 KB per language.
content:
application/json:
schema:
$ref: '../components/schemas/common.yaml#/ErrorResponse'
example:
error: 'Request body too large: a template request is limited to 1048576 bytes'
'401':
description: Unauthorized - invalid or missing authentication token
content:
Expand Down
Loading
Loading