479 lines
18 KiB
Go
479 lines
18 KiB
Go
package mailtemplate
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
"testing/fstest"
|
|
|
|
"lincodex/backend/internal/domain"
|
|
)
|
|
|
|
// Run "go test ./internal/usecase/notification/mailtemplate -update" from
|
|
// backend/ after an intended copy change, then review the golden diff.
|
|
var updateGolden = flag.Bool("update", false, "rewrite the golden renderings in testdata")
|
|
|
|
const (
|
|
testOrigin = "https://lincodex.example"
|
|
// syntheticToken matches the contract token pattern and is fixed so that
|
|
// golden files stay stable. It is not a real credential.
|
|
syntheticToken = "SyntheticToken_0123456789-abcdefghijklmnopqrstuv"
|
|
// hostileSubject tries markup, quotes, and a header line injection.
|
|
hostileSubject = "Приглашение <script>alert(\"x\")</script> & 'кавычки'\r\nX-Injected: yes"
|
|
// hostileBody adds a bidi override, a bell, a stray CR, extra blank
|
|
// lines, an ampersand, markup, and non-ASCII text.
|
|
hostileBody = "Компания \"Тест & Ко\" <b>пригласила</b> вас.\r\nВторая строка\u202eреверс\u0007\r\n\n\n\nВторой абзац: ёжик 🚀 <img src=x onerror=alert(1)>"
|
|
)
|
|
|
|
func newTestRenderer(t *testing.T) *Renderer {
|
|
t.Helper()
|
|
renderer, err := NewRenderer(testOrigin)
|
|
if err != nil {
|
|
t.Fatalf("NewRenderer() error = %v", err)
|
|
}
|
|
return renderer
|
|
}
|
|
|
|
func testToken(t *testing.T) domain.SecretToken {
|
|
t.Helper()
|
|
token, err := domain.ParseSecretToken(syntheticToken)
|
|
if err != nil {
|
|
t.Fatalf("ParseSecretToken() error = %v", err)
|
|
}
|
|
return token
|
|
}
|
|
|
|
func hostileNotification() NotificationData {
|
|
return NotificationData{Subject: hostileSubject, Body: hostileBody, LinkPath: "/candidate/invitations"}
|
|
}
|
|
|
|
// renderAll renders one message of every kind with the fixed test data.
|
|
func renderAll(t *testing.T, renderer *Renderer) map[Kind]RenderedMail {
|
|
t.Helper()
|
|
token := testToken(t)
|
|
verification, err := renderer.RenderVerification(VerificationData{Token: token, TokenLifetime: 24})
|
|
if err != nil {
|
|
t.Fatalf("RenderVerification() error = %v", err)
|
|
}
|
|
reset, err := renderer.RenderPasswordReset(PasswordResetData{Token: token, TokenLifetime: 1})
|
|
if err != nil {
|
|
t.Fatalf("RenderPasswordReset() error = %v", err)
|
|
}
|
|
notification, err := renderer.RenderNotification(hostileNotification())
|
|
if err != nil {
|
|
t.Fatalf("RenderNotification() error = %v", err)
|
|
}
|
|
return map[Kind]RenderedMail{KindVerification: verification, KindPasswordReset: reset, KindNotification: notification}
|
|
}
|
|
|
|
func TestRenderingsMatchGoldenFiles(t *testing.T) {
|
|
for kind, mail := range renderAll(t, newTestRenderer(t)) {
|
|
t.Run(string(kind), func(t *testing.T) {
|
|
base := filepath.Join("testdata", string(mail.TemplateVersion()))
|
|
assertGolden(t, base+".txt.golden", "Subject: "+mail.Subject()+"\n\n"+mail.Text())
|
|
assertGolden(t, base+".html.golden", mail.HTML())
|
|
})
|
|
}
|
|
}
|
|
|
|
func assertGolden(t *testing.T, path, got string) {
|
|
t.Helper()
|
|
if *updateGolden {
|
|
if err := os.WriteFile(path, []byte(got), 0o600); err != nil {
|
|
t.Fatalf("write %s: %v", path, err)
|
|
}
|
|
return
|
|
}
|
|
want, err := os.ReadFile(path)
|
|
if err != nil {
|
|
t.Fatalf("read %s: %v (run with -update to create it)", path, err)
|
|
}
|
|
if got != string(want) {
|
|
t.Fatalf("%s differs from the rendering; review the copy change and run with -update\n--- got ---\n%s", path, got)
|
|
}
|
|
}
|
|
|
|
func TestRenderingCarriesKindAndVersion(t *testing.T) {
|
|
want := map[Kind]TemplateVersion{
|
|
KindVerification: "verification.v1",
|
|
KindPasswordReset: "password_reset.v1",
|
|
KindNotification: "notification.v1",
|
|
}
|
|
for kind, mail := range renderAll(t, newTestRenderer(t)) {
|
|
if mail.Kind() != kind || mail.TemplateVersion() != want[kind] {
|
|
t.Fatalf("rendering for %s has kind %s and version %s", kind, mail.Kind(), mail.TemplateVersion())
|
|
}
|
|
if !strings.Contains(mail.HTML(), `<html lang="ru">`) {
|
|
t.Fatalf("%s HTML does not declare lang=ru", kind)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestTokenLinksUseOriginPathAndFragment(t *testing.T) {
|
|
renderer := newTestRenderer(t)
|
|
mails := renderAll(t, renderer)
|
|
for kind, path := range map[Kind]string{KindVerification: "/verify-email", KindPasswordReset: "/reset-password"} {
|
|
mail := mails[kind]
|
|
want := testOrigin + path + "#token=" + syntheticToken
|
|
link, err := url.Parse(want)
|
|
if err != nil {
|
|
t.Fatalf("url.Parse() error = %v", err)
|
|
}
|
|
if link.RawQuery != "" || link.Fragment != "token="+syntheticToken {
|
|
t.Fatalf("%s link must carry the token only in the fragment", kind)
|
|
}
|
|
if !strings.Contains(mail.Text(), "\n"+want+"\n") {
|
|
t.Fatalf("%s text part does not contain the link on its own line", kind)
|
|
}
|
|
if strings.Count(mail.HTML(), `href="`+want+`"`) != 2 || !strings.Contains(mail.HTML(), ">"+want+"</a>") {
|
|
t.Fatalf("%s HTML part does not contain the link as a button, a visible link, and text", kind)
|
|
}
|
|
if strings.Contains(mail.Text()+mail.HTML(), "?token=") {
|
|
t.Fatalf("%s puts the token in a query", kind)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestLoopbackOriginKeepsPort(t *testing.T) {
|
|
renderer, err := NewRenderer("http://localhost:5173/")
|
|
if err != nil {
|
|
t.Fatalf("NewRenderer() error = %v", err)
|
|
}
|
|
mail, err := renderer.RenderVerification(VerificationData{Token: testToken(t), TokenLifetime: 24})
|
|
if err != nil {
|
|
t.Fatalf("RenderVerification() error = %v", err)
|
|
}
|
|
if !strings.Contains(mail.Text(), "http://localhost:5173/verify-email#token="+syntheticToken+"\n") {
|
|
t.Fatal("verification link does not use the loopback origin")
|
|
}
|
|
}
|
|
|
|
func TestNotificationEscapesCallerText(t *testing.T) {
|
|
mail, err := newTestRenderer(t).RenderNotification(hostileNotification())
|
|
if err != nil {
|
|
t.Fatalf("RenderNotification() error = %v", err)
|
|
}
|
|
if strings.ContainsAny(mail.Subject(), "\r\n") || !strings.HasSuffix(mail.Subject(), "'кавычки' X-Injected: yes") {
|
|
t.Fatalf("subject is not one sanitized line: %q", mail.Subject())
|
|
}
|
|
html := mail.HTML()
|
|
for _, raw := range []string{"<script>", "<b>", "<img", `"Тест`, "'кавычки'", "& Ко", "\u202e", "\u0007"} {
|
|
if strings.Contains(html, raw) {
|
|
t.Fatalf("HTML part contains unescaped %q", raw)
|
|
}
|
|
}
|
|
for _, escaped := range []string{"<script>", "<b>пригласила</b>", ""Тест & Ко"", "'кавычки'", "Вторая строка", "<br>", "ёжик 🚀"} {
|
|
if !strings.Contains(html, escaped) {
|
|
t.Fatalf("HTML part does not contain %q", escaped)
|
|
}
|
|
}
|
|
text := mail.Text()
|
|
if strings.ContainsAny(text, "\r\u202e\u0007") {
|
|
t.Fatalf("text part contains a control or bidi character: %q", text)
|
|
}
|
|
if !strings.Contains(text, "<b>пригласила</b> вас.\nВторая строкареверс\n\nВторой абзац") {
|
|
t.Fatalf("text part does not keep the plain caller text and paragraphs: %q", text)
|
|
}
|
|
if !strings.Contains(text, "\n"+testOrigin+"/candidate/invitations\n") {
|
|
t.Fatal("text part does not contain the cabinet link")
|
|
}
|
|
}
|
|
|
|
func TestRejectsUnsafeOrigins(t *testing.T) {
|
|
for _, origin := range []string{
|
|
"",
|
|
"lincodex.example",
|
|
"//lincodex.example",
|
|
"http://lincodex.example",
|
|
"ftp://lincodex.example",
|
|
"javascript:alert(1)",
|
|
"https://user:secret@lincodex.example",
|
|
"https://lincodex.example/app",
|
|
"https://lincodex.example?next=x",
|
|
"https://lincodex.example#",
|
|
"https://lincodex.example:0",
|
|
"https://lincodex.example:",
|
|
"https://bad host.example",
|
|
} {
|
|
if _, err := NewRenderer(origin); err == nil {
|
|
t.Fatalf("NewRenderer(%q) accepted an unsafe origin", origin)
|
|
} else if origin != "" && strings.Contains(err.Error(), origin) {
|
|
t.Fatalf("NewRenderer(%q) error echoes the value: %v", origin, err)
|
|
}
|
|
}
|
|
for _, origin := range []string{"https://lincodex.example:8443", "http://127.0.0.1:8080", "http://[::1]:8080", "HTTPS://Lincodex.Example"} {
|
|
if _, err := NewRenderer(origin); err != nil {
|
|
t.Fatalf("NewRenderer(%q) error = %v", origin, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestNotificationRejectsLinksOutsideTheApp(t *testing.T) {
|
|
renderer := newTestRenderer(t)
|
|
for _, linkPath := range []string{
|
|
"",
|
|
"candidate/invitations",
|
|
"//evil.example/candidate",
|
|
"https://evil.example/candidate",
|
|
"javascript:alert(1)",
|
|
"/candidate/../admin",
|
|
"/candidate/./invitations",
|
|
"/candidate/",
|
|
"/",
|
|
"/candidate?next=https://evil.example",
|
|
"/candidate#token=x",
|
|
`/\evil.example`,
|
|
"/candidate/%2e%2e",
|
|
"/candidate invitations",
|
|
"/" + strings.Repeat("a", maxLinkPathLength),
|
|
} {
|
|
data := hostileNotification()
|
|
data.LinkPath = linkPath
|
|
_, err := renderer.RenderNotification(data)
|
|
if !errors.Is(err, ErrInvalidTemplateData) {
|
|
t.Fatalf("RenderNotification(LinkPath %q) error = %v, want ErrInvalidTemplateData", linkPath, err)
|
|
}
|
|
}
|
|
data := hostileNotification()
|
|
data.LinkPath = "/employer/candidates/0190a5e4-7c1b-7d2e-9f00-1a2b3c4d5e6f"
|
|
if _, err := renderer.RenderNotification(data); err != nil {
|
|
t.Fatalf("RenderNotification() rejected a cabinet path: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestRejectsInvalidData(t *testing.T) {
|
|
renderer := newTestRenderer(t)
|
|
token := testToken(t)
|
|
tokenCases := map[string]VerificationData{
|
|
"missing token": {TokenLifetime: 24},
|
|
"zero lifetime": {Token: token},
|
|
"negative": {Token: token, TokenLifetime: -1},
|
|
"lifetime too big": {Token: token, TokenLifetime: maxTokenLifetime + 1},
|
|
}
|
|
for name, data := range tokenCases {
|
|
if _, err := renderer.RenderVerification(data); !errors.Is(err, ErrInvalidTemplateData) {
|
|
t.Fatalf("RenderVerification(%s) error = %v", name, err)
|
|
}
|
|
reset := PasswordResetData(data)
|
|
if _, err := renderer.RenderPasswordReset(reset); !errors.Is(err, ErrInvalidTemplateData) {
|
|
t.Fatalf("RenderPasswordReset(%s) error = %v", name, err)
|
|
}
|
|
}
|
|
|
|
notificationCases := map[string]func(*NotificationData){
|
|
"blank subject": func(data *NotificationData) { data.Subject = " \r\n\t" },
|
|
"long subject": func(data *NotificationData) { data.Subject = strings.Repeat("я", maxNotificationSubjectRunes+1) },
|
|
"invalid UTF-8": func(data *NotificationData) { data.Body = "abc\xff" },
|
|
"only control body": func(data *NotificationData) { data.Body = "\u202e\u0007\r\n \n" },
|
|
"long body": func(data *NotificationData) { data.Body = strings.Repeat("я", maxNotificationBodyRunes+1) },
|
|
"invalid UTF-8 title": func(data *NotificationData) { data.Subject = "\xc3\x28" },
|
|
}
|
|
for name, mutate := range notificationCases {
|
|
data := hostileNotification()
|
|
mutate(&data)
|
|
if _, err := renderer.RenderNotification(data); !errors.Is(err, ErrInvalidTemplateData) {
|
|
t.Fatalf("RenderNotification(%s) error = %v", name, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestLifetimeCopyUsesRussianPlural(t *testing.T) {
|
|
renderer := newTestRenderer(t)
|
|
for hours, want := range map[domain.Hours]string{1: "1 час.", 3: "3 часа.", 11: "11 часов.", 21: "21 час.", 24: "24 часа.", 48: "48 часов.", 168: "168 часов."} {
|
|
mail, err := renderer.RenderVerification(VerificationData{Token: testToken(t), TokenLifetime: hours})
|
|
if err != nil {
|
|
t.Fatalf("RenderVerification(%d) error = %v", hours, err)
|
|
}
|
|
if !strings.Contains(mail.Text(), "Ссылка действует "+want) {
|
|
t.Fatalf("lifetime %d is not phrased as %q", hours, want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestContentHashPinsTheBody(t *testing.T) {
|
|
renderer := newTestRenderer(t)
|
|
first := renderAll(t, renderer)
|
|
second := renderAll(t, renderer)
|
|
seen := make(map[ContentHash]Kind)
|
|
for kind, mail := range first {
|
|
if mail.ContentHash() != second[kind].ContentHash() {
|
|
t.Fatalf("%s content hash differs for the same version and data", kind)
|
|
}
|
|
if mail.ContentHash() != ContentHash(domain.MailContentHash(string(mail.TemplateVersion()), mail.Subject(), mail.Text(), mail.HTML())) {
|
|
t.Fatalf("%s content hash does not cover the version, subject, and parts", kind)
|
|
}
|
|
// A delivery stores the rendering as domain.MailContent; both forms
|
|
// must name the same kind, version, parts, and hash.
|
|
content, err := mail.Content()
|
|
if err != nil {
|
|
t.Fatalf("%s Content() error = %v", kind, err)
|
|
}
|
|
if string(content.Kind()) != string(kind) || content.TemplateVersion() != string(mail.TemplateVersion()) ||
|
|
content.Subject() != mail.Subject() || content.Text() != mail.Text() || content.HTML() != mail.HTML() ||
|
|
ContentHash(content.Hash()) != mail.ContentHash() {
|
|
t.Fatalf("%s Content() does not carry the rendering", kind)
|
|
}
|
|
seen[mail.ContentHash()] = kind
|
|
}
|
|
if len(seen) != len(first) {
|
|
t.Fatal("different kinds share a content hash")
|
|
}
|
|
|
|
otherToken, err := domain.NewSecretToken()
|
|
if err != nil {
|
|
t.Fatalf("NewSecretToken() error = %v", err)
|
|
}
|
|
changed := []struct {
|
|
name string
|
|
render func() (RenderedMail, error)
|
|
base Kind
|
|
}{
|
|
{"token", func() (RenderedMail, error) {
|
|
return renderer.RenderVerification(VerificationData{Token: otherToken, TokenLifetime: 24})
|
|
}, KindVerification},
|
|
{"lifetime", func() (RenderedMail, error) {
|
|
return renderer.RenderVerification(VerificationData{Token: testToken(t), TokenLifetime: 25})
|
|
}, KindVerification},
|
|
{"body", func() (RenderedMail, error) {
|
|
data := hostileNotification()
|
|
data.Body += "!"
|
|
return renderer.RenderNotification(data)
|
|
}, KindNotification},
|
|
{"link", func() (RenderedMail, error) {
|
|
data := hostileNotification()
|
|
data.LinkPath = "/candidate/results"
|
|
return renderer.RenderNotification(data)
|
|
}, KindNotification},
|
|
}
|
|
for _, change := range changed {
|
|
mail, err := change.render()
|
|
if err != nil {
|
|
t.Fatalf("render with changed %s: %v", change.name, err)
|
|
}
|
|
if mail.ContentHash() == first[change.base].ContentHash() {
|
|
t.Fatalf("content hash did not change with the %s", change.name)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestRenderingNeverReachesLogs plays the render harness: it prints every
|
|
// input, rendering, and error through fmt and slog, then checks that no
|
|
// token, link, subject, or body text appears.
|
|
func TestRenderingNeverReachesLogs(t *testing.T) {
|
|
renderer := newTestRenderer(t)
|
|
token := testToken(t)
|
|
mails := renderAll(t, renderer)
|
|
|
|
var output bytes.Buffer
|
|
loggers := []*slog.Logger{
|
|
slog.New(slog.NewTextHandler(&output, nil)),
|
|
slog.New(slog.NewJSONHandler(&output, nil)),
|
|
}
|
|
verification := VerificationData{Token: token, TokenLifetime: 24}
|
|
notification := hostileNotification()
|
|
// RenderedMail hides its content even in an unexported field.
|
|
// NotificationData redacts itself only where fmt can call its methods.
|
|
type envelope struct {
|
|
mail RenderedMail
|
|
Notification NotificationData
|
|
}
|
|
for _, mail := range mails {
|
|
for _, logger := range loggers {
|
|
logger.Info("rendered", "mail", mail, "verification", verification, "notification", notification)
|
|
}
|
|
nested := envelope{mail: mail, Notification: notification}
|
|
fmt.Fprintf(&output, "%v %+v %#v %s %v %+v %v %+v\n", mail, mail, mail, mail, verification, verification, nested, &nested)
|
|
}
|
|
|
|
badLink := hostileNotification()
|
|
badLink.LinkPath = "javascript:alert('" + syntheticToken + "')"
|
|
_, linkErr := renderer.RenderNotification(badLink)
|
|
badSubject := hostileNotification()
|
|
badSubject.Subject = strings.Repeat(syntheticToken, 4)
|
|
_, subjectErr := renderer.RenderNotification(badSubject)
|
|
_, originErr := NewRenderer("https://user:" + syntheticToken + "@lincodex.example")
|
|
for _, err := range []error{linkErr, subjectErr, originErr} {
|
|
if err == nil {
|
|
t.Fatal("invalid input was rendered")
|
|
}
|
|
fmt.Fprintln(&output, err)
|
|
for _, logger := range loggers {
|
|
logger.Error("render failed", "error", err)
|
|
}
|
|
}
|
|
|
|
logs := output.String()
|
|
for kind, mail := range mails {
|
|
if !strings.Contains(logs, mail.ContentHash().String()) || !strings.Contains(logs, string(kind)) {
|
|
t.Fatalf("logs do not identify the %s rendering by kind and content hash", kind)
|
|
}
|
|
assertAbsent(t, logs, mail.Subject(), mail.Text(), mail.HTML())
|
|
}
|
|
assertAbsent(t, logs, syntheticToken, "token=", "Подтвердите", "Сброс пароля", "Приглашение", "пригласила", "Компания", "<html")
|
|
}
|
|
|
|
func assertAbsent(t *testing.T, output string, secrets ...string) {
|
|
t.Helper()
|
|
for _, secret := range secrets {
|
|
if strings.Contains(output, secret) {
|
|
t.Fatalf("render harness output exposes %q:\n%s", secret, output)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestToOutgoingMailIsValidForThePort(t *testing.T) {
|
|
recipient, err := domain.NewEmailAddress("candidate@lincodex.example")
|
|
if err != nil {
|
|
t.Fatalf("NewEmailAddress() error = %v", err)
|
|
}
|
|
for kind, mail := range renderAll(t, newTestRenderer(t)) {
|
|
outgoing := mail.ToOutgoingMail(recipient, "email_verification/0190a5e4-7c1b-7d2e-9f00-1a2b3c4d5e6f")
|
|
if err := outgoing.Validate(); err != nil {
|
|
t.Fatalf("%s rendering is not a valid OutgoingMail: %v", kind, err)
|
|
}
|
|
if outgoing.Subject != mail.Subject() || outgoing.TextBody != mail.Text() || outgoing.HTMLBody != mail.HTML() {
|
|
t.Fatalf("%s OutgoingMail does not carry the rendering unchanged", kind)
|
|
}
|
|
}
|
|
if !(RenderedMail{}).IsZero() || (RenderedMail{}).Text() != "" {
|
|
t.Fatal("zero RenderedMail is not empty")
|
|
}
|
|
}
|
|
|
|
func TestTemplateSetIsComplete(t *testing.T) {
|
|
part := func(body string) *fstest.MapFile { return &fstest.MapFile{Data: []byte(body)} }
|
|
complete := func() fstest.MapFS {
|
|
return fstest.MapFS{
|
|
"templates/verification.v1.subject.tmpl": part("s"),
|
|
"templates/verification.v1.txt.tmpl": part("t"),
|
|
"templates/verification.v1.html.tmpl": part("<p>h</p>"),
|
|
}
|
|
}
|
|
if _, err := parseTemplates(complete()); err != nil {
|
|
t.Fatalf("parseTemplates(complete) error = %v", err)
|
|
}
|
|
cases := map[string]func(fstest.MapFS){
|
|
"missing part": func(files fstest.MapFS) { delete(files, "templates/verification.v1.html.tmpl") },
|
|
"stray file": func(files fstest.MapFS) { files["templates/verification.html"] = part("x") },
|
|
"bad version": func(files fstest.MapFS) { files["templates/verification.v0.txt.tmpl"] = part("x") },
|
|
"bad text": func(files fstest.MapFS) { files["templates/verification.v1.txt.tmpl"] = part("{{.Link") },
|
|
"bad html": func(files fstest.MapFS) {
|
|
files["templates/verification.v1.html.tmpl"] = part(`<a href="{{.Link}}`)
|
|
},
|
|
}
|
|
for name, mutate := range cases {
|
|
files := complete()
|
|
mutate(files)
|
|
if _, err := parseTemplates(files); err == nil {
|
|
t.Fatalf("parseTemplates(%s) accepted a broken template set", name)
|
|
}
|
|
}
|
|
}
|