-
-
Notifications
You must be signed in to change notification settings - Fork 614
feat(api): format webhook email payload #955
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
2af3c8c
docs: design webhook payload formatting
AchoArnold ede8a3d
docs: plan webhook payload formatting
AchoArnold 1a7dca9
docs: record API baseline constraints
AchoArnold e330244
feat(api): format webhook email payload
AchoArnold 6d1e18a
feat(api): render rich email dictionary values
AchoArnold f58a74e
feat(api): highlight webhook email payload
AchoArnold 19b221a
fix(api): restore webhook payload text
AchoArnold df260ed
fix(api): harden webhook payload formatting
AchoArnold File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| package emails | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "encoding/json" | ||
| "html" | ||
| "html/template" | ||
| "strings" | ||
| ) | ||
|
|
||
| const ( | ||
| eventPayloadCodeBlockStyle = "margin:0;padding:12px;border:1px solid #D0D7DE;border-radius:6px;background:#F6F8FA;color:#24292F;font-family:Consolas,Monaco,'Courier New',monospace;font-size:13px;line-height:1.5;white-space:pre-wrap;word-break:break-word;overflow-wrap:anywhere;" | ||
| jsonKeyStyle = "color:#0550AE;font-weight:600;" | ||
| jsonStringStyle = "color:#0A3069;" | ||
| jsonNumberStyle = "color:#953800;" | ||
| jsonLiteralStyle = "color:#8250DF;" | ||
| ) | ||
|
|
||
| func formatEventPayload(payload string) (string, template.HTML) { | ||
| formattedPayload, isJSON := indentEventPayloadJSON(payload) | ||
| content := html.EscapeString(formattedPayload) | ||
| if isJSON { | ||
| content = highlightEventPayloadJSON(formattedPayload) | ||
| } | ||
|
|
||
| // Every payload token is escaped before this trusted wrapper is constructed. | ||
| richPayload := template.HTML(`<pre style="` + eventPayloadCodeBlockStyle + `">` + content + `</pre>`) | ||
|
Check failure on line 27 in api/pkg/emails/event_payload_formatter.go
|
||
| return formattedPayload, richPayload | ||
| } | ||
|
|
||
| func indentEventPayloadJSON(payload string) (string, bool) { | ||
| var formatted bytes.Buffer | ||
| if err := json.Indent(&formatted, []byte(payload), "", " "); err != nil { | ||
| return payload, false | ||
| } | ||
|
|
||
| return formatted.String(), true | ||
| } | ||
|
|
||
| func highlightEventPayloadJSON(payload string) string { | ||
| var highlighted strings.Builder | ||
| highlighted.Grow(len(payload)) | ||
|
|
||
| for index := 0; index < len(payload); { | ||
| switch { | ||
| case payload[index] == '"': | ||
| end := eventPayloadJSONStringEnd(payload, index) | ||
| style := jsonStringStyle | ||
| if eventPayloadNextNonSpace(payload, end) == ':' { | ||
| style = jsonKeyStyle | ||
| } | ||
| writeEventPayloadToken(&highlighted, style, payload[index:end]) | ||
| index = end | ||
| case payload[index] == '-' || isEventPayloadDigit(payload[index]): | ||
| end := index + 1 | ||
| // json.Indent already validated this as JSON, so this continuation set only sees JSON number bytes. | ||
| for end < len(payload) && isEventPayloadNumberCharacter(payload[end]) { | ||
| end++ | ||
| } | ||
| writeEventPayloadToken(&highlighted, jsonNumberStyle, payload[index:end]) | ||
| index = end | ||
| case strings.HasPrefix(payload[index:], "true"): | ||
| writeEventPayloadToken(&highlighted, jsonLiteralStyle, "true") | ||
| index += len("true") | ||
| case strings.HasPrefix(payload[index:], "false"): | ||
| writeEventPayloadToken(&highlighted, jsonLiteralStyle, "false") | ||
| index += len("false") | ||
| case strings.HasPrefix(payload[index:], "null"): | ||
| writeEventPayloadToken(&highlighted, jsonLiteralStyle, "null") | ||
| index += len("null") | ||
| default: | ||
| highlighted.WriteString(html.EscapeString(payload[index : index+1])) | ||
| index++ | ||
| } | ||
| } | ||
|
|
||
| return highlighted.String() | ||
| } | ||
|
|
||
| func eventPayloadJSONStringEnd(payload string, start int) int { | ||
| escaped := false | ||
| for index := start + 1; index < len(payload); index++ { | ||
| switch { | ||
| case escaped: | ||
| escaped = false | ||
| case payload[index] == '\\': | ||
| escaped = true | ||
| case payload[index] == '"': | ||
| return index + 1 | ||
| } | ||
| } | ||
|
|
||
| return len(payload) | ||
| } | ||
|
|
||
| func eventPayloadNextNonSpace(payload string, start int) byte { | ||
| for index := start; index < len(payload); index++ { | ||
| switch payload[index] { | ||
| case ' ', '\n', '\r', '\t': | ||
| continue | ||
| default: | ||
| return payload[index] | ||
| } | ||
| } | ||
|
|
||
| return 0 | ||
| } | ||
|
|
||
| func isEventPayloadDigit(value byte) bool { | ||
| return value >= '0' && value <= '9' | ||
| } | ||
|
|
||
| func isEventPayloadNumberCharacter(value byte) bool { | ||
| return isEventPayloadDigit(value) || | ||
| value == '-' || | ||
| value == '+' || | ||
| value == '.' || | ||
| value == 'e' || | ||
| value == 'E' | ||
| } | ||
|
|
||
| func writeEventPayloadToken(builder *strings.Builder, style string, token string) { | ||
| builder.WriteString(`<span style="`) | ||
| builder.WriteString(style) | ||
| builder.WriteString(`">`) | ||
| builder.WriteString(html.EscapeString(token)) | ||
| builder.WriteString(`</span>`) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| package emails | ||
|
|
||
| import ( | ||
| "strings" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| ) | ||
|
|
||
| func TestFormatEventPayloadIndentsAndHighlightsJSON(t *testing.T) { | ||
| payload := `{"message":"hello","count":2,"ratio":1.5,"enabled":true,"disabled":false,"missing":null,"nested":{"value":"ok"}}` | ||
|
|
||
| plain, rich := formatEventPayload(payload) | ||
| html := string(rich) | ||
|
|
||
| assert.Equal(t, `{ | ||
| "message": "hello", | ||
| "count": 2, | ||
| "ratio": 1.5, | ||
| "enabled": true, | ||
| "disabled": false, | ||
| "missing": null, | ||
| "nested": { | ||
| "value": "ok" | ||
| } | ||
| }`, plain) | ||
| assert.Contains(t, html, `<span style="color:#0550AE;font-weight:600;">"message"</span>`) | ||
| assert.Contains(t, html, `<span style="color:#0A3069;">"hello"</span>`) | ||
| assert.Contains(t, html, `<span style="color:#953800;">2</span>`) | ||
| assert.Contains(t, html, `<span style="color:#953800;">1.5</span>`) | ||
| assert.Contains(t, html, `<span style="color:#8250DF;">true</span>`) | ||
| assert.Contains(t, html, `<span style="color:#8250DF;">false</span>`) | ||
| assert.Contains(t, html, `<span style="color:#8250DF;">null</span>`) | ||
| assert.Contains(t, html, `white-space:pre-wrap`) | ||
| } | ||
|
|
||
| func TestFormatEventPayloadEscapesPayloadHTML(t *testing.T) { | ||
| plain, rich := formatEventPayload(`{"message":"<script>alert(\"x\")</script>&"}`) | ||
| html := string(rich) | ||
|
|
||
| assert.Contains(t, plain, `<script>alert`) | ||
| assert.NotContains(t, html, `<script>`) | ||
| assert.Contains(t, html, `<script>`) | ||
| assert.Contains(t, html, `&`) | ||
| } | ||
|
|
||
| func TestFormatEventPayloadPreservesInvalidJSONWithoutHighlighting(t *testing.T) { | ||
| payload := "line one\n <strong>line two</strong>" | ||
|
|
||
| plain, rich := formatEventPayload(payload) | ||
| html := string(rich) | ||
|
|
||
| assert.Equal(t, payload, plain) | ||
| assert.Contains(t, html, "line one\n <strong>line two</strong>") | ||
| assert.NotContains(t, html, `<strong>`) | ||
| assert.NotContains(t, html, `<span style="color:`) | ||
| assert.Equal(t, 1, strings.Count(html, `<pre style=`)) | ||
| } | ||
|
|
||
| func TestFormatEventPayloadHandlesTopLevelPayloadShapes(t *testing.T) { | ||
| tests := []struct { | ||
| name string | ||
| payload string | ||
| wantPlain string | ||
| wantHTMLContains []string | ||
| wantHTMLNotContains []string | ||
| }{ | ||
| { | ||
| name: "empty payload falls back to unhighlighted block", | ||
| payload: "", | ||
| wantPlain: "", | ||
| wantHTMLContains: []string{`<pre style="`, `</pre>`}, | ||
| wantHTMLNotContains: []string{`<span style="color:`}, | ||
| }, | ||
| { | ||
| name: "top-level number stays valid JSON", | ||
| payload: "42", | ||
| wantPlain: "42", | ||
| wantHTMLContains: []string{`<span style="color:#953800;">42</span>`}, | ||
| wantHTMLNotContains: []string{`color:#0550AE`}, | ||
| }, | ||
| { | ||
| name: "json array stays readable and escaped", | ||
| payload: `[{"message":"<b>safe</b>"},true,null,3]`, | ||
| wantPlain: "[\n {\n \"message\": \"<b>safe</b>\"\n },\n true,\n null,\n 3\n]", | ||
| wantHTMLContains: []string{ | ||
| "[\n {", | ||
| `"message"`, | ||
| `<b>safe</b>`, | ||
| `<span style="color:#953800;">3</span>`, | ||
| }, | ||
| wantHTMLNotContains: []string{`<b>safe</b>`}, | ||
| }, | ||
| } | ||
|
|
||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| plain, rich := formatEventPayload(tt.payload) | ||
| html := string(rich) | ||
|
|
||
| assert.Equal(t, tt.wantPlain, plain) | ||
| assert.Equal(t, 1, strings.Count(html, `<pre style=`)) | ||
|
|
||
| for _, want := range tt.wantHTMLContains { | ||
| assert.Contains(t, html, want) | ||
| } | ||
|
|
||
| for _, unwanted := range tt.wantHTMLNotContains { | ||
| assert.NotContains(t, html, unwanted) | ||
| } | ||
| }) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
replaceWebhookSendFailedEventPayloadPlaceholderreturnstextunchanged when the placeholder is not found. At that pointtextis the hermes-generated plain-text output, which still contains__HTTPSMS_WEBHOOK_SEND_FAILED_EVENT_PAYLOAD__as the literalValueof the dictionary entry. If hermes or the underlying html2text converter ever transforms or trims this token (unlikely today but possible on a dependency bump), users would receive a webhook failure email whose "Event Payload" line reads__HTTPSMS_WEBHOOK_SEND_FAILED_EVENT_PAYLOAD__instead of the actual payload. An alternative would be to setValuetoformattedPayloaddirectly and accept that html2text may collapse its whitespace, or to emit an observable signal (log/metric) when!found.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed in 9fa5b76. If Hermes no longer preserves the sentinel, plain-text generation now retries with the actual formatted payload instead of exposing the internal token.