Skip to content

fix: quote attachments not rendering when client hostname differs from Site_Url#40107

Open
ricardogarim wants to merge 1 commit intodevelopfrom
fix/quote-attachment-url-mismatch
Open

fix: quote attachments not rendering when client hostname differs from Site_Url#40107
ricardogarim wants to merge 1 commit intodevelopfrom
fix/quote-attachment-url-mismatch

Conversation

@ricardogarim
Copy link
Copy Markdown
Member

@ricardogarim ricardogarim commented Apr 9, 2026

Proposed changes

Quote attachments (the quoted message block) were not rendered when the client hostname differed from the server's Site_Url setting (e.g. localhost vs 127.0.0.1, or behind a reverse proxy).

The root cause was a strict url.includes(siteUrl) check in BeforeSaveJumpToMessage that silently dropped the quote URL when hostnames didn't match.

The fix replaces this with getMessageIdFromUrl(), which identifies quote permalinks by the ?msg= query parameter instead. Security is preserved by the existing getMessages + canAccessRoom checks downstream. The typeof check on the query param also prevents NoSQL injection via parameter pollution (?msg[$gt]=).

Issues

Reported here #40078 (comment).

Steps to test or reproduce

  1. Set Site_Url to http://127.0.0.1:3000
  2. Access Rocket.Chat via http://localhost:3000
  3. Send a message in a channel
  4. Click the message menu > Quote (or Reply in DM)
  5. Send the reply
  6. Before fix: the quoted message block does not appear
  7. After fix: the quoted message block renders correctly

Further comments

  • Removed siteUrl from the createAttachmentForMessageURLs config since it's no longer used
  • Removed QueryString import in favor of URL.parse(url, true) which parses query strings directly
  • Added unit test for hostname mismatch scenario and query parameter pollution

Summary by CodeRabbit

  • Bug Fixes
    • Fixed quote attachments failing to render when the client hostname differs from the Site_Url setting.

Task: [CORE-2095]

@dionisio-bot
Copy link
Copy Markdown
Contributor

dionisio-bot bot commented Apr 9, 2026

Looks like this PR is not ready to merge, because of the following issues:

  • This PR is missing the 'stat: QA assured' label
  • This PR is missing the required milestone or project

Please fix the issues and try again

If you have any trouble, please check the PR guidelines

@changeset-bot
Copy link
Copy Markdown

changeset-bot bot commented Apr 9, 2026

🦋 Changeset detected

Latest commit: c24a7d7

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 41 packages
Name Type
@rocket.chat/meteor Patch
@rocket.chat/core-typings Patch
@rocket.chat/rest-typings Patch
@rocket.chat/uikit-playground Patch
@rocket.chat/api-client Patch
@rocket.chat/apps Patch
@rocket.chat/core-services Patch
@rocket.chat/cron Patch
@rocket.chat/ddp-client Patch
@rocket.chat/fuselage-ui-kit Patch
@rocket.chat/gazzodown Patch
@rocket.chat/http-router Patch
@rocket.chat/livechat Patch
@rocket.chat/model-typings Patch
@rocket.chat/ui-avatar Patch
@rocket.chat/ui-client Patch
@rocket.chat/ui-contexts Patch
@rocket.chat/ui-voip Patch
@rocket.chat/web-ui-registration Patch
@rocket.chat/account-service Patch
@rocket.chat/authorization-service Patch
@rocket.chat/ddp-streamer Patch
@rocket.chat/omnichannel-transcript Patch
@rocket.chat/presence-service Patch
@rocket.chat/queue-worker Patch
@rocket.chat/abac Patch
@rocket.chat/federation-matrix Patch
@rocket.chat/license Patch
@rocket.chat/media-calls Patch
@rocket.chat/omnichannel-services Patch
@rocket.chat/pdf-worker Patch
@rocket.chat/presence Patch
rocketchat-services Patch
@rocket.chat/models Patch
@rocket.chat/network-broker Patch
@rocket.chat/omni-core-ee Patch
@rocket.chat/mock-providers Patch
@rocket.chat/ui-video-conf Patch
@rocket.chat/instance-status Patch
@rocket.chat/omni-core Patch
@rocket.chat/server-fetch Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 9, 2026

Walkthrough

This change fixes quote attachment rendering when clients access Rocket.Chat via a hostname different from the configured Site_Url setting. The solution replaces hostname-based URL matching with query parameter detection (checking for the msg parameter), removes the redundant siteUrl configuration, and adds test coverage for hostname mismatch scenarios.

Changes

Cohort / File(s) Summary
Changeset Documentation
.changeset/shy-pillows-repair.md
Marks a patch release documenting the fix for quote attachments failing to render on hostname mismatches.
Core Implementation
apps/meteor/server/services/messages/hooks/BeforeSaveJumpToMessage.ts, apps/meteor/server/services/messages/service.ts
Replaces siteUrl-based URL filtering with a new getMessageIdFromUrl() helper that extracts the msg query parameter. Removes siteUrl from the config object passed to createAttachmentForMessageURLs(). Updated logic iterates all message URLs and extracts msgId directly from query parameters, eliminating hostname-dependent filtering.
Unit Tests
apps/meteor/tests/unit/server/services/messages/hooks/BeforeSaveJumpToMessage.tests.ts
Removed siteUrl from test configuration objects. Added new test validating quote attachment creation when client hostname differs from server hostname (e.g., localhost vs 127.0.0.1). Updated test descriptions to focus on msg query parameter presence/absence instead of hostname matching. Adjusted test fixtures for query parameter pollution scenarios.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR successfully addresses all objectives from CORE-2094: detects quote permalinks by ?msg= query parameter instead of hostname, preserves security checks, removes unused siteUrl config, and adds unit tests for hostname mismatch and parameter pollution scenarios.
Out of Scope Changes check ✅ Passed All changes directly address the linked issue objectives: URL detection logic, config parameter removal, service configuration update, and targeted test modifications with no extraneous alterations.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title accurately describes the main fix: quote attachments not rendering when client hostname differs from Site_Url, which is the core issue being addressed.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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 and usage tips.

@ricardogarim ricardogarim added this to the 8.4.0 milestone Apr 9, 2026
@ricardogarim
Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 9, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@ricardogarim
Copy link
Copy Markdown
Member Author

/jira CORE-2094

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
apps/meteor/server/services/messages/hooks/BeforeSaveJumpToMessage.ts (2)

98-106: Skip message lookup when no URL contains a valid msg parameter.

At Line 106, getMessages is still called when linkedMessages is empty. An early return avoids unnecessary data access.

♻️ Suggested optimization
 		const linkedMessages: { msgId: string; urlItem: MessageUrl }[] = [];
 		for (const urlItem of message.urls) {
 			const msgId = getMessageIdFromUrl(urlItem.url);
 			if (msgId) {
 				linkedMessages.push({ msgId, urlItem });
 			}
 		}
+
+		if (linkedMessages.length === 0) {
+			return message;
+		}
 
 		const msgs = await this.getMessages(linkedMessages.map((linkedMsg) => linkedMsg.msgId));
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/meteor/server/services/messages/hooks/BeforeSaveJumpToMessage.ts` around
lines 98 - 106, The code always calls this.getMessages even when no URLs yielded
a msgId; change the flow in BeforeSaveJumpToMessage.ts to check
linkedMessages.length and return early (or skip the lookup) when linkedMessages
is empty to avoid unnecessary DB access—locate the block that builds
linkedMessages using getMessageIdFromUrl over message.urls and guard the
subsequent call to this.getMessages(linkedMessages.map(...)) so it only runs
when linkedMessages.length > 0 (or return immediately).

142-143: Remove inline implementation comment to match repository guideline.

The added comment is clear, but this file now diverges from the no-comments-in-implementation rule.

🧹 Suggested cleanup
-			// prevent OEmbed from also fetching this URL for a link preview
 			urlItem.ignoreParse = true;
As per coding guidelines, "Avoid code comments in the implementation."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/meteor/server/services/messages/hooks/BeforeSaveJumpToMessage.ts` around
lines 142 - 143, Remove the inline implementation comment placed immediately
above the assignment to urlItem.ignoreParse (the line "urlItem.ignoreParse =
true;"): delete the comment line so only the statement remains, keeping the code
consistent with the repository guideline to avoid comments inside implementation
blocks; no code behavior changes needed.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@apps/meteor/server/services/messages/hooks/BeforeSaveJumpToMessage.ts`:
- Around line 98-106: The code always calls this.getMessages even when no URLs
yielded a msgId; change the flow in BeforeSaveJumpToMessage.ts to check
linkedMessages.length and return early (or skip the lookup) when linkedMessages
is empty to avoid unnecessary DB access—locate the block that builds
linkedMessages using getMessageIdFromUrl over message.urls and guard the
subsequent call to this.getMessages(linkedMessages.map(...)) so it only runs
when linkedMessages.length > 0 (or return immediately).
- Around line 142-143: Remove the inline implementation comment placed
immediately above the assignment to urlItem.ignoreParse (the line
"urlItem.ignoreParse = true;"): delete the comment line so only the statement
remains, keeping the code consistent with the repository guideline to avoid
comments inside implementation blocks; no code behavior changes needed.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 41b3d2e6-3f15-4801-b807-478462dc6741

📥 Commits

Reviewing files that changed from the base of the PR and between cd79677 and c24a7d7.

📒 Files selected for processing (4)
  • .changeset/shy-pillows-repair.md
  • apps/meteor/server/services/messages/hooks/BeforeSaveJumpToMessage.ts
  • apps/meteor/server/services/messages/service.ts
  • apps/meteor/tests/unit/server/services/messages/hooks/BeforeSaveJumpToMessage.tests.ts
💤 Files with no reviewable changes (1)
  • apps/meteor/server/services/messages/service.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: 🔎 Code Check / TypeScript
  • GitHub Check: 🔨 Test Storybook / Test Storybook
  • GitHub Check: 🔨 Test Unit / Unit Tests
  • GitHub Check: 🔎 Code Check / Code Lint
  • GitHub Check: 📦 Meteor Build (coverage)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation

Files:

  • apps/meteor/server/services/messages/hooks/BeforeSaveJumpToMessage.ts
  • apps/meteor/tests/unit/server/services/messages/hooks/BeforeSaveJumpToMessage.tests.ts
🧠 Learnings (22)
📓 Common learnings
Learnt from: ggazzo
Repo: RocketChat/Rocket.Chat PR: 35995
File: apps/meteor/app/api/server/v1/rooms.ts:1107-1112
Timestamp: 2026-02-23T17:53:18.785Z
Learning: In Rocket.Chat PR reviews, maintain strict scope boundaries—when a PR is focused on a specific endpoint (e.g., rooms.favorite), avoid reviewing or suggesting changes to other endpoints that were incidentally refactored (e.g., rooms.invite) unless explicitly requested by maintainers.
Learnt from: smirk-dev
Repo: RocketChat/Rocket.Chat PR: 39625
File: apps/meteor/app/api/server/v1/push.ts:85-97
Timestamp: 2026-03-14T14:58:58.834Z
Learning: In RocketChat/Rocket.Chat, the `push.token` POST/DELETE endpoints in `apps/meteor/app/api/server/v1/push.ts` were already migrated to the chained router API pattern on `develop` prior to PR `#39625`. `cleanTokenResult` (which strips `authToken` and returns `PushTokenResult`) and `isPushTokenPOSTProps`/`isPushTokenDELETEProps` validators already exist on `develop`. PR `#39625` only migrates `push.get` and `push.info` to the chained pattern. Do not flag `cleanTokenResult` or `PushTokenResult` as newly introduced behavior-breaking changes when reviewing this PR.
Learnt from: dougfabris
Repo: RocketChat/Rocket.Chat PR: 39425
File: apps/meteor/app/api/server/v1/rooms.ts:294-296
Timestamp: 2026-03-11T18:15:53.272Z
Learning: In Rocket.Chat's `rooms.mediaConfirm/:rid/:fileId` endpoint (apps/meteor/app/api/server/v1/rooms.ts), updating `file.name` from `bodyParams.fileName` without updating `file.path` is intentionally safe. The file path is keyed by `_id` (not by filename), so the stored path remains valid regardless of a rename. `file.name` only affects the display name in the message attachment; do not flag this as a path-divergence issue.
Learnt from: ahmed-n-abdeltwab
Repo: RocketChat/Rocket.Chat PR: 38974
File: apps/meteor/app/api/server/v1/im.ts:220-221
Timestamp: 2026-02-24T19:09:09.561Z
Learning: In RocketChat/Rocket.Chat OpenAPI migration PRs for apps/meteor/app/api/server/v1 endpoints, maintainers prefer to avoid any logic changes; style-only cleanups (like removing inline comments) may be deferred to follow-ups to keep scope tight.
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 38493
File: apps/meteor/tests/e2e/page-objects/fragments/home-content.ts:60-82
Timestamp: 2026-02-24T19:36:55.089Z
Learning: In RocketChat/Rocket.Chat e2e tests (apps/meteor/tests/e2e/page-objects/fragments/home-content.ts), thread message preview listitems do not have aria-roledescription="message", so lastThreadMessagePreview locator cannot be scoped to messageListItems (which filters for aria-roledescription="message"). It should remain scoped to page.getByRole('listitem') or mainMessageList.getByRole('listitem').
📚 Learning: 2026-02-24T19:09:09.561Z
Learnt from: ahmed-n-abdeltwab
Repo: RocketChat/Rocket.Chat PR: 38974
File: apps/meteor/app/api/server/v1/im.ts:220-221
Timestamp: 2026-02-24T19:09:09.561Z
Learning: In RocketChat/Rocket.Chat OpenAPI migration PRs for apps/meteor/app/api/server/v1 endpoints, maintainers prefer to avoid any logic changes; style-only cleanups (like removing inline comments) may be deferred to follow-ups to keep scope tight.

Applied to files:

  • .changeset/shy-pillows-repair.md
📚 Learning: 2026-03-11T18:15:53.272Z
Learnt from: dougfabris
Repo: RocketChat/Rocket.Chat PR: 39425
File: apps/meteor/app/api/server/v1/rooms.ts:294-296
Timestamp: 2026-03-11T18:15:53.272Z
Learning: In Rocket.Chat's `rooms.mediaConfirm/:rid/:fileId` endpoint (apps/meteor/app/api/server/v1/rooms.ts), updating `file.name` from `bodyParams.fileName` without updating `file.path` is intentionally safe. The file path is keyed by `_id` (not by filename), so the stored path remains valid regardless of a rename. `file.name` only affects the display name in the message attachment; do not flag this as a path-divergence issue.

Applied to files:

  • .changeset/shy-pillows-repair.md
  • apps/meteor/server/services/messages/hooks/BeforeSaveJumpToMessage.ts
📚 Learning: 2026-03-16T21:50:37.589Z
Learnt from: amitb0ra
Repo: RocketChat/Rocket.Chat PR: 39676
File: .changeset/migrate-users-register-openapi.md:3-3
Timestamp: 2026-03-16T21:50:37.589Z
Learning: For changes related to OpenAPI migrations in Rocket.Chat/OpenAPI, when removing endpoint types and validators from rocket.chat/rest-typings (e.g., UserRegisterParamsPOST, /v1/users.register) document this as a minor changeset (not breaking) per RocketChat/Rocket.Chat-Open-API#150 Rule 7. Note that the endpoint type is re-exposed via a module augmentation .d.ts in the consuming package (e.g., packages/web-ui-registration/src/users-register.d.ts). In reviews, ensure the changeset clearly states: this is a non-breaking change, the major version should not be bumped, and the changeset reflects a minor version bump. Do not treat this as a breaking change during OpenAPI migrations.

Applied to files:

  • .changeset/shy-pillows-repair.md
📚 Learning: 2026-03-11T22:04:20.529Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 39545
File: apps/meteor/client/views/room/body/hooks/useHasNewMessages.ts:59-61
Timestamp: 2026-03-11T22:04:20.529Z
Learning: In `apps/meteor/client/views/room/body/hooks/useHasNewMessages.ts`, the `msg.u._id === uid` early-return in the `streamNewMessage` handler is intentional: the "New messages" indicator is designed to notify about messages from other users only. Self-sent messages — including those sent from a different session/device — are always skipped, by design. Do not flag this as a multi-session regression.

Applied to files:

  • apps/meteor/server/services/messages/hooks/BeforeSaveJumpToMessage.ts
  • apps/meteor/tests/unit/server/services/messages/hooks/BeforeSaveJumpToMessage.tests.ts
📚 Learning: 2026-03-11T16:46:55.955Z
Learnt from: ricardogarim
Repo: RocketChat/Rocket.Chat PR: 39535
File: apps/meteor/app/apps/server/bridges/livechat.ts:249-249
Timestamp: 2026-03-11T16:46:55.955Z
Learning: In `apps/meteor/app/apps/server/bridges/livechat.ts`, `createVisitor()` intentionally does not propagate `externalIds` to `registerData`. This is by design: the method is deprecated (JSDoc: `deprecated Use createAndReturnVisitor instead. Note: This method does not support externalIds.`) to push callers toward `createAndReturnVisitor()`, which does support `externalIds`. Do not flag the missing `externalIds` field in `createVisitor()` as a bug.

Applied to files:

  • apps/meteor/server/services/messages/hooks/BeforeSaveJumpToMessage.ts
📚 Learning: 2026-03-14T14:58:58.834Z
Learnt from: smirk-dev
Repo: RocketChat/Rocket.Chat PR: 39625
File: apps/meteor/app/api/server/v1/push.ts:85-97
Timestamp: 2026-03-14T14:58:58.834Z
Learning: In RocketChat/Rocket.Chat, the `push.token` POST/DELETE endpoints in `apps/meteor/app/api/server/v1/push.ts` were already migrated to the chained router API pattern on `develop` prior to PR `#39625`. `cleanTokenResult` (which strips `authToken` and returns `PushTokenResult`) and `isPushTokenPOSTProps`/`isPushTokenDELETEProps` validators already exist on `develop`. PR `#39625` only migrates `push.get` and `push.info` to the chained pattern. Do not flag `cleanTokenResult` or `PushTokenResult` as newly introduced behavior-breaking changes when reviewing this PR.

Applied to files:

  • apps/meteor/server/services/messages/hooks/BeforeSaveJumpToMessage.ts
📚 Learning: 2026-02-24T19:36:55.089Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 38493
File: apps/meteor/tests/e2e/page-objects/fragments/home-content.ts:60-82
Timestamp: 2026-02-24T19:36:55.089Z
Learning: In RocketChat/Rocket.Chat e2e tests (apps/meteor/tests/e2e/page-objects/fragments/home-content.ts), thread message preview listitems do not have aria-roledescription="message", so lastThreadMessagePreview locator cannot be scoped to messageListItems (which filters for aria-roledescription="message"). It should remain scoped to page.getByRole('listitem') or mainMessageList.getByRole('listitem').

Applied to files:

  • apps/meteor/server/services/messages/hooks/BeforeSaveJumpToMessage.ts
  • apps/meteor/tests/unit/server/services/messages/hooks/BeforeSaveJumpToMessage.tests.ts
📚 Learning: 2026-01-17T01:51:47.764Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 38219
File: packages/core-typings/src/cloud/Announcement.ts:5-6
Timestamp: 2026-01-17T01:51:47.764Z
Learning: In packages/core-typings/src/cloud/Announcement.ts, the AnnouncementSchema.createdBy field intentionally overrides IBannerSchema.createdBy (object with _id and optional username) with a string enum ['cloud', 'system'] to match existing runtime behavior. This is documented as technical debt with a FIXME comment at apps/meteor/app/cloud/server/functions/syncWorkspace/handleCommsSync.ts:53 and should not be flagged as an error until the runtime behavior is corrected.

Applied to files:

  • apps/meteor/server/services/messages/hooks/BeforeSaveJumpToMessage.ts
📚 Learning: 2026-03-11T18:17:53.972Z
Learnt from: dougfabris
Repo: RocketChat/Rocket.Chat PR: 39425
File: apps/meteor/client/lib/chats/flows/processMessageUploads.ts:112-119
Timestamp: 2026-03-11T18:17:53.972Z
Learning: In `apps/meteor/client/lib/chats/flows/processMessageUploads.ts`, when sending multiple file uploads, each file is confirmed via its own `/rooms.mediaConfirm/${rid}/${fileId}` call and produces a separate message. Only the first file's confirm payload carries the composed message text (`msg`); all subsequent files receive `msg: ''`. This one-message-per-file behavior is intentional by design — do not flag it as a bug or suggest batching into a single message.

Applied to files:

  • apps/meteor/server/services/messages/hooks/BeforeSaveJumpToMessage.ts
  • apps/meteor/tests/unit/server/services/messages/hooks/BeforeSaveJumpToMessage.tests.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In the Rocket.Chat repository, do not reference Biome lint rules in code review feedback. Biome is not used even if biome.json exists; only reference Biome rules if there is explicit, project-wide usage documented. For TypeScript files, review lint implications without Biome guidance unless the project enables Biome rules.

Applied to files:

  • apps/meteor/server/services/messages/hooks/BeforeSaveJumpToMessage.ts
  • apps/meteor/tests/unit/server/services/messages/hooks/BeforeSaveJumpToMessage.tests.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In this repository (RocketChat/Rocket.Chat), Biome lint rules are not used even if a biome.json exists. When reviewing TypeScript files (e.g., packages/ui-voip/src/providers/useMediaSession.ts), ensure lint suggestions do not reference Biome-specific rules. Rely on general ESLint/TypeScript lint rules and project conventions instead.

Applied to files:

  • apps/meteor/server/services/messages/hooks/BeforeSaveJumpToMessage.ts
  • apps/meteor/tests/unit/server/services/messages/hooks/BeforeSaveJumpToMessage.tests.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Ensure tests run reliably in parallel without shared state conflicts

Applied to files:

  • apps/meteor/tests/unit/server/services/messages/hooks/BeforeSaveJumpToMessage.tests.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Utilize Playwright fixtures (`test`, `page`, `expect`) for consistency in test files

Applied to files:

  • apps/meteor/tests/unit/server/services/messages/hooks/BeforeSaveJumpToMessage.tests.ts
📚 Learning: 2026-03-16T11:57:17.987Z
Learnt from: ricardogarim
Repo: RocketChat/Rocket.Chat PR: 39657
File: apps/meteor/tests/end-to-end/apps/app-resolve-visitor.ts:43-45
Timestamp: 2026-03-16T11:57:17.987Z
Learning: In `apps/meteor/tests/end-to-end/apps/app-resolve-visitor.ts`, `externalIds` lookups are namespaced per `app.id`. Because `cleanupApps()` is called before each test run and a fresh app is installed (giving a new unique `app.id`), fixed `userId` strings like `'nonexistent-id'` in null-path tests are safe and cannot collide with stale visitor records from previous runs. Do not flag these as needing unique/random values.

Applied to files:

  • apps/meteor/tests/unit/server/services/messages/hooks/BeforeSaveJumpToMessage.tests.ts
📚 Learning: 2025-12-10T21:00:54.909Z
Learnt from: KevLehman
Repo: RocketChat/Rocket.Chat PR: 37091
File: ee/packages/abac/jest.config.ts:4-7
Timestamp: 2025-12-10T21:00:54.909Z
Learning: Rocket.Chat monorepo: Jest testMatch pattern '<rootDir>/src/**/*.spec.(ts|js|mjs)' is valid in this repo and used across multiple packages (e.g., packages/tools, ee/packages/omnichannel-services). Do not flag it as invalid in future reviews.

Applied to files:

  • apps/meteor/tests/unit/server/services/messages/hooks/BeforeSaveJumpToMessage.tests.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Use `test.beforeAll()` and `test.afterAll()` for setup/teardown in Playwright tests

Applied to files:

  • apps/meteor/tests/unit/server/services/messages/hooks/BeforeSaveJumpToMessage.tests.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Maintain test isolation between test cases in Playwright tests

Applied to files:

  • apps/meteor/tests/unit/server/services/messages/hooks/BeforeSaveJumpToMessage.tests.ts
📚 Learning: 2026-03-06T18:02:20.381Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 39397
File: packages/gazzodown/src/elements/Timestamp/RelativeTime.spec.tsx:63-70
Timestamp: 2026-03-06T18:02:20.381Z
Learning: In RocketChat/Rocket.Chat, tests in the `packages/gazzodown` package (and likely the broader test suite) are always expected to run in the UTC timezone. This makes `toLocaleString()` output deterministic, so snapshot tests that include locale/timezone-sensitive content (such as `title` attributes from `toLocaleString()`) are stable and do not need to be replaced with targeted assertions.

Applied to files:

  • apps/meteor/tests/unit/server/services/messages/hooks/BeforeSaveJumpToMessage.tests.ts
📚 Learning: 2026-03-06T18:09:17.867Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 39397
File: packages/gazzodown/src/elements/Timestamp/DateTimeFormats.spec.tsx:20-23
Timestamp: 2026-03-06T18:09:17.867Z
Learning: In the RocketChat/Rocket.Chat gazzodown package (`packages/gazzodown`), tests are intended to run under the UTC timezone, but as of PR `#39397` this is NOT yet explicitly enforced in `jest.config.ts` or the `package.json` test scripts (which just run `jest` without `TZ=UTC`). To make timezone-sensitive snapshot tests reliable across all environments, `TZ=UTC` should be added to the test scripts in `package.json` or to `jest.config.ts` via `testEnvironmentOptions.timezone`. Without explicit UTC enforcement, snapshot tests involving date-fns formatted output or `toLocaleString()` will fail for contributors in non-UTC timezones.

Applied to files:

  • apps/meteor/tests/unit/server/services/messages/hooks/BeforeSaveJumpToMessage.tests.ts
📚 Learning: 2025-11-04T16:49:19.107Z
Learnt from: ricardogarim
Repo: RocketChat/Rocket.Chat PR: 37377
File: apps/meteor/ee/server/hooks/federation/index.ts:86-88
Timestamp: 2025-11-04T16:49:19.107Z
Learning: In Rocket.Chat's federation system (apps/meteor/ee/server/hooks/federation/), permission checks follow two distinct patterns: (1) User-initiated federation actions (creating rooms, adding users to federated rooms, joining from invites) should throw MeteorError to inform users they lack 'access-federation' permission. (2) Remote server-initiated federation events should silently skip/ignore when users lack permission. The beforeAddUserToRoom hook only executes for local user-initiated actions, so throwing an error there is correct. Remote federation events are handled separately by the federation Matrix package with silent skipping logic.

Applied to files:

  • apps/meteor/tests/unit/server/services/messages/hooks/BeforeSaveJumpToMessage.tests.ts
📚 Learning: 2025-10-28T16:53:42.761Z
Learnt from: ricardogarim
Repo: RocketChat/Rocket.Chat PR: 37205
File: ee/packages/federation-matrix/src/FederationMatrix.ts:296-301
Timestamp: 2025-10-28T16:53:42.761Z
Learning: In the Rocket.Chat federation-matrix integration (ee/packages/federation-matrix/), the createRoom method from rocket.chat/federation-sdk will support a 4-argument signature (userId, roomName, visibility, displayName) in newer versions. Code using this 4-argument call is forward-compatible with planned library updates and should not be flagged as an error.

Applied to files:

  • apps/meteor/tests/unit/server/services/messages/hooks/BeforeSaveJumpToMessage.tests.ts
🔇 Additional comments (5)
.changeset/shy-pillows-repair.md (1)

1-5: Changeset entry matches the bugfix scope.

Patch bump and description are consistent with the behavior change introduced in this PR.

apps/meteor/tests/unit/server/services/messages/hooks/BeforeSaveJumpToMessage.tests.ts (3)

64-64: Config updates are consistent with the new hook signature.

All updated calls now pass only chainLimit and useRealName, keeping tests aligned with the createAttachmentForMessageURLs contract change.

Also applies to: 88-88, 113-113, 138-138, 163-163, 198-198, 223-223, 248-248, 282-282, 323-323, 351-351, 377-377, 559-559, 597-597


120-143: Security regression coverage for query-parameter pollution looks solid.

The msg[$gt]= case correctly validates that polluted query payloads do not create quote attachments.


145-178: Hostname-mismatch test directly covers the reported bug path.

Good assertion set for ignoreParse: true and quote creation when permalink host differs from server host.

apps/meteor/server/services/messages/hooks/BeforeSaveJumpToMessage.ts (1)

8-11: msg extraction guard is correctly constrained to string values.

This safely ignores non-string query payloads and keeps quote detection tied to canonical ?msg= values.

@ricardogarim ricardogarim marked this pull request as ready for review April 9, 2026 23:40
@ricardogarim ricardogarim requested a review from a team as a code owner April 9, 2026 23:40
@codecov
Copy link
Copy Markdown

codecov bot commented Apr 9, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 70.14%. Comparing base (a6c863a) to head (c24a7d7).
⚠️ Report is 12 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop   #40107      +/-   ##
===========================================
- Coverage    70.19%   70.14%   -0.06%     
===========================================
  Files         3273     3278       +5     
  Lines       116304   116624     +320     
  Branches     20602    20682      +80     
===========================================
+ Hits         81645    81803     +158     
- Misses       31379    31533     +154     
- Partials      3280     3288       +8     
Flag Coverage Δ
e2e 59.69% <ø> (-0.04%) ⬇️
e2e-api 46.59% <100.00%> (-0.09%) ⬇️
unit 70.95% <100.00%> (-0.07%) ⬇️

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

🚀 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.

Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 4 files

@nazabucciarelli
Copy link
Copy Markdown
Contributor

the PR's title should explain what's being fixed, not how (reference: https://developer.rocket.chat/docs/pull-requests-tags)

@nazabucciarelli
Copy link
Copy Markdown
Contributor

nazabucciarelli commented Apr 10, 2026

My only concern is that this was worked as a feature some time ago: #30011

And a (weird) edge case for this solution will cause adding quotes to the message if for any reason we send a link with the msg parameter that casually matches a msg ID in the db (very unfortunate case):

image

This could render external links as if they were Rocket Chat quotes

@ricardogarim ricardogarim changed the title fix: detect quote permalinks by query param instead of hostname fix: quote attachments not rendering when client hostname differs from Site_Url Apr 12, 2026
@ricardogarim
Copy link
Copy Markdown
Member Author

Fair. Regarding the edge case: for an external URL to be rendered as a quote, its ?msg= value would need to exactly match our random alphanumeric Rocket.Chat message ID in the database, and the user would also need access to the room containing that message. The probability of this happening accidentally is effectively zero.

That said, I see a few options:

  1. Relax the check by validating the pathname pattern - instead of matching the full hostname, verify that the URL path follows a known Rocket.Chat route (/channel/, /group/, /direct/, etc.), which we control. This would reject clearly external URLs while still working across hostname mismatches.
  2. Introduce a domain allowlist - though this feels like overkill for what we’re solving here.
  3. Keep the current Site_Url check and accept the limitation - users behind a proxy or accessing via a different hostname than Site_Url simply won’t get quote rendering, since Site_Url is the canonical source of truth.

WDYT? I’ll also bring this to the team for review, since this was a quick 5-minute fix picked up from another PR that hasn’t been discussed yet.

@alfredodelfabro alfredodelfabro removed this from the 8.4.0 milestone Apr 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants