Skip to content

Conversation

@rodrigok
Copy link
Member

@rodrigok rodrigok commented Oct 15, 2025

https://rocketchat.atlassian.net/browse/FDR-232

Proposed changes (including videos or screenshots)

Issue(s)

Steps to test or reproduce

Further comments

Summary by CodeRabbit

  • Bug Fixes

    • Improved invite handling when joining/accepting federated rooms to reduce join failures and edge cases.
    • More consistent invite behavior across federated rooms.
  • New Features

    • Federation messages now preserve the original server timestamp so remote messages, quotes, and edits display their original time.
  • Chores

    • Updated federation-related library to a newer release for upstream fixes and stability.

Copilot AI review requested due to automatic review settings October 15, 2025 23:44
@dionisio-bot
Copy link
Contributor

dionisio-bot bot commented Oct 15, 2025

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

  • 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

changeset-bot bot commented Oct 15, 2025

⚠️ No Changeset found

Latest commit: 6c5dd1a

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

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

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

Fix updates federation invite handling so local users can be added to remote rooms by adjusting how joinUser is invoked.

  • Updated joinUser calls to pass the full inviteEvent instead of only the roomId.
  • Consistent change applied in joinRoom flow and acceptInvite handler.

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 15, 2025

Walkthrough

Updated two calls to joinUser in ee/packages/federation-matrix/src/api/_matrix/invite.ts to pass the full inviteEvent object (plus state_key) instead of inviteEvent.roomId. Also bumped @rocket.chat/federation-sdk from 0.1.29 to 0.1.31 in two package.json files.

Changes

Cohort / File(s) Summary
Federation invite handling
ee/packages/federation-matrix/src/api/_matrix/invite.ts
Replaced room.joinUser(inviteEvent.roomId, inviteEvent.event.state_key) with room.joinUser(inviteEvent, inviteEvent.event.state_key) in joinRoom and acceptInvite. No other logic changes.
Message timestamp plumbing
apps/meteor/server/services/messages/service.ts, ee/packages/federation-matrix/src/events/message.ts, packages/core-services/src/types/IMessageService.ts
Added ts: Date parameter to sendMessage / saveMessageFromFederation signatures and threaded ts through federation message saves (origin_server_ts → new Date(...)) into save calls and result objects.
Dependency bumps
ee/packages/federation-matrix/package.json, packages/core-services/package.json
Bumped @rocket.chat/federation-sdk from 0.1.29 to 0.1.31.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor RemoteServer
  participant InviteHandler as invite.ts
  participant RoomService as room.joinUser

  RemoteServer->>InviteHandler: incoming inviteEvent
  InviteHandler->>RoomService: joinUser(inviteEvent, inviteEvent.event.state_key)
  Note right of RoomService: Previously called with roomId\nNow receives full inviteEvent
  RoomService-->>InviteHandler: join result
  InviteHandler-->>RemoteServer: response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

stat: ready to merge

Suggested reviewers

  • debdutdeb
  • sampaiodiego

Poem

I hopped through code with nimble feet,
Carried invites so joins could meet.
Timestamp tucked in every thread,
A federated dance—softly led. 🥕🐇

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The PR title "fix(federation): can't add local users to remote rooms" directly relates to the main objective of fixing the federation issue (FDR-232) where external owners cannot add same-homeserver users to federated rooms. The title clearly summarizes the problem being addressed, though it doesn't capture all aspects of the changeset such as timestamp propagation enhancements and dependency updates. For a complex federation fix, the title appropriately highlights the core issue being resolved without requiring exhaustive detail.
Linked Issues Check ✅ Passed The code changes appear to address the FDR-232 objectives: the modifications to invite.ts passing the full inviteEvent object instead of just roomId directly relate to fixing invite/user-addition handling in federation contexts FDR-232, the @rocket.chat/federation-sdk version bump (0.1.29 to 0.1.31) likely contains the underlying federation fixes, and the timestamp field additions to MessageService and related federation message handling ensure proper message timestamp propagation across federated rooms FDR-232. These changes collectively support enabling external owners to successfully add same-homeserver users to federated rooms by improving invitation context and message timestamp handling.
Out of Scope Changes Check ✅ Passed All changes in this PR are directly related to fixing the federation issue described in FDR-232. The invite.ts modifications address core invitation handling, the federation-sdk dependency update provides the underlying fixes, and the MessageService timestamp enhancements ensure proper message propagation in federation scenarios. No tangential features, unrelated bug fixes, or random code refactoring are present that would fall outside the scope of fixing the federation user-addition issue.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/federation-add-loca-user-to-remote-rooms

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.

sampaiodiego
sampaiodiego previously approved these changes Oct 16, 2025
@sampaiodiego sampaiodiego added the stat: QA assured Means it has been tested and approved by a company insider label Oct 16, 2025
@codecov
Copy link

codecov bot commented Oct 16, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
⚠️ Please upload report for BASE (release-7.11.0@9896fc4). Learn more about missing BASE report.

Additional details and impacted files

Impacted file tree graph

@@                Coverage Diff                @@
##             release-7.11.0   #37246   +/-   ##
=================================================
  Coverage                  ?   66.37%           
=================================================
  Files                     ?     3386           
  Lines                     ?   115628           
  Branches                  ?    21360           
=================================================
  Hits                      ?    76745           
  Misses                    ?    36270           
  Partials                  ?     2613           
Flag Coverage Δ
e2e 57.26% <ø> (?)
unit 71.24% <ø> (?)

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.

@ggazzo ggazzo requested a review from a team as a code owner October 16, 2025 10:21
ggazzo
ggazzo previously approved these changes Oct 16, 2025
Copy link
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.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Jira integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between c60db83 and 3d6816d.

📒 Files selected for processing (3)
  • apps/meteor/server/services/messages/service.ts (2 hunks)
  • ee/packages/federation-matrix/src/events/message.ts (5 hunks)
  • packages/core-services/src/types/IMessageService.ts (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
apps/meteor/server/services/messages/service.ts (2)
packages/core-typings/src/IMessage/IMessage.ts (1)
  • IMessage (138-239)
apps/meteor/app/lib/server/methods/sendMessage.ts (1)
  • executeSendMessage (22-109)
⏰ 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). (3)
  • GitHub Check: 📦 Build Packages
  • GitHub Check: CodeQL-Build
  • GitHub Check: CodeQL-Build
🔇 Additional comments (2)
packages/core-services/src/types/IMessageService.ts (1)

12-37: LGTM!

The addition of the ts: Date parameter to saveMessageFromFederation correctly extends the API to accept timestamp information for federation messages. This aligns with the IMessage interface where ts is a required field (see packages/core-typings/src/IMessage/IMessage.ts line 142).

apps/meteor/server/services/messages/service.ts (1)

88-131: LGTM with timestamp validation caveat.

The implementation correctly threads the ts parameter through to executeSendMessage and matches the IMessageService interface definition. However, note the timestamp validation concern raised in the review of ee/packages/federation-matrix/src/events/message.ts regarding executeSendMessage's 60-second sync validation potentially rejecting legitimate federation messages with older timestamps.

msg: formatted,
federation_event_id: data.event_id,
thread,
ts: new Date(data.origin_server_ts),
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Add validation for origin_server_ts before Date conversion.

If data.origin_server_ts is undefined or not a valid number, new Date(data.origin_server_ts) will create an Invalid Date, which could cause issues in downstream validation or database operations.

Apply this pattern to validate the timestamp before conversion:

+	const timestamp = typeof data.origin_server_ts === 'number' 
+		? new Date(data.origin_server_ts)
+		: new Date();
+
 	await Message.saveMessageFromFederation({
 		fromId: user._id,
 		rid: room._id,
 		msg: formatted,
 		federation_event_id: data.event_id,
 		thread,
-		ts: new Date(data.origin_server_ts),
+		ts: timestamp,
 	});

Apply this pattern to all 5 locations where ts: new Date(data.origin_server_ts) is used (lines 227, 245, 259, 362, 376).

Also applies to: 245-245, 259-259, 362-362, 376-376

🤖 Prompt for AI Agents
In ee/packages/federation-matrix/src/events/message.ts around lines 227, 245,
259, 362, and 376, the code constructs dates using new
Date(data.origin_server_ts) without validating the timestamp; change each
occurrence to first coerce and validate the timestamp (e.g. const tsVal =
Number(data.origin_server_ts); if (!Number.isFinite(tsVal)) handle invalid case)
and then use new Date(tsVal) only when valid, otherwise set ts to null/undefined
or throw an explicit error depending on caller expectations; apply this exact
validation pattern to all five locations so Invalid Date values are never
produced.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Verify timestamp validation doesn't reject legitimate federation messages.

The origin_server_ts is converted to a Date and passed to executeSendMessage, which validates timestamps and throws an error if they're more than 60 seconds out of sync with the current time (see apps/meteor/app/lib/server/methods/sendMessage.ts lines 33-40). Federation messages during catchup, replay, or network delays may legitimately have timestamps older than 60 seconds, potentially causing a 500 Internal Server Error.

Consider whether federation messages should bypass or have relaxed timestamp validation, especially given the PR objective to fix "can't add local users to remote rooms" with 500 errors.

Run the following script to check how timestamp validation errors are handled in federation flows:

Also applies to: 245-245, 259-259, 362-362, 376-376


🏁 Script executed:

#!/bin/bash
# Description: Search for error handling around executeSendMessage in federation code

# Check how federation message saves handle timestamp validation errors
rg -n -A 10 -B 3 'saveMessageFromFederation|executeSendMessage' --type ts -g '*federation*'

# Look for error-message-ts-out-of-sync handling
rg -n -A 5 'error-message-ts-out-of-sync' --type ts

Length of output: 543


Relax timestamp validation for federation messages
The executeSendMessage method (apps/meteor/app/lib/server/methods/sendMessage.ts:38) throws a 500 error when origin_server_ts is > 60 s behind the server clock (“error-message-ts-out-of-sync”), blocking federation catch-up and causing the 500s seen in “can’t add local users to remote rooms.” Bypass or widen this check for federation imports.

@ggazzo ggazzo merged commit 9ce795e into release-7.11.0 Oct 16, 2025
8 of 9 checks passed
@ggazzo ggazzo deleted the fix/federation-add-loca-user-to-remote-rooms branch October 16, 2025 10:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

stat: QA assured Means it has been tested and approved by a company insider

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants