Skip to content

Fixed 500 on newsletter verification with a non-newsletter token - #30281

Open
9larsons wants to merge 1 commit into
mainfrom
slars/newsletter-verification-token-guard
Open

Fixed 500 on newsletter verification with a non-newsletter token#30281
9larsons wants to merge 1 commit into
mainfrom
slars/newsletter-verification-token-guard

Conversation

@9larsons

Copy link
Copy Markdown
Contributor

ref https://linear.app/ghost/issue/PLA-375

Why

The newsletters service and the settings BREAD service each construct their own MagicLink with a separate SingleUseTokenProvider, but both providers wrap the same SingleUseToken model. There's no type discriminator on the token, so a support address verification token validates cleanly against the newsletter verification endpoint.

The payloads differ: settings tokens carry {key, value}, while verifyPropertyUpdate destructures {id, property, value}. A support token therefore leaves id undefined, which reaches Newsletter.edit(attrs, {id: undefined}) and makes knex throw at query-compile time:

Undefined binding(s) detected when compiling SELECT. Undefined column(s): [id]

That's a raw error rather than a Ghost API error, so it surfaces as a 500. It never degrades into a clean 404, because the throw happens before the row lookup runs.

What changed

verifyPropertyUpdate now validates the token payload before touching the model: id must be present, and property must be one of sender_email / sender_reply_to. Anything else gets a BadRequestError.

This mirrors the guard the settings service already applies in verifyKeyUpdate, which rejects keys outside its EMAIL_KEYS allowlist for the same reason — tokens issued for another flow, or by an older version.

Notes for reviewers

  • No user-facing behaviour change, so no release-note emoji. Admin routes each verification link to a single handler, so this path isn't reachable through the UI today; the fix is about the endpoint not 500ing on a token it shouldn't accept.
  • Two unit tests added: a support-address token payload, and a token naming a property that can't be verified. Both assert BadRequestError and that the model is never touched.
  • test/unit/server/services/newsletters/service.test.js passes (17 tests), eslint and oxfmt clean.

ref https://linear.app/ghost/issue/PLA-375

Newsletter and settings email verification links are issued by two separate
MagicLink services that share one single-use token store, so a support address
token decodes cleanly on the newsletter side. Its payload is `{key, value}`
rather than `{id, property, value}`, which left the model edit with an
undefined id and knex throwing "Undefined binding(s) detected" as a 500.

Validating the token payload up front mirrors the key allowlist the settings
service already applies in verifyKeyUpdate, and turns the crash into a 400.
@nx-cloud

nx-cloud Bot commented Aug 25, 2026

Copy link
Copy Markdown

🤖 Nx Cloud AI Fix

Ensure the fix-ci command is configured to always run in your CI pipeline to get automatic fixes in future runs. For more information, please see https://nx.dev/ci/features/self-healing-ci


View your CI Pipeline Execution ↗ for commit 13c3006

Command Status Duration Result
nx run ghost:test:ci:integration ✅ Succeeded 3m 6s View ↗
nx run ghost:test:integration ✅ Succeeded 3m 31s View ↗
nx run ghost:test:legacy ✅ Succeeded 3m 2s View ↗
nx run ghost:test:e2e ✅ Succeeded 2m 59s View ↗
nx run-many -t test:unit -p ghost ✅ Succeeded 32s View ↗
nx run ghost-monorepo:lint:boundaries ✅ Succeeded 22s View ↗
nx run-many -t lint -p ghost,ghost-monorepo ✅ Succeeded 20s View ↗
nx run-many --target=build --projects=tag:publi... ✅ Succeeded <1s View ↗
nx run @tryghost/admin:build ✅ Succeeded 4s View ↗

💡 Verify your cache is correct by running tasks in a sandbox. Read docs ↗


☁️ Nx Cloud last updated this comment at 2026-08-25 14:15:08 UTC

@coderabbitai

coderabbitai Bot commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: QUIET

Plan: Pro Plus

Run ID: 124e8511-1e7a-4eda-8d00-4dd15ec00bfd

📥 Commits

Reviewing files that changed from the base of the PR and between faf88e0 and 13c3006.

📒 Files selected for processing (2)
  • ghost/core/core/server/services/newsletters/newsletters-service.js
  • ghost/core/test/unit/server/services/newsletters/service.test.js

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

📜 Recent review details
⏰ Context from checks skipped due to timeout. (9)
  • GitHub Check: Build Ghost-CLI archive
  • GitHub Check: Build Docker Images
  • GitHub Check: Acceptance tests (Node 22.23.1, mysql8)
  • GitHub Check: Unit tests (Node 22.23.1)
  • GitHub Check: Acceptance tests (Node 22.23.1, better-sqlite3)
  • GitHub Check: Lint
  • GitHub Check: Legacy tests (Node 22.23.1, mysql8)
  • GitHub Check: Legacy tests (Node 22.23.1, better-sqlite3)
  • GitHub Check: Analyze (javascript-typescript)
🧰 Additional context used
📓 Path-based instructions (7)
Review new or changed service boundaries for explicit dependency ownership,

⚙️ CodeRabbit configuration file

Files:

  • ghost/core/core/server/services/newsletters/newsletters-service.js
Review whether tests prove changed behaviour, meaningful error/edge paths, and

⚙️ CodeRabbit configuration file

Files:

  • ghost/core/test/unit/server/services/newsletters/service.test.js
New source files must be TypeScript: flag new JS files as a required change

⚙️ CodeRabbit configuration file

Files:

  • ghost/core/core/server/services/newsletters/newsletters-service.js
  • ghost/core/test/unit/server/services/newsletters/service.test.js
Prioritise concrete correctness, security, data-integrity, compatibility,

⚙️ CodeRabbit configuration file

Files:

  • ghost/core/core/server/services/newsletters/newsletters-service.js
  • ghost/core/test/unit/server/services/newsletters/service.test.js
Boot owns service initialization; do not

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • ghost/core/core/server/services/newsletters/newsletters-service.js
New files are TypeScript: Fail if the PR adds a new .js/.jsx/.cjs/.mjs source file, unless it is: a DB

📄 CodeRabbit inference engine (Custom checks)

Files:

  • ghost/core/core/server/services/newsletters/newsletters-service.js
  • ghost/core/test/unit/server/services/newsletters/service.test.js
Always use `pnpm`, never npm or Yarn.

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • ghost/core/core/server/services/newsletters/newsletters-service.js
  • ghost/core/test/unit/server/services/newsletters/service.test.js
🔇 Additional comments (4)
ghost/core/core/server/services/newsletters/newsletters-service.js (2)

16-22: LGTM!


278-283: LGTM!

ghost/core/test/unit/server/services/newsletters/service.test.js (2)

318-329: LGTM!


331-342: LGTM!


Walkthrough

The newsletter service adds an invalid-token error message and allows token-based updates only for sender_email and sender_reply_to. verifyPropertyUpdate rejects tokens without a newsletter ID or with unsupported properties before editing. Unit tests cover support-address tokens and tokens targeting the name property.

Merge Risk: ⚪ Minimal · up to 13c30

The PR validates newsletter verification token payloads and returns a clean bad-request response instead of a raw 500 for invalid tokens. No actionable merge-blocking risk remains after normal checks.

🚥 Pre-merge checks | ✅ 5 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Type-Safe Boundaries ⚠️ Warning The PR adds a hand-written check for decoded token data instead of a Zod boundary schema. The endpoint receives frame.data.token from HTTP, and SingleUseTokenProvider.validate() parses persisted t… Define a Zod schema for the newsletter verification token payload. Validate the result of getDataFromToken() before destructuring or model access. Include the required non-empty id, the allowed property enum, and the value type requ…
✅ Passed checks (5 passed)
Check name Status Explanation
Description check ✅ Passed The description clearly explains the 500 error, the token payload validation change, and the added tests. It directly matches the changeset.
Title check ✅ Passed The title clearly identifies the main change: preventing a 500 error when newsletter verification receives a non-newsletter token.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
New Files Are Typescript ✅ Passed The pull request adds no files. The exact parent-to-HEAD diff contains only two modified .js files, and both paths existed in the parent revision. The check does not fail for modifications to pre-ex…
Full details: Type-Safe Boundaries

Explanation

The PR adds a hand-written check for decoded token data instead of a Zod boundary schema. The endpoint receives frame.data.token from HTTP, and SingleUseTokenProvider.validate() parses persisted token JSON into an arbitrary object. verifyPropertyUpdate() destructures that object before validation, then only checks truthiness of id and membership of property; value remains unchecked before it is passed to NewsletterModel.edit(). No Zod schema validates the payload first. The changed guard and allowlist introduce this non-Zod boundary validation path. The changed files contain no new any, unchecked as, or TypeScript suppression.

Resolution

Define a Zod schema for the newsletter verification token payload. Validate the result of getDataFromToken() before destructuring or model access. Include the required non-empty id, the allowed property enum, and the value type required by the token producer. Convert schema failures to BadRequestError, and use the schema as the single source for the allowed properties.

Full details: New Files Are Typescript

Explanation

The pull request adds no files. The exact parent-to-HEAD diff contains only two modified .js files, and both paths existed in the parent revision. The check does not fail for modifications to pre-existing JavaScript files.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch slars/newsletter-verification-token-guard

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@codecov

codecov Bot commented Aug 25, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 45.45455% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.44%. Comparing base (b31835a) to head (13c3006).
⚠️ Report is 6 commits behind head on main.

Files with missing lines Patch % Lines
...server/services/newsletters/newsletters-service.js 45.45% 6 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #30281      +/-   ##
==========================================
- Coverage   75.48%   75.44%   -0.05%     
==========================================
  Files        1641     1641              
  Lines      155761   155776      +15     
  Branches    18772    18757      -15     
==========================================
- Hits       117577   117519      -58     
- Misses      37176    37274      +98     
+ Partials     1008      983      -25     
Flag Coverage Δ
e2e-tests 77.10% <45.45%> (-0.05%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant