Skip to content

Conversation

@ggazzo
Copy link
Member

@ggazzo ggazzo commented Sep 26, 2025

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

Proposed changes (including videos or screenshots)

Issue(s)

Steps to test or reproduce

Further comments

Summary by CodeRabbit

  • New Features

    • Added an authenticated API endpoint to bulk-verify Matrix IDs, returning a per-ID verification status.
  • Improvements

    • Added input validation and structured responses for the new endpoint.
    • Improved route registration with startup guards and clearer success/failure logging.
    • Improved error handling when federation services are unavailable.

@dionisio-bot
Copy link
Contributor

dionisio-bot bot commented Sep 26, 2025

Looks like this PR is ready to merge! 🎉
If you have any trouble, please check the PR guidelines

@changeset-bot
Copy link

changeset-bot bot commented Sep 26, 2025

⚠️ No Changeset found

Latest commit: 6ec7458

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

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 26, 2025

Walkthrough

Adds an authenticated REST endpoint /federation/matrixIds.verify that validates input and returns per-ID verification statuses by calling a newly added verifyMatrixIds on the federation service; wires service injection into route registration and updates the federation interface and implementation.

Changes

Cohort / File(s) Summary
API & route registration
apps/meteor/ee/server/api/federation.ts
Adds /federation/matrixIds.verify route with AJV query validation and auth; introduces module-scoped federationService and updated registerFederationRoutes(f) signature; guards for unregistered service; logs and try/catch around Express registration.
Federation service implementation
ee/packages/federation-matrix/src/FederationMatrix.ts
Adds async verifyMatrixIds(matrixIds: string[]): Promise<{ [key: string]: string }> to parse IDs, check local users or query remote homeservers' federation profile endpoint, and return per-ID status (VERIFIED / UNVERIFIED / UNABLE_TO_VERIFY).
Interface / types
packages/core-services/src/types/IFederationMatrixService.ts
Extends IFederationMatrixService with verifyMatrixIds(matrixIds: string[]): Promise<{ [key: string]: string }>.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Client
  participant API as REST API (/federation/matrixIds.verify)
  participant FS as IFederationMatrixService (verifyMatrixIds)
  participant U as Local User Store
  participant HS as Remote Homeserver

  Note over API: Auth + AJV validation

  C->>API: GET /federation/matrixIds.verify?matrixId=...
  API->>FS: verifyMatrixIds([ids])

  alt local home server
    FS->>U: lookup username
    U-->>FS: found / not found
  else remote home server
    loop per remote id
      FS->>HS: GET /_matrix/federation/v1/query/profile?user_id=...
      HS-->>FS: profile / { errcode: M_NOT_FOUND } / error
    end
  end

  FS-->>API: { matrixId: status, ... }
  API-->>C: 200 { matrixId -> status }
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • ricardogarim

Poem

I twitch my whiskers, hop and scribe—
I map each Matrix ID across the vibe.
Local burrow checks or distant roam,
I stamp them VERIFIED or send them home.
Carrot cheers for routes aligned—🥕🐇

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title succinctly describes the introduction of the verifyMatrixIds method and its corresponding API endpoint within the federation module, clearly reflecting the main change of the pull request in a concise and focused manner.
Linked Issues Check ✅ Passed The implementation adds the verifyMatrixIds method to IFederationMatrixService, provides a concrete implementation in the FederationMatrix class, and exposes it via a secured and validated API route, satisfying the coding requirements outlined in issue FDR-172.
Out of Scope Changes Check ✅ Passed All modifications exclusively pertain to the matrix ID verification feature, updating only the service interface, federation implementation, and API routing without touching unrelated modules or introducing extraneous functionality.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch chore/matrixIds.verify

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.

@ggazzo ggazzo added this to the 7.11.0 milestone Sep 26, 2025
@codecov
Copy link

codecov bot commented Sep 26, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 67.39%. Comparing base (10dadee) to head (6ec7458).
⚠️ Report is 4 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop   #37080      +/-   ##
===========================================
- Coverage    67.40%   67.39%   -0.01%     
===========================================
  Files         3328     3328              
  Lines       113338   113342       +4     
  Branches     20561    20557       -4     
===========================================
- Hits         76391    76385       -6     
- Misses       34346    34356      +10     
  Partials      2601     2601              
Flag Coverage Δ
e2e 57.29% <ø> (+0.02%) ⬆️
unit 71.15% <ø> (-0.02%) ⬇️

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 force-pushed the chore/matrixIds.verify branch from 5b0700a to d983a85 Compare September 26, 2025 19:36
@juliajforesti juliajforesti marked this pull request as ready for review September 26, 2025 19:49
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

🧹 Nitpick comments (1)
packages/core-services/src/types/IFederationMatrixService.ts (1)

30-30: Prefer a strongly typed verification result over Record<string, string>

Returning a plain string per matrixId leaves the contract open-ended—callers have no compile-time clue about the possible statuses or payload shape we intend to surface. Please introduce a dedicated type (e.g., a union of the allowed status literals or a structured { status: ..., reason?: ... } object) and use Promise<Record<string, MatrixIdVerificationResult>> (or similar) here. That keeps the interface self-documenting and prevents the REST layer and downstream clients from silently diverging later.

📜 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 f1fbcdd and d983a85.

📒 Files selected for processing (3)
  • apps/meteor/ee/server/api/federation.ts (1 hunks)
  • ee/packages/federation-matrix/src/FederationMatrix.ts (1 hunks)
  • packages/core-services/src/types/IFederationMatrixService.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-09-19T15:15:04.642Z
Learnt from: rodrigok
PR: RocketChat/Rocket.Chat#36991
File: apps/meteor/server/services/federation/infrastructure/rocket-chat/adapters/Settings.ts:219-221
Timestamp: 2025-09-19T15:15:04.642Z
Learning: The Federation_Matrix_homeserver_domain setting in apps/meteor/server/services/federation/infrastructure/rocket-chat/adapters/Settings.ts is part of the old federation system and is being deprecated/removed, so configuration issues with this setting should not be flagged for improvement.

Applied to files:

  • apps/meteor/ee/server/api/federation.ts
🧬 Code graph analysis (1)
apps/meteor/ee/server/api/federation.ts (2)
packages/core-services/src/types/IFederationMatrixService.ts (1)
  • IFederationMatrixService (4-31)
packages/rest-typings/src/v1/Ajv.ts (1)
  • ajv (23-23)
⏰ 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). (1)
  • GitHub Check: 🚢 Build Docker Images for Testing (alpine)

Comment on lines +17 to +43
query: ajv.compile<{
matrixIds: string[];
}>({
type: 'object',
properties: {
matrixIds: { type: 'array', items: { type: 'string' } },
},
}),
response: {
200: ajv.compile<{
results: { [key: string]: string };
}>({
type: 'object',
properties: {
results: { type: 'object', additionalProperties: { type: 'string' } },
},
}),
},
},
async function () {
const { matrixIds } = this.queryParams;
if (!federationService) {
throw new Error('Federation service not registered');
}
return API.v1.success({
results: await federationService.verifyMatrixIds(matrixIds),
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Make matrixIds mandatory in the query schema

Right now the AJV schema doesn’t mark matrixIds as required, so a request without that parameter is accepted and matrixIds is undefined. The handler then calls federationService.verifyMatrixIds(matrixIds), which blows up at runtime because it tries to iterate over undefined. Please make the field required (and consider rejecting unexpected extras) so we respond with a 400 instead of a 500:

 		query: ajv.compile<{
 			matrixIds: string[];
 		}>({
 			type: 'object',
 			properties: {
 				matrixIds: { type: 'array', items: { type: 'string' } },
 			},
+			required: ['matrixIds'],
+			additionalProperties: false,
 		}),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
query: ajv.compile<{
matrixIds: string[];
}>({
type: 'object',
properties: {
matrixIds: { type: 'array', items: { type: 'string' } },
},
}),
response: {
200: ajv.compile<{
results: { [key: string]: string };
}>({
type: 'object',
properties: {
results: { type: 'object', additionalProperties: { type: 'string' } },
},
}),
},
},
async function () {
const { matrixIds } = this.queryParams;
if (!federationService) {
throw new Error('Federation service not registered');
}
return API.v1.success({
results: await federationService.verifyMatrixIds(matrixIds),
});
query: ajv.compile<{
matrixIds: string[];
}>({
type: 'object',
properties: {
matrixIds: { type: 'array', items: { type: 'string' } },
},
required: ['matrixIds'],
additionalProperties: false,
}),
🤖 Prompt for AI Agents
In apps/meteor/ee/server/api/federation.ts around lines 17 to 43, the AJV query
schema does not mark matrixIds as required so matrixIds can be undefined at
runtime; update the query schema to include required: ['matrixIds'], tighten the
matrixIds property to be an array of strings (optionally with minItems: 1 if
empty should be rejected), and set additionalProperties: false on the query
object to reject unexpected extras; this ensures AJV returns a 400 for
missing/extra params and prevents passing undefined into
federationService.verifyMatrixIds.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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: 1

📜 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 d983a85 and 6ec7458.

📒 Files selected for processing (1)
  • ee/packages/federation-matrix/src/FederationMatrix.ts (1 hunks)
⏰ 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

Comment on lines +980 to +985
if ('errcode' in result && result.errcode === 'M_NOT_FOUND') {
return [matrixId, 'UNVERIFIED'];
}

return [matrixId, 'VERIFIED'];
} catch (e) {
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Do not mark errored Matrix profile queries as VERIFIED

Any response that still contains an errcode (e.g., M_FORBIDDEN, M_UNAUTHORIZED, M_LIMIT_EXCEEDED) currently falls through this branch and is treated as VERIFIED. That gives a false positive: a homeserver telling us it could not supply the profile is strong evidence that we failed to verify the ID. Please treat every non-M_NOT_FOUND errcode as UNABLE_TO_VERIFY instead of VERIFIED.

-						if ('errcode' in result && result.errcode === 'M_NOT_FOUND') {
-							return [matrixId, 'UNVERIFIED'];
-						}
-
-						return [matrixId, 'VERIFIED'];
+						if ('errcode' in result) {
+							if (result.errcode === 'M_NOT_FOUND') {
+								return [matrixId, 'UNVERIFIED'];
+							}
+
+							return [matrixId, 'UNABLE_TO_VERIFY'];
+						}

Committable suggestion skipped: line range outside the PR's diff.

@ggazzo ggazzo added the stat: QA assured Means it has been tested and approved by a company insider label Sep 26, 2025
@dionisio-bot dionisio-bot bot added the stat: ready to merge PR tested and approved waiting for merge label Sep 26, 2025
@ggazzo ggazzo merged commit 23ba66a into develop Sep 26, 2025
52 checks passed
@ggazzo ggazzo deleted the chore/matrixIds.verify branch September 26, 2025 21:30
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 stat: ready to merge PR tested and approved waiting for merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants