From 3a725469c6318e6bb9d64134fe1e5d7d144825ef Mon Sep 17 00:00:00 2001 From: Jakub Zych Date: Sat, 14 Nov 2026 15:20:29 +0100 Subject: [PATCH] fix(postcard,cabana): unsafe site names never stop a send and are refused at save - postcard.UnsafeText: a text a layout prints is unsafe when, escaped, it fails the rendered-HTML checks or holds a script or data URL at a scheme boundary ("Big Data: Summit" is safe) - siteNameFrom/layoutSiteName: an unsafe Branding name falls back to the mail.from display name, an unsafe one of those gives no name; one rate-limited warning per source (site_name:branding, site_name:mail.from), never the value; file version, override, fallback and editor alike - the Branding preview of an unsafe draft name renders without it - MailBrandSetting.BeforeValidate: 422 on site_name with backend::lang.mail.brand.site_name_unsafe (en/pl) - settings Put localizes a BeforeValidate refusal's phrase keys, as a controller save does - TestMailSafetySmoke/unsafe_site_name, TestMailBrandSiteName/unsafe_name_refused --- docs/services/mail.md | 2 + modules/cabana/README.md | 2 +- modules/cabana/mail_admin.go | 9 ++- .../cabana/mail_brand_layout_postgres_test.go | 25 +++++++ modules/cabana/settings.go | 4 +- modules/phrasebook/backend/lang/en/lang.yaml | 1 + modules/phrasebook/backend/lang/pl/lang.yaml | 1 + modules/postcard/README.md | 5 +- modules/postcard/editor.go | 4 +- modules/postcard/mailer.go | 55 ++++++++++++--- modules/postcard/safety.go | 20 ++++++ modules/postcard/safety_smoke_test.go | 68 +++++++++++++++++++ 12 files changed, 180 insertions(+), 16 deletions(-) diff --git a/docs/services/mail.md b/docs/services/mail.md index 666ab50b..7ac3c4ef 100644 --- a/docs/services/mail.md +++ b/docs/services/mail.md @@ -85,6 +85,8 @@ The settings also hold a logo. A layout shows it where it uses `{{ .logoUrl }}`: The settings also hold a site name, given to layouts as `{{ .siteName }}`. The built-in layouts show it in the header (as the logo's alternative text when there is a logo) and in the footer. Left empty, the display name of `mail.from` is used (`Acme` for `Acme `), so mail from an application that never saved Branding still carries a name. +A site name mail could not show safely is refused when the settings are saved: one holding a `javascript:`, `vbscript:` or `data:` address, or text that would read as markup, such as `onclick=`. Ordinary text with a colon, such as `Big Data: Summit`, is accepted. A name stored before this check, or a `mail.from` display name of that kind, is left out of mail at send time (the next name in line is used, or none), with a warning in the log; the message is still sent. + A mail client needs an absolute address, so the logo's URL is built at send time from the configuration: `storage.uploads.public_url` when it is set, otherwise `app.url` with `storage.uploads.public_path_prefix`; see [Absolute URLs for mail](storage.md#absolute-urls-for-mail). Set one of them, or the logo is left out and a warning is logged. ## Sample values for previews diff --git a/modules/cabana/README.md b/modules/cabana/README.md index 04a3a2d7..2d1f8cef 100644 --- a/modules/cabana/README.md +++ b/modules/cabana/README.md @@ -59,7 +59,7 @@ Use cases: - Form fields on another plugin's controller: a `pact.AdminActionExtension` with `Form` set to a `pact.AdminFormExtension` places fields and tabs in any admin controller's form by its ID. Its fields document is the `fields.yaml` format plus `before:`/`after:` anchors, `zone:` (only the tab zone for now) and a `tabs:` list, compiled at boot with every `fields.yaml` check; extensions apply in plugin activation order and the form is sent in the compiled order, so the SPA adds no ordering. `Hide` removes owner fields, `Permissions` and `Visible` decide per request who sees the fields (schema, show and save alike), widget fields run the extension's `Actions` and partial fields render from its `Dir` through `PartialData`. Extension values leave the save body before any owner path reads them; `Save` runs in the record's save transaction after the owner row is written (`pact.AdminFormErrors` answers 422, its notices join `meta.notices`) and `Load` serves the values on show. A form no extension lays out compiles unchanged. Unknown anchors, duplicate names, anchor cycles, anchors outside `Requires()`, other zones, `fileupload` fields and clashing widget action or partial names stop the boot naming the plugin, the controller and the name. - Plugins screen: Settings → System → Plugins opens the admin SPA route `/system/plugins` (the settings entry carries `path` instead of a controller) for administrators holding `cabana.PermissionViewPlugins` (`backend.view_plugins`, granted to no role in code; superusers always pass). GET `/plugins` lists the plugins the application was built with from the `party.Installed` metadata `summer build` bakes (name, description, version, source, module and package), or only the IDs of `party.Activated` for an application built before that metadata existed, with the framework version and the state of the plugin registry (`plugins.registry_url`, read through `kiosk.RegistryURL`). With the registry configured, cabana (never the SPA) looks up each versioned plugin's releases through `kiosk.Client` and marks an update when `kiosk.NewestCompatible` finds a release newer than the installed version by `kiosk.Newer` (a `git describe` string or a pseudo-version compares by the tag it builds on), with the `summer plugin:update ` command; GET `/plugins/marketplace` searches the registry and adds installed and compatibility markers (compatible when `summer plugin:install` can install some release with the built framework, looking up the releases of a plugin whose newest one needs a newer framework; always compatible when the built framework version is not a release) and the `summer plugin:install ` command. Registry calls have a 4 second timeout, at most four run at once, and answers are cached in process (searches 5 minutes, at most 256 distinct searches with expired and then the oldest dropped first, releases 15 minutes, failures 1 minute); a failing registry gives `status` unavailable and never a non-200 answer. - Administrators screen: when some plugin registers admin controllers, `cabana.Activate` also compiles the admin's own screens, an internal plugin with ID `summercms.cabana`. Settings → System → Administrators (controller `cabana.AdministratorsControllerID`, permission `cabana.PermissionManageUsers`) lists backend administrators with their role and last sign-in, opens a preview of each, where record actions (the admin's own and contributed ones) are offered, and creates and edits administrators: login, email, names, a password (hashed at `admin.password.bcrypt_cost`, at least 4 characters and at most 72 bytes), the role and per-administrator permission overrides. The server enforces the privilege rules in the save transaction: only a superuser sees superusers or sends the superuser switch, an administrator can neither grant permissions or roles above their own grants nor change an administrator who holds more than they do, their own role, superuser flag, permissions and password are not changed here, and the last active superuser cannot be demoted. A password set for another administrator ends their sessions (personal API tokens stay valid, as with `admin:reset-password`). Administrators are activated, deactivated and restored by record and bulk actions and deleted softly through `deleted_at` (never hard-deleted); the list shows deleted and deactivated rows with their row states and filters deleted ones, and the preview shows a status hint. Deactivating or deleting an administrator ends their sessions and stops their personal API tokens; the last active superuser cannot be demoted, deactivated or deleted on any of these paths (a transaction-scoped advisory lock serializes the check). The permission codes `cabana.PermissionManageUsers` and `cabana.PermissionManageRoles` are registered with no role grant, so after an upgrade only superusers see the screens until an administrator grants them. An application without admin controllers still activates no admin. -- Mail screens (Settings → Mail): when the application publishes postcard's Mailer (`postcard.EditorFrom` succeeds; `party.Activate` runs `postcard.Activate`), the internal plugin also registers the mail screens over postcard's tables, the permission codes `cabana.PermissionManageMailTemplates` (`system.manage_mail_templates`) and `cabana.PermissionManageMailLayouts` (`system.manage_mail_layouts`), both granted to no role in code, and their Settings entries in category `backend::lang.settings.category_mail`. Mail templates (controller `cabana.MailTemplatesControllerID`, model `cabana.MailTemplate`) lists one row per template of this process's catalog (rows of uninstalled plugins are hidden; the row is the template's own, or the lowest locale variant when only variants ship) with code, subject, description, customized locales (`cabana.MailTemplate.CustomizedLocales`: Default and the locale codes of the customized versions, at most three then +N) and layout, and edits the subject, the Markdown body and the layout (a `relation` over `cabana.MailLayout` rows: every database-only layout and the catalog's file layouts). There is no create and no delete. A save marks the row customized, stamps `base_hash` with the file's current hash and `customized_at`, and validates the result through `postcard.Editor.Validate` inside the save's transaction; a `postcard.DraftError` is a 422 on its field with `backend::lang.mail.invalid_` (`:message`, `:name`). The index rows are written by `postcard.SyncIndex` and `postcard.EnsureLocaleRows` through `lagoon.OnDatabase` at activation; a failed sync is logged and retried on the first mail list request of the process, and a list request syncs again when the mail locales changed. The mail locales are the locales the translator's catalog holds plus, when a `cabana.TranslationWriter` is published, its enabled locales; the default locale is the writer's default locale, else the translator's. A template is one record per locale version: its own row (Default), a row per locale variant file (`welcome-en`) and a row per other mail locale that ships no file (`welcome-de`, created by `postcard.EnsureLocaleRows`, showing and sending the default version until it is customized). The update form's locale switcher lists them (`meta.localeVariants`); the record title is the template's base code, and the show response first ensures the template's missing locale rows, so a newly enabled locale can be opened without a restart. A save of a locale without a file stamps `base_hash` with the base file's hash; until it is customized, its form shows the base template's current version (its customization when there is one), and reset returns it to the base file. Mail layouts (`cabana.MailLayoutsControllerID`, model `cabana.MailLayout`) lists postcard's default layout first, then the file layouts and the custom (database-only, `source` NULL, shown as Custom) layouts by name; it creates custom layouts (code `^[a-z0-9-]+$`, free, create-only) and deletes them, refusing one that template rows still reference with a `cabana.ForbiddenError` whose message names the layout and the count (CLDR plural). Mail partials (`cabana.MailPartialsControllerID`, model `cabana.MailPartial`) edits the partials' HTML and text sections. Both need `cabana.PermissionManageMailLayouts`; saves are stamped and validated as templates are. On all three, the record action `reset` (danger, offered on a customized file-backed row) calls `postcard.ResetOverride` in the action's transaction; rows from files are never deleted. The list row states are `customized` (an override) and `outdated` (an override whose `base_hash` differs from the file's `file_hash`), the lists have a status filter (customized, not customized, outdated); on the templates list both apply to the whole template, any of its locale versions. The forms carry the `info` and `file_version` partials: the file (the base template's for a locale without a file), the status, on a template with locale versions the Default line or the line of a locale without a file (`backend::lang.mail.info_locale_default`, `info_locale_fallback`), the sample variables or the partial's call, the drift callout, and a 3-line-context LCS line diff of the serialized override (`postcard.FormatTemplate`, `FormatLayout`, `FormatPartial`) against the file, skipped above 2000 lines per side. The mail controllers declare `recordActions` without a preview block: the admin offers them in the update form's footer, a boot rule only these internal controllers are exempt from. The layout form's CSS tab has the `disable_auto_inline_css` switch (`cabana.MailLayout.DisableAutoInlineCSS`, off for a new custom layout): on, postcard keeps the layout's CSS in its style block instead of also copying it onto the elements; the preview and the save validation render with the switch's value. Layout and partial content fields use the built-in `codeeditor` type (`language: html|css|text`, optional `mailImages`); Branding is the settings form `mail_brand` on `cabana.MailBrandSetting` (postcard's brand row, a `mailimage` logo, the `site_name` text field shown by the built-in layouts' header and footer (trimmed, at most 255 characters, empty falls back to the display name of `mail.from`) and 13 `colorpicker` colours; the first save switches mail from `mail.brandCss` to the compiled colours). Mail images is the singleton controller `cabana.MailImagesControllerID` (`cabana.MailImageLibrary`) with a public attachMany `images` fileupload; GET/POST `/mail/images` and GET `/mail/images/{id}` return absolute public URLs (`attach.AbsolutePublicURL`) and refuse with `mail.images.no_public_url` when neither `storage.uploads.public_url` nor `app.url` is set. Listing answers either mail permission; upload and the singleton form need `system.manage_mail_layouts`. POST `/mail/preview` renders an unsaved draft (`cabana.AdminMailPreviewRequest`: `mode`, `id`, `values`) through `postcard.Editor.Preview` and answers `cabana.AdminMailPreviewResult` (subject, html, text); mode `template` needs `system.manage_mail_templates`, modes `layout`, `partial` and `branding` need `system.manage_mail_layouts`. POST `/mail/test-send` (interactive sessions only) sends a template, layout or partial draft to the signed-in administrator's own email (`cabana.AdminMailTestSendResult`), refuses recipient keys in the body, and is limited to five sends per administrator per ten minutes through a published `cooler.Attempter` when `serve` has one, otherwise an in-process fixed window (429 with `Retry-After`). Forms carry `mailpreview` fields (`mode` matching the screen). +- Mail screens (Settings → Mail): when the application publishes postcard's Mailer (`postcard.EditorFrom` succeeds; `party.Activate` runs `postcard.Activate`), the internal plugin also registers the mail screens over postcard's tables, the permission codes `cabana.PermissionManageMailTemplates` (`system.manage_mail_templates`) and `cabana.PermissionManageMailLayouts` (`system.manage_mail_layouts`), both granted to no role in code, and their Settings entries in category `backend::lang.settings.category_mail`. Mail templates (controller `cabana.MailTemplatesControllerID`, model `cabana.MailTemplate`) lists one row per template of this process's catalog (rows of uninstalled plugins are hidden; the row is the template's own, or the lowest locale variant when only variants ship) with code, subject, description, customized locales (`cabana.MailTemplate.CustomizedLocales`: Default and the locale codes of the customized versions, at most three then +N) and layout, and edits the subject, the Markdown body and the layout (a `relation` over `cabana.MailLayout` rows: every database-only layout and the catalog's file layouts). There is no create and no delete. A save marks the row customized, stamps `base_hash` with the file's current hash and `customized_at`, and validates the result through `postcard.Editor.Validate` inside the save's transaction; a `postcard.DraftError` is a 422 on its field with `backend::lang.mail.invalid_` (`:message`, `:name`). The index rows are written by `postcard.SyncIndex` and `postcard.EnsureLocaleRows` through `lagoon.OnDatabase` at activation; a failed sync is logged and retried on the first mail list request of the process, and a list request syncs again when the mail locales changed. The mail locales are the locales the translator's catalog holds plus, when a `cabana.TranslationWriter` is published, its enabled locales; the default locale is the writer's default locale, else the translator's. A template is one record per locale version: its own row (Default), a row per locale variant file (`welcome-en`) and a row per other mail locale that ships no file (`welcome-de`, created by `postcard.EnsureLocaleRows`, showing and sending the default version until it is customized). The update form's locale switcher lists them (`meta.localeVariants`); the record title is the template's base code, and the show response first ensures the template's missing locale rows, so a newly enabled locale can be opened without a restart. A save of a locale without a file stamps `base_hash` with the base file's hash; until it is customized, its form shows the base template's current version (its customization when there is one), and reset returns it to the base file. Mail layouts (`cabana.MailLayoutsControllerID`, model `cabana.MailLayout`) lists postcard's default layout first, then the file layouts and the custom (database-only, `source` NULL, shown as Custom) layouts by name; it creates custom layouts (code `^[a-z0-9-]+$`, free, create-only) and deletes them, refusing one that template rows still reference with a `cabana.ForbiddenError` whose message names the layout and the count (CLDR plural). Mail partials (`cabana.MailPartialsControllerID`, model `cabana.MailPartial`) edits the partials' HTML and text sections. Both need `cabana.PermissionManageMailLayouts`; saves are stamped and validated as templates are. On all three, the record action `reset` (danger, offered on a customized file-backed row) calls `postcard.ResetOverride` in the action's transaction; rows from files are never deleted. The list row states are `customized` (an override) and `outdated` (an override whose `base_hash` differs from the file's `file_hash`), the lists have a status filter (customized, not customized, outdated); on the templates list both apply to the whole template, any of its locale versions. The forms carry the `info` and `file_version` partials: the file (the base template's for a locale without a file), the status, on a template with locale versions the Default line or the line of a locale without a file (`backend::lang.mail.info_locale_default`, `info_locale_fallback`), the sample variables or the partial's call, the drift callout, and a 3-line-context LCS line diff of the serialized override (`postcard.FormatTemplate`, `FormatLayout`, `FormatPartial`) against the file, skipped above 2000 lines per side. The mail controllers declare `recordActions` without a preview block: the admin offers them in the update form's footer, a boot rule only these internal controllers are exempt from. The layout form's CSS tab has the `disable_auto_inline_css` switch (`cabana.MailLayout.DisableAutoInlineCSS`, off for a new custom layout): on, postcard keeps the layout's CSS in its style block instead of also copying it onto the elements; the preview and the save validation render with the switch's value. Layout and partial content fields use the built-in `codeeditor` type (`language: html|css|text`, optional `mailImages`); Branding is the settings form `mail_brand` on `cabana.MailBrandSetting` (postcard's brand row, a `mailimage` logo, the `site_name` text field shown by the built-in layouts' header and footer (trimmed, at most 255 characters, empty falls back to the display name of `mail.from`; a name `postcard.UnsafeText` refuses is a 422 on `site_name` with `backend::lang.mail.brand.site_name_unsafe`) and 13 `colorpicker` colours; the first save switches mail from `mail.brandCss` to the compiled colours). Mail images is the singleton controller `cabana.MailImagesControllerID` (`cabana.MailImageLibrary`) with a public attachMany `images` fileupload; GET/POST `/mail/images` and GET `/mail/images/{id}` return absolute public URLs (`attach.AbsolutePublicURL`) and refuse with `mail.images.no_public_url` when neither `storage.uploads.public_url` nor `app.url` is set. Listing answers either mail permission; upload and the singleton form need `system.manage_mail_layouts`. POST `/mail/preview` renders an unsaved draft (`cabana.AdminMailPreviewRequest`: `mode`, `id`, `values`) through `postcard.Editor.Preview` and answers `cabana.AdminMailPreviewResult` (subject, html, text); mode `template` needs `system.manage_mail_templates`, modes `layout`, `partial` and `branding` need `system.manage_mail_layouts`. POST `/mail/test-send` (interactive sessions only) sends a template, layout or partial draft to the signed-in administrator's own email (`cabana.AdminMailTestSendResult`), refuses recipient keys in the body, and is limited to five sends per administrator per ten minutes through a published `cooler.Attempter` when `serve` has one, otherwise an in-process fixed window (429 with `Retry-After`). Forms carry `mailpreview` fields (`mode` matching the screen). - Danger record actions: `pact.AdminRecordAction.Danger` is served as `danger` on the record response's `cabana.RecordAction` (absent when false, so existing payloads are unchanged); the admin's confirm dialog then uses its danger variant. - Prompted record actions: a `pact.AdminRecordAction` with a `Prompt` (`pact.AdminActionPrompt`) asks the administrator for one text value in its confirm dialog. The record response serves it as `prompt` on the action's `cabana.RecordAction` (absent for every other action, so existing payloads are unchanged), and the action route accepts the body key `payload`, a JSON string, only for such an action: trimmed, not empty and at most `max_length` runes (422 on `payload` with `backend::lang.form.action_prompt_required` or `action_prompt_too_long`, `backend::lang.form.action_prompt_invalid` for another JSON type), then handed to `Run` as `pact.AdminRecordActionInput.Value`. Every other record action keeps refusing `record_id`, `values` and `payload`. A prompt without a label fails boot, owned or contributed. - My account contributions: a plugin implementing `pact.HasAccountContributions` adds sections (`pact.AccountContribution`) to the administrator's own account page, each with a status line and buttons (`pact.AccountAction`). GET `/account/contributions` lists them for the signed-in administrator and POST `/account/contributions/{name}/actions/{action}` runs one for that administrator only, behind the interactive-only guard, the action's permissions and its `Applies` rule, inside a transaction; the answer may carry a URL the admin opens in a new tab. That URL is kept only when it is an absolute `http`/`https` URL with a host or a same-origin path (one leading `/`); anything else, `javascript:` and `data:` included, is dropped and logged without the URL. A section whose `Status` fails is listed with an empty status and `error: true`, and an action whose `Applies` fails is left out and marks its section `error: true` as well; both are logged and the other sections are answered as usual. A status is translated only when it is a phrase key. Names are generic: cabana never names the contributing plugin. The existing `/account*` and `/auth/me` payloads are unchanged. A non-identifier or duplicate section name, an empty label, a duplicate or non-identifier action name, a nil `Run` or an empty action label stops the boot. diff --git a/modules/cabana/mail_admin.go b/modules/cabana/mail_admin.go index f0ece523..31bc3546 100644 --- a/modules/cabana/mail_admin.go +++ b/modules/cabana/mail_admin.go @@ -1800,11 +1800,16 @@ func (MailBrandSetting) Rules() map[string]string { var brandColourPattern = regexp.MustCompile(`^#[0-9a-f]{6}$`) -// BeforeValidate trims the site name, lower-cases colours, refuses anything -// but #rrggbb or empty, and checks logo_file_id is null or a library image. +// BeforeValidate trims the site name and refuses a name mail could not show +// (postcard's UnsafeText), lower-cases colours, refuses anything but #rrggbb +// or empty, and checks logo_file_id is null or a library image. One refusal +// lists every field at fault. func (b *MailBrandSetting) BeforeValidate(tx *gorm.DB) error { b.SiteName = strings.TrimSpace(b.SiteName) details := map[string]any{} + if postcard.UnsafeText(b.SiteName) { + details["site_name"] = []string{"backend::lang.mail.brand.site_name_unsafe"} + } for _, col := range []struct { name string value *string diff --git a/modules/cabana/mail_brand_layout_postgres_test.go b/modules/cabana/mail_brand_layout_postgres_test.go index d51ed7e7..ca230755 100644 --- a/modules/cabana/mail_brand_layout_postgres_test.go +++ b/modules/cabana/mail_brand_layout_postgres_test.go @@ -89,6 +89,31 @@ func TestMailBrandSiteName(t *testing.T) { t.Errorf("a send without a site name, a logo or a mail.from name has a header row:\n%s", got.HTML) } }) + + t.Run("unsafe_name_refused", func(t *testing.T) { + env.expect(t, http.StatusOK, http.MethodPut, mailBrandPath, root, map[string]any{"site_name": "Acme Mail"}) + // A name mail could not show is refused on the field; nothing is stored. + env.expectFieldRefusal(t, http.StatusUnprocessableEntity, http.MethodPut, mailBrandPath, root, + map[string]any{"site_name": "javascript: Acme"}, "site_name", "cannot be shown in mail", false) + var stored cabana.MailBrandSetting + if err := env.gdb.First(&stored, 1).Error; err != nil || stored.SiteName != "Acme Mail" { + t.Fatalf("refused save changed the row: %+v err=%v", stored, err) + } + // The preview of the unsaved draft renders without the name. + if html := brandPreview(t, env, root, map[string]any{"site_name": "javascript: Acme"}); strings.Contains(html, "javascript:") { + t.Errorf("the preview shows the unsafe name:\n%s", html) + } + // Prose with a colon is a name like any other. + env.expect(t, http.StatusOK, http.MethodPut, mailBrandPath, root, map[string]any{"site_name": "Big Data: Summit"}) + tmplID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome) + defaultID := env.mailRowID(t, postcard.LayoutsTable, "postcard::mail.layouts.default") + env.expect(t, http.StatusOK, http.MethodPut, fmt.Sprintf("%s/%d", mailTemplatesPath, tmplID), root, templateBody("Witaj, {{ .name }}", "Cześć **{{ .name }}**.", defaultID)) + got := sendGrace(t, env, blogWelcome) + if m := headerSpan.FindStringSubmatch(got.HTML); m == nil || m[1] != "Big Data: Summit" { + t.Errorf("sent header does not show the saved site name:\n%s", got.HTML) + } + env.expect(t, http.StatusOK, http.MethodPut, mailBrandPath, root, map[string]any{"site_name": ""}) + }) } // inlineLayoutFiles is the blog fixture whose blog layout carries a style diff --git a/modules/cabana/settings.go b/modules/cabana/settings.go index 16578186..bf9c744f 100644 --- a/modules/cabana/settings.go +++ b/modules/cabana/settings.go @@ -264,7 +264,9 @@ func (s SettingsService) Put(ctx context.Context, setting *CompiledSetting, body } if hook, ok := model.(lagoon.HasBeforeValidate); ok && hook != nil { if err := hook.BeforeValidate(tx); err != nil { - return err + // A refusal's phrase keys are localized, as on a + // controller save. + return localizeControllerError(ctx, s.Tr, err) } } rules := settingRules(setting, model) diff --git a/modules/phrasebook/backend/lang/en/lang.yaml b/modules/phrasebook/backend/lang/en/lang.yaml index 4c595a0c..d4c05dfb 100644 --- a/modules/phrasebook/backend/lang/en/lang.yaml +++ b/modules/phrasebook/backend/lang/en/lang.yaml @@ -703,6 +703,7 @@ mail: logo_comment: "The built-in layouts show the logo in their header. Your own layouts show it where they use {{ .logoUrl }}." site_name: "Site name" site_name_comment: "Shown in the header and footer of the built-in layouts. Leave it empty to use the sender name from mail.from." + site_name_unsafe: "This name cannot be shown in mail. Remove addresses that start with javascript:, vbscript: or data: and text such as onclick=." body_bg: "Body background" content_bg: "Content background" header_color: "Header colour" diff --git a/modules/phrasebook/backend/lang/pl/lang.yaml b/modules/phrasebook/backend/lang/pl/lang.yaml index c7339356..0754ef4b 100644 --- a/modules/phrasebook/backend/lang/pl/lang.yaml +++ b/modules/phrasebook/backend/lang/pl/lang.yaml @@ -741,6 +741,7 @@ mail: logo_comment: "Wbudowane układy pokazują logo w nagłówku. Własne układy pokazują je tam, gdzie używają {{ .logoUrl }}." site_name: "Nazwa witryny" site_name_comment: "Wyświetlana w nagłówku i stopce wbudowanych układów. Zostaw puste, aby użyć nazwy nadawcy z mail.from." + site_name_unsafe: "Tej nazwy nie można pokazać w wiadomościach. Usuń adresy zaczynające się od javascript:, vbscript: lub data: oraz tekst w rodzaju onclick=." body_bg: "Główne tło" content_bg: "Tło treści" header_color: "Kolor górnego nagłówka" diff --git a/modules/postcard/README.md b/modules/postcard/README.md index a5cb3913..d48ac17c 100644 --- a/modules/postcard/README.md +++ b/modules/postcard/README.md @@ -289,6 +289,8 @@ The row's `logo_file_id` names a public `system_files` row. Its URL is not store The row's `site_name` column is `postcard.Brand.SiteName`. The built-in layouts show it in their header (as the logo's alternative text when there is a logo) and footer. While it is empty, and while no Branding row exists, `{{ .siteName }}` is the display name of `mail.from` parsed with `net/mail` (`Acme` for `Acme `), or empty when the address has none. The name is HTML-escaped by `html/template` wherever a layout prints it. +A name `postcard.UnsafeText` refuses (a `javascript:`, `vbscript:` or `data:` URL, or text that would read as markup such as `Shop onclick=x`) never reaches a layout and never stops a send: an unsafe Branding name is treated as empty, so the `mail.from` display name is used if that one is safe, and an unsafe `mail.from` display name gives no name. A warning naming the source (`branding` or `mail.from`), never the value, is logged at most once a minute per source. Prose such as `Big Data: Summit` is a name like any other. The Branding preview of an unsaved draft leaves such a name out the same way; the admin's Branding form refuses to save it. + A mail that falls back to its file version because an override failed still gets the Branding. ### Sample values @@ -412,6 +414,7 @@ A draft is rendered by the code that renders a send, with the mailer's CSS and t | `postcard.Brand` | The Branding: thirteen colours, `postcard.Brand.LogoURL`, the logo's absolute URL, and `postcard.Brand.SiteName`, the name the built-in layouts show. | | `postcard.DefaultBrand` | WinterCMS's default mail colours. | | `postcard.CompileBrandCSS` | Checks a brand's colours and returns the brand CSS compiled from them. | +| `postcard.UnsafeText` | Reports whether a text a layout prints, such as the site name, must be kept out of mail: it holds a `javascript:`, `vbscript:` or `data:` URL, or fails the rendered-HTML safety checks once HTML-escaped. | | `postcard.Migrations` | The gormigrate set that creates the mail tables; lagoon runs it under the `summercms.postcard` history. | | `postcard.TemplatesTable`, `postcard.LayoutsTable`, `postcard.PartialsTable`, `postcard.BrandTable`, `postcard.ImageLibraryTable` | The names of the mail tables, for code that defines models over them. | | `postcard.SyncIndex` | Upserts one index row per file template, layout and partial of a catalog; mirrors the file into rows that are not customized and refreshes `file_hash` and the template's `base_code` on all. | @@ -467,7 +470,7 @@ mail: - SummerCMS modules: [backpack](../backpack/README.md), [compass](../compass/README.md), [diary](../diary/README.md) (component logger `postcard` when the app publishes no logger), [pact](../pact/README.md), and the `attach` package of [lagoon](../lagoon/README.md) (`attach.AbsolutePublicURL` and `attach.BlobKey` for the logo's URL; lagoon itself is not imported). - Third-party: `github.com/wneessen/go-mail` (SMTP), `github.com/yuin/goldmark` (Markdown, and its table extension inside partials), `github.com/vanng822/go-premailer` (CSS inlining, pinned at v1.38.0; see `.planning/notes/2026-11-13-mail-layouts-css-inlining.md`), `golang.org/x/net/html` (tokenizing rendered HTML for the safety checks, already a framework dependency; see `.planning/notes/2026-11-14-mail-url-scheme-check.md`), `gorm.io/gorm` (reading overrides), `github.com/go-gormigrate/gormigrate/v2` (the mail tables' migrations). -- Standard library: `bytes`, `context`, `crypto/rand`, `crypto/sha256`, `database/sql`, `embed`, `encoding/hex`, `errors`, `fmt`, `html/template`, `io/fs`, `log/slog`, `net/mail`, `regexp`, `sort`, `strconv`, `strings`, `sync`, `text/template` (and `text/template/parse`), `time`. +- Standard library: `bytes`, `context`, `crypto/rand`, `crypto/sha256`, `database/sql`, `embed`, `encoding/hex`, `errors`, `fmt`, `html`, `html/template`, `io/fs`, `log/slog`, `net/mail`, `regexp`, `sort`, `strconv`, `strings`, `sync`, `text/template` (and `text/template/parse`), `time`. - Tests additionally use `github.com/testcontainers/testcontainers-go` (Mailpit and Postgres containers), `gorm.io/driver/postgres` and `github.com/jackc/pgx/v5`. ## Testing diff --git a/modules/postcard/editor.go b/modules/postcard/editor.go index 0a4d8ed4..db25ec65 100644 --- a/modules/postcard/editor.go +++ b/modules/postcard/editor.go @@ -325,7 +325,9 @@ func (e *Editor) renderBrand(d Draft, ov Overrides, opts renderOptions) (Rendere return RenderedMessage{}, err } opts.brandCSS, opts.logoURL = css, brand.LogoURL - opts.siteName = siteName(&brand, e.m.opts.From) + // An unsafe draft name is left out as a send would leave it out; the + // Branding save is what refuses it. + opts.siteName = e.m.layoutSiteName(&brand) opts.overrides = ov sample := sampleMessage() return e.m.catalog.renderFrom(Message{ diff --git a/modules/postcard/mailer.go b/modules/postcard/mailer.go index 0033068d..faf00c0f 100644 --- a/modules/postcard/mailer.go +++ b/modules/postcard/mailer.go @@ -149,11 +149,13 @@ func (m *mailer) render(ctx context.Context, msg Message) (RenderedMessage, erro // options returns the render options of the file version: mail.css, and // either the saved Branding (its compiled CSS and its logo) or, while none // has been saved, mail.brandCss. A Branding whose colours do not compile -// keeps mail.brandCss. The site name is the Branding's, else the display -// name of mail.from. +// keeps mail.brandCss. The site name is layoutSiteName's: the Branding's, +// else the display name of mail.from, leaving out a name that fails the +// safety check. The override render and the override-failure fallback are +// built from these options, so all of them carry the same checked name. func (m *mailer) options(brand *Brand) renderOptions { opts := renderOptions{ - css: m.opts.CSS, brandCSS: m.opts.BrandCSS, siteName: siteName(brand, m.opts.From), year: time.Now().Year(), + css: m.opts.CSS, brandCSS: m.opts.BrandCSS, siteName: m.layoutSiteName(brand), year: time.Now().Year(), inline: m.inline, warn: m.warn, } if brand == nil { @@ -172,18 +174,51 @@ func (m *mailer) options(brand *Brand) renderOptions { // siteName returns the name the built-in layouts show: the Branding's site // name, trimmed, else the display name of the sender address from, else -// empty. +// empty. A name UnsafeText refuses is skipped. func siteName(brand *Brand, from string) string { + name, _ := siteNameFrom(brand, from) + return name +} + +// siteNameFrom returns the first non-empty candidate UnsafeText accepts, of +// the trimmed Branding site name and the trimmed display name of from. In +// skipped it returns the source ("branding" or "mail.from") of the first +// non-empty candidate it refused. +func siteNameFrom(brand *Brand, from string) (name, skipped string) { + type candidate struct{ source, name string } + var candidates []candidate if brand != nil { - if name := strings.TrimSpace(brand.SiteName); name != "" { - return name + candidates = append(candidates, candidate{"branding", strings.TrimSpace(brand.SiteName)}) + } + if addr, err := netmail.ParseAddress(from); err == nil { + candidates = append(candidates, candidate{"mail.from", strings.TrimSpace(addr.Name)}) + } + for _, c := range candidates { + if c.name == "" { + continue } + if UnsafeText(c.name) { + if skipped == "" { + skipped = c.source + } + continue + } + return c.name, skipped } - addr, err := netmail.ParseAddress(from) - if err != nil { - return "" + return "", skipped +} + +// layoutSiteName is the site name the layouts get for brand and mail.from. +// A name that fails the safety check is left out, so it can never stop a +// send; a warning names its source, never its value, at most once per +// warnInterval. +func (m *mailer) layoutSiteName(brand *Brand) string { + name, skipped := siteNameFrom(brand, m.opts.From) + if skipped != "" { + m.warn("site_name:"+skipped, "postcard: site name left out of the layouts, it fails the mail safety check", + slog.String("source", skipped)) } - return strings.TrimSpace(addr.Name) + return name } // overrides asks the source once. A failed lookup (no connection, tables not diff --git a/modules/postcard/safety.go b/modules/postcard/safety.go index 1ce7fb93..bfdecb33 100644 --- a/modules/postcard/safety.go +++ b/modules/postcard/safety.go @@ -1,11 +1,31 @@ package postcard import ( + "html" + "regexp" "strings" xhtml "golang.org/x/net/html" ) +// scriptURLText finds a script URL in text: javascript: or vbscript: at a +// scheme boundary, or data: at a scheme boundary directly followed by a +// non-space character (a data URL). A boundary is the start of the text or a +// character that cannot belong to a URL scheme, so "Metadata: Weekly" and +// "Big Data: Summit" do not match. +var scriptURLText = regexp.MustCompile(`(?i)(?:^|[^a-z0-9+.\-])(?:(?:javascript|vbscript):|data:\S)`) + +// UnsafeText reports whether a text that a layout prints, such as the site +// name of the built-in layouts, must be kept out of mail. A text is unsafe +// when, HTML-escaped as html/template prints text, it fails the rendered-HTML +// safety checks (for example event-handler-shaped text such as +// "Shop onclick=x"), or when it holds a script URL: javascript: or vbscript: +// at a scheme boundary, or a data: URL. "Big Data: Summit" is safe; +// "javascript: Acme" is not. +func UnsafeText(s string) bool { + return validateHTML(html.EscapeString(s)) != nil || scriptURLText.MatchString(s) +} + // urlAttributes are the attributes that hold one URL. Their decoded value is // refused when it starts with a script or data scheme. var urlAttributes = map[string]bool{ diff --git a/modules/postcard/safety_smoke_test.go b/modules/postcard/safety_smoke_test.go index cbf382f2..ffa35432 100644 --- a/modules/postcard/safety_smoke_test.go +++ b/modules/postcard/safety_smoke_test.go @@ -2,6 +2,7 @@ package postcard import ( "bytes" + "context" "log/slog" "strings" "testing" @@ -101,4 +102,71 @@ func TestMailSafetySmoke(t *testing.T) { } } }) + t.Run("unsafe_site_name", func(t *testing.T) { + ctx := context.Background() + for _, s := range []string{"", "Acme", "Big Data: Summit", "Metadata: Weekly", "Metadata:Weekly", "Acme ", "*Acme*", "[x](https://example.com)"} { + if UnsafeText(s) { + t.Errorf("UnsafeText(%q) = true, want false", s) + } + } + for _, s := range []string{"javascript:alert(1)", "javascript: Acme", "JavaScript:x", "Go vbscript:msgbox(1)", "data:text/html,x", "Shop onclick=x"} { + if !UnsafeText(s) { + t.Errorf("UnsafeText(%q) = false, want true", s) + } + } + + // An unsafe Branding name is left out; the mail.from name is shown, + // and one warning names the source, never the value. + m, drv := partialsMailer(t, Options{From: "Acme "}, &Overrides{Brand: &Brand{SiteName: "javascript:alert(1)"}}) + logs := captureLog(m) + for range 2 { + msg := sendTemplate(t, m, drv, "acme.blog::mail.welcome", inlineVars) + assertSiteName(t, msg, "Acme") + if strings.Contains(msg.HTML, "javascript:") || strings.Contains(msg.Text, "javascript:") { + t.Errorf("the unsafe name reached the message:\n%s\n%s", msg.HTML, msg.Text) + } + } + out := logs.String() + if n := strings.Count(out, "site name left out of the layouts"); n != 1 { + t.Errorf("%d site name warnings in two sends, want 1:\n%s", n, out) + } + if !strings.Contains(out, "source=branding") || strings.Contains(out, "alert") { + t.Errorf("log = %q, want the source and not the value", out) + } + + // Both names unsafe: no name at all, so no header row (no logo) and a + // footer with the year only. + m, drv = partialsMailer(t, Options{From: `"javascript: Acme" `}, &Overrides{Brand: &Brand{SiteName: "Shop onclick=x"}}) + logs = captureLog(m) + msg := sendTemplate(t, m, drv, "acme.blog::mail.welcome", inlineVars) + if _, ok := headerCell(msg.HTML); ok { + t.Errorf("a header row without a name or a logo:\n%s", msg.HTML) + } + if got := footerText(t, msg.HTML); got != copyright() { + t.Errorf("footer = %q, want %q", got, copyright()) + } + if out := logs.String(); !strings.Contains(out, "source=branding") || strings.Contains(out, "onclick") { + t.Errorf("log = %q, want the branding source and not the value", out) + } + + // The editor: saving a template or a layout under a stored unsafe + // name is not refused; the Branding preview of an unsafe draft name + // renders without it. + ed, _ := newEditor(t, &Overrides{Brand: &Brand{SiteName: "Shop onclick=x"}}) + tmpl := Draft{Kind: KindTemplate, Name: editorWelcome, Subject: "Hi {{ .Name }}", Body: "Hi **{{ .Name }}**.", Layout: defaultLayoutName} + if err := ed.Validate(ctx, tmpl); err != nil { + t.Errorf("a template draft under an unsafe stored name was refused: %+v", err) + } + layout := Draft{Kind: KindLayout, Name: defaultLayoutName, HTML: `
{{ .Content }}
{{ partial "footer" "body" .siteName }}`, Text: "{{ .Content }}"} + if err := ed.Validate(ctx, layout); err != nil { + t.Errorf("a layout draft under an unsafe stored name was refused: %+v", err) + } + preview, err := ed.Preview(ctx, Draft{Kind: KindBrand, Brand: &Brand{SiteName: "javascript:alert(1)"}}) + if err != nil { + t.Fatalf("Branding preview of an unsafe name: %v", err) + } + if strings.Contains(preview.HTML, "javascript:") || strings.Contains(preview.Text, "javascript:") { + t.Errorf("the Branding preview shows the unsafe name:\n%s", preview.HTML) + } + }) }