From 75669b343f028e38f8044a746c963d0cd2c65f82 Mon Sep 17 00:00:00 2001 From: Jakub Zych Date: Fri, 13 Nov 2026 22:23:31 +0100 Subject: [PATCH] docs(35): add code review report --- .../35-REVIEW.md | 303 +++++++++--------- 1 file changed, 144 insertions(+), 159 deletions(-) diff --git a/.planning/phases/35-mail-templates-and-layouts-editor/35-REVIEW.md b/.planning/phases/35-mail-templates-and-layouts-editor/35-REVIEW.md index a0ce8346..d6f355b7 100644 --- a/.planning/phases/35-mail-templates-and-layouts-editor/35-REVIEW.md +++ b/.planning/phases/35-mail-templates-and-layouts-editor/35-REVIEW.md @@ -1,216 +1,201 @@ --- phase: 35-mail-templates-and-layouts-editor -reviewed: 2026-11-13T13:39:18Z +reviewed: 2026-11-13T18:30:00Z depth: standard -files_reviewed: 91 +scope: incremental (gap closure 35-05, 35-06, 35-07; diff 593f99ac..HEAD) +files_reviewed: 52 files_reviewed_list: + - admin/openapi/admin.json - admin/src/api/schema.d.ts - - admin/src/api/types.ts - - admin/src/components/form/codeeditor/editor.ts - - admin/src/components/form/codeeditor/load.ts - - admin/src/components/form/fields/CodeEditorField.vue - - admin/src/components/form/fields/ColorPickerField.vue - - admin/src/components/form/fields/DatepickerField.vue - - admin/src/components/form/fields/MailImageField.vue - - admin/src/components/form/fields/MailPreviewField.vue - - admin/src/components/form/fields/MarkdownField.vue - - admin/src/components/form/fields/PartialField.vue - - admin/src/components/form/formContext.ts - - admin/src/components/form/registry.ts - - admin/src/components/list/DataTable.vue - - admin/src/components/list/RowStateBadges.vue - - admin/src/components/mail/insertImage.ts - - admin/src/components/mail/MailImagePicker.vue - - admin/src/styles/main.css + - admin/src/components/form/LocaleVariantSwitcher.vue - admin/src/views/FormView.vue - - admin/src/views/ListView.vue - - admin/src/views/SettingsFormView.vue - - modules/beachcomber/engines.go - - modules/beachcomber/searchable.go - - modules/beachcomber/typesense/engine.go - - modules/beachcomber/typesense/highlights.go - - modules/cabana/admin_openapi.go - - modules/cabana/backendscreens/controllers/mailimages/config_form.yaml - - modules/cabana/backendscreens/controllers/maillayouts/config_filter.yaml - - modules/cabana/backendscreens/controllers/maillayouts/config_form.yaml - - modules/cabana/backendscreens/controllers/maillayouts/config_list.yaml - - modules/cabana/backendscreens/controllers/maillayouts/_file_version.htm - - modules/cabana/backendscreens/controllers/maillayouts/_info.htm - - modules/cabana/backendscreens/controllers/mailpartials/config_filter.yaml - - modules/cabana/backendscreens/controllers/mailpartials/config_form.yaml - - modules/cabana/backendscreens/controllers/mailpartials/config_list.yaml - - modules/cabana/backendscreens/controllers/mailpartials/_file_version.htm - - modules/cabana/backendscreens/controllers/mailpartials/_info.htm - - modules/cabana/backendscreens/controllers/mailtemplates/config_filter.yaml - - modules/cabana/backendscreens/controllers/mailtemplates/config_form.yaml - - modules/cabana/backendscreens/controllers/mailtemplates/config_list.yaml - - modules/cabana/backendscreens/controllers/mailtemplates/_file_version.htm + - admin/tests/form/FormViewMail.test.ts + - admin/tests/form/LocaleVariantSwitcher.test.ts + - docs/backend/forms.md + - docs/services/mail.md + - go.mod + - go.sum + - modules/cabana/README.md - modules/cabana/backendscreens/controllers/mailtemplates/_info.htm - - modules/cabana/backend_screens.go + - modules/cabana/backendscreens/controllers/mailtemplates/config_filter.yaml - modules/cabana/backendscreens/models/mailbrandsetting/fields.yaml - - modules/cabana/backendscreens/models/mailimagelibrary/fields.yaml - - modules/cabana/backendscreens/models/maillayout/columns.yaml - modules/cabana/backendscreens/models/maillayout/fields.yaml - - modules/cabana/backendscreens/models/mailpartial/columns.yaml - - modules/cabana/backendscreens/models/mailpartial/fields.yaml - modules/cabana/backendscreens/models/mailtemplate/columns.yaml - - modules/cabana/backendscreens/models/mailtemplate/fields.yaml - modules/cabana/crud.go - - modules/cabana/extension.go - - modules/cabana/field_file.go - - modules/cabana/field_mail.go - - modules/cabana/form_schema.go - - modules/cabana/http.go - modules/cabana/mail_admin.go - - modules/cabana/mail_diff.go + - modules/cabana/mail_brand_layout_postgres_test.go + - modules/cabana/mail_lifecycle_postgres_test.go + - modules/cabana/mail_locale_postgres_test.go - modules/cabana/mail_routes.go - - modules/cabana/messages.go - - modules/cabana/query.go + - modules/cabana/mail_screens_smoke_test.go + - modules/cabana/mail_unit_test.go - modules/cabana/relation_field.go - - modules/cabana/schema_types.go - - modules/cabana/settings.go - - modules/conga/commands.go - - modules/lagoon/attach/absolute.go - - modules/lagoon/commands.go - - modules/lagoon/migrations.go - - modules/pact/capabilities.go - modules/phrasebook/backend/lang/en/lang.yaml - modules/phrasebook/backend/lang/pl/lang.yaml - - modules/pier/pier.go + - modules/postcard/README.md - modules/postcard/assets/brand.css.tmpl + - modules/postcard/assets/default.htm - modules/postcard/assets/minimal.htm - - modules/postcard/assets/partials/button.htm - - modules/postcard/assets/partials/panel.htm - - modules/postcard/assets/partials/subcopy.htm - - modules/postcard/assets/partials/table.htm - - modules/postcard/assets/sample.htm + - modules/postcard/assets/partials/footer.htm + - modules/postcard/assets/partials/header.htm - modules/postcard/assets/system.htm - modules/postcard/brand.go + - modules/postcard/brand_smoke_test.go + - modules/postcard/brand_test.go - modules/postcard/editor.go + - modules/postcard/editor_smoke_test.go + - modules/postcard/inline.go + - modules/postcard/inline_test.go + - modules/postcard/layouts_test.go + - modules/postcard/locale_postgres_test.go + - modules/postcard/locale_test.go - modules/postcard/mailer.go - - modules/postcard/partials.go - - modules/postcard/samples.go + - modules/postcard/mailer_test.go + - modules/postcard/override_smoke_test.go + - modules/postcard/override_test.go + - modules/postcard/partials_smoke_test.go - modules/postcard/store.go - modules/postcard/templates.go - - modules/surf/serve.go - - modules/wristband/authorize.go - scripts/check-phase35.sh findings: - critical: 0 - warning: 4 - info: 3 - total: 7 + critical: 1 + warning: 5 + info: 4 + total: 10 status: issues_found --- -# Phase 35: Code Review Report +# Phase 35: Code Review Report (gap closure 35-05 / 35-06 / 35-07) -**Reviewed:** 2026-11-13T13:39:18Z +**Reviewed:** 2026-11-13T18:30:00Z **Depth:** standard -**Files Reviewed:** 91 +**Files Reviewed:** 52 **Status:** issues_found +This report supersedes the earlier 35-REVIEW.md (2026-11-13T13:39:18Z, plans 35-01..35-04). It reviews the incremental scope `593f99ac..HEAD`: one admin record per mail template with a locale switcher (postcard `TemplateFor`, `EnsureLocaleRows`, the `base_code` migration, cabana grouping, the switcher), the WinterCMS default layout with header/footer partials, `Brand.SiteName`, CSS inlining via go-premailer with a per-layout opt-out, and the 35-07 tests and `check-phase35.sh` consumer stage. Earlier findings for files outside this diff are not re-stated here. + ## Summary -Phase 35 (mail templates/layouts editor) was reviewed at standard depth across postcard, cabana mail screens/routes, and the admin SPA mail editor. Security posture is solid: permission gates, `interactiveOnly` test-send, recipient-key refusal, rate limiting, sandboxed preview iframe (`sandbox=""`), HTML/CSS unsafe-tag checks, colour validation, and image upload limits. Draft validation runs inside the form save transaction (`FormAfterUpdate`), so invalid overrides roll back. Findings below are correctness/UX gaps, not blockers. +The locale-group model is mostly consistent. Send resolution, the admin's `base_code` grouping, reset, drift stamping and the switcher agree on what a fallback-locale row is. Inlining is wrapped with panic recovery and degrades to the style block on inliner errors. The vue switcher reverts correctly on a refused navigation, and FormView is remounted per path, so variants never go stale. + +The main defect is the known site-name item. Its impact is wider than recorded. The check that fails is the unanchored `dangerousScheme` regex, so ordinary names such as "Big Data: Summit" or "Metadata: Weekly" fail it. The same name taken from `mail.from` breaks every built-in-layout send after an upgrade, with no admin action. It also blocks saving any template or layout in the admin. I confirmed this with a probe test run through a `go test -overlay` that changed no source. Other issues: the site name is rendered as Markdown in the footer. Lock ordering in the show and save transactions can deadlock. A swallowed error inside a Postgres transaction leaves it aborted. The fallback rule silently accepts typos while rejecting real 3-letter locales. The safety check runs before entity decoding, which the new opt-out now exposes. ## Narrative Findings (AI reviewer) +## Critical Issues + +### CR-01: Site name (Branding or mail.from display name) can stop every send on the built-in layouts and block template/layout saves + +**File:** `modules/cabana/mail_admin.go:1781-1806`, `modules/postcard/mailer.go:124,154-198`, `modules/postcard/templates.go:45`, `modules/postcard/assets/default.htm:10,28`, `modules/postcard/assets/system.htm` (same lines), `modules/postcard/assets/partials/header.htm` +**Issue:** This confirms and widens the known open item. `siteName` is inserted into the rendered HTML (header ``/`alt`, footer line). The rendered HTML then goes through `validateHTML`, whose `dangerousScheme` is `(?i)(?:javascript|vbscript|data):` with no word boundary and no attribute context. Any site name containing `data:` as a substring fails it. Verified with a probe (overlay test, no source change): +- Branding `SiteName: "Big Data: Summit"`: `Send` of a default-layout template fails with `error calling partial: postcard: rendered HTML contains a dangerous URL scheme`. +- No Branding, `mail.from = "\"Metadata: Weekly\" "`, which is a valid address: the same failure. An application whose sender name contains `data:` stops sending all default/system-layout mail after upgrading to this phase, without anyone touching the admin. +- With that Branding saved, `Editor.Validate` of an ordinary template draft returns `postcard: draft layout: unsafe: ...Big Data: Summit...`. `FormAfterUpdate` runs this validation, so every template on default/system and every layout save is refused, and the error is blamed on the Layout field. + +Nothing catches this when the name is saved. `MailBrandSetting.Rules` has `site_name: nullable|max:255`, `BeforeValidate` only trims, and the Branding settings form never calls `editor.Validate`. Nothing catches it when mail is sent either. `mailer.render` builds the "file version" fallback with `m.options(ov.Brand)`, which carries the same site name, so the override-to-file fallback fails too and `Send` returns the error. Password-reset and other system mail stop. +**Fix:** Check the name in both places. When it is saved, refuse it on the field. When mail is sent, never let a site name fail the render: +```go +// postcard: export the check so cabana can reuse it +func UnsafeText(s string) bool { return validateHTML(html.EscapeString(s)) != nil } + +// postcard/mailer.go siteName(): drop a name that would fail the safety check +name := ... +if UnsafeText(name) { + // log once via m.warn, fall back to "" + return "" +} + +// cabana MailBrandSetting.BeforeValidate +if postcard.UnsafeText(b.SiteName) { + details["site_name"] = []string{"backend::lang.mail.brand.site_name_unsafe"} +} +``` +Also consider anchoring `dangerousScheme` to URL-bearing attribute values (`href|src|action|style|background`) instead of the whole document. Today any body text or variable containing `metadata:` breaks the send as well. That part predates this phase, but the site name makes it reachable from configuration alone. + ## Warnings -### WR-01: Layout status filter hides every database-only layout +### WR-01: Site name is interpreted as Markdown in the footer (but printed literally in the header) -**File:** `modules/cabana/mail_admin.go:682-688` -**Issue:** `mailStatusScope` treats "customized" and "outdated" as file-backed only (`is_custom AND source IS NOT NULL`), while "not_customized" is `NOT is_custom`. Database-only layouts have `source IS NULL` and `is_custom = true`, so they match none of the three values. Choosing any status on the layouts list silently drops all custom layouts. -**Fix:** Include database-only layouts under customized (and keep outdated file-backed-only), e.g.: +**File:** `modules/postcard/assets/partials/footer.htm:11`, `modules/postcard/assets/default.htm:28`, `modules/postcard/assets/system.htm` (footer call), `modules/postcard/README.md:290` +**Issue:** The layouts build `$copy := "© "` and pass it as `body` to the `footer` partial, which renders `{{ markdown .body }}`. A probe confirmed: +- `*Acme* Shop` becomes `© 2026 Acme Shop`. +- `Acme ` becomes `© 2026 Acme `. The name is lost and an HTML comment is shipped in the mail. +- `[Acme](https://evil.example)` becomes a live link in every mail. +The header prints the same value escaped and literal, so header and footer disagree. The README states "The name is HTML-escaped by `html/template` wherever a layout prints it", which is false for the footer. The source is admin-controlled, but Markdown is not the documented contract for this field. +**Fix:** Escape Markdown metacharacters before building `$copy`, or give the footer partial a plain-text argument for the built-in layouts. For example, add a `text` key that the partial prints as `

{{ .text }}

` and keep `markdown .body` for callers that pass Markdown on purpose. Alternatively, render the copyright `

` directly in the layout. + +### WR-02: Lock-order inversion between show/save transactions and the index sync (global advisory lock taken inside request transactions) + +**File:** `modules/cabana/crud.go:562-567` (ShowRecord), `modules/cabana/crud.go:1000-1003` (save), `modules/cabana/mail_admin.go:1960-1977`, `modules/postcard/store.go:520-582` +**Issue:** `recordLocaleVariants` runs `postcard.EnsureLocaleRows` inside the ShowRecord transaction and inside the save transaction, after the row write. `EnsureLocaleRows` takes `pg_advisory_xact_lock(syncLockKey)` and holds it until the outer request transaction ends. The savepoint does not release it. It then upserts every fallback row of the template with `ON CONFLICT DO UPDATE ... WHERE`, which row-locks each conflicting row even when nothing changes. `rows` is built from the catalog alone, so this runs on every show of a template that has a locale without a file. +- Save tx A updates row `welcome-pl` (row lock), then waits for the advisory lock. +- Show tx B for `welcome-de`, or `SyncIndex` from `ensureSynced`, holds the advisory lock and upserts `welcome-pl`, so it waits on A's row lock. + +Postgres detects the deadlock after `deadlock_timeout`. One side's savepoint absorbs it with only a warning, or the sync fails, so it self-heals. The cost is about 1s stalls and spurious warnings. In addition, every show of a mail template, a GET, serializes on one global lock, row-locks sibling rows, and performs writes for users who only have read access. +**Fix:** Move `EnsureLocaleRows` out of the request transaction. Run it before `ShowRecord` opens its transaction, on `m.db()`, or only from `ensureSynced`. At minimum, check for missing rows with a plain `SELECT code ... WHERE code IN ?` and call `EnsureLocaleRows` only when some are absent. Drop it from the save path entirely, because the saved row already exists there. + +### WR-03: `mailLocales` swallows TranslationWriter errors while running inside a Postgres transaction + +**File:** `modules/cabana/mail_admin.go:173-201`, called with the show/save `tx` from `mail_admin.go:1965` and through `localeInfo` (`requestDB(ctx)`, line 764 onward) +**Issue:** The function is written as "warn and continue" (`moduleLog.WarnContext(ctx, "cabana: mail locales: enabled locales", ...)`). When `db` is a request transaction, a failing `EnabledLocales` or `DefaultLocale` SQL statement puts the whole transaction into the aborted state. Every later statement fails with "current transaction is aborted": the `EnsureLocaleRows` savepoint, then the `localeVariants` query, which returns its error. The mail template show then fails with a 500. Opening a template therefore depends on an optional plugin's tables being healthy, which is exactly the failure the code tried to tolerate. +**Fix:** Call the writer through its own savepoint so a failure is really contained: ```go -case mailStatusCustomized: - return db.Where(table + ".is_custom") -case mailStatusNotCustomized: - return db.Where("NOT " + table + ".is_custom") -case mailStatusOutdated: - return db.Where(table + ".is_custom AND " + table + ".source IS NOT NULL AND " + table + ".base_hash IS DISTINCT FROM " + table + ".file_hash") -``` - -### WR-02: Unknown `filterStatus` value leaves the query unfiltered - -**File:** `modules/cabana/mail_admin.go:677-689` -**Issue:** When `name == mailFilterStatus` but `value` is not one of the three known statuses, the function returns `db` unchanged (all rows). Wrong scope names correctly match nothing (`1 = 0`); wrong values do the opposite. -**Fix:** - -```go - switch value { - case mailStatusCustomized: - // ... - case mailStatusNotCustomized: - // ... - case mailStatusOutdated: - // ... - default: - return db.Where("1 = 0") - } -``` - -### WR-03: Mail image upload errors ignore field-level validation details - -**File:** `admin/src/components/mail/MailImagePicker.vue:180-182` -**Issue:** Upload failures from the API use `ValidationError` details shaped as `{ file: ["…"] }` (`mail_routes.go` via `writeCRUDError`). The picker reads `details.message`, which is absent, so operators usually see the generic top-level `"Validation failed"` instead of the attach limit/type message. -**Fix:** Prefer the first string under `details.file` (or any field array), then fall back: - -```ts -const err = (error as { error?: { message?: string; details?: Record } } | undefined)?.error -const fieldDetails = err?.details?.file -const fromFile = Array.isArray(fieldDetails) ? fieldDetails.find((v) => typeof v === 'string') : undefined -uploadError.value = - (typeof fromFile === 'string' && fromFile) || - (typeof err?.details?.message === 'string' && err.details.message) || - err?.message || - t('backend::lang.mail.picker.load_failed') -``` - -### WR-04: Partial preview/test-send gated only on `content_html` - -**File:** `admin/src/components/form/fields/MailPreviewField.vue:47-66` -**Issue:** For `mode === 'partial'` (and `layout`), `draftEmpty` only inspects `content_html`. A text-only partial draft (empty HTML, non-empty `content_text`) shows the empty state and disables test-send on the text tab, even though the server draft can render text. -**Fix:** Treat the draft as non-empty when any relevant content field is present: - -```ts -const draftEmpty = computed(() => { - if (mode.value === 'branding') return false - if (mode.value === 'template') { - const raw = formValues.value.body - return raw === null || raw === undefined || String(raw).trim() === '' - } - const html = String(formValues.value.content_html ?? '').trim() - const text = String(formValues.value.content_text ?? '').trim() - const css = mode.value === 'layout' ? String(formValues.value.content_css ?? '').trim() : '' - return html === '' && text === '' && css === '' +_ = db.Transaction(func(sp *gorm.DB) error { + codes, err := w.EnabledLocales(ctx, sp) + if err != nil { return err } // rolls back to the savepoint only + add(codes...) + return nil }) ``` +Alternatively, pass `m.db()` instead of the request transaction. The value is not transactional. + +### WR-04: Fallback-locale rule silently resolves typos, yet rejects real locales the admin offers + +**File:** `modules/postcard/templates.go:249` (`localeTag`), `templates.go:271-291` (`fallbackLocked`), `modules/postcard/store.go:556-561` +**Issue:** `localeTag` accepts any two letters with an optional 2-8 character subtag, independent of the application's locales. A probe confirmed: +- `acme.blog::mail.order-ok` resolves to `order`. +- `acme.blog::mail.order-xx-confirm` resolves to `order`, because `xx-confirm` matches. + +A mistyped or removed template name of that shape now sends the wrong mail instead of failing with `unknown template`, and nothing is logged. In the other direction, the admin's locale set (translator plus translate plugin) can contain 3-letter ISO 639 codes (`fil`, `haw`) or multi-subtag tags (`zh-Hant-TW`). For those, `TemplateFor` fails, so `EnsureLocaleRows` silently skips them (the `!ok` branch at 559) and sends of `