Skip to content

Conversation

@rodrigok
Copy link
Member

@rodrigok rodrigok commented Sep 25, 2025

Linked to RocketChat/Rocket.Chat#37064

Summary by CodeRabbit

  • Bug Fixes
    • Media authorization is more reliable for federated content, deriving the target room from media metadata to prevent incorrect access denials.
  • Performance
    • Reduced lookups during media access checks, improving response times under load.
  • Refactor
    • Simplified federation logic and service dependencies by consolidating room resolution into upload metadata and removing legacy bridging layers.
  • Chores
    • Tooling updated to ignore generated federation bundles, reducing noise and speeding up local analysis.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 25, 2025

Walkthrough

Removes MatrixBridgedRoom repository and its DI wiring, shifts media authorization to read Matrix room ID directly from uploads, updates Upload repository API accordingly, and adds "federation-bundle" to Biome ignore list. No new public exports are added; one repository file is deleted and related imports/registrations are removed.

Changes

Cohort / File(s) Summary
Config: Biome ignore
biome.jsonc
Added "federation-bundle" to files.ignore array; no other config changes.
DI container and repo removal
packages/federation-sdk/src/container.ts, packages/federation-sdk/src/repositories/matrix-bridged-room.repository.ts
Removed MatrixBridgedRoomRepository import, collection registration, and singleton registration; deleted matrix-bridged-room.repository.ts file and its MatrixBridgedRoom type and repository.
Upload repository API change
packages/federation-sdk/src/repositories/upload.repository.ts
Added federation.mrid: string to Upload; renamed findRocketChatRoomIdByMediaId to findByMediaId returning `Upload
Authorization service refactor
packages/federation-sdk/src/services/event-authorization.service.ts
Removed dependency on MatrixBridgedRoomRepository; canAccessMedia now reads Matrix room ID from rcUpload.federation.mrid instead of bridged-room lookup; constructor signature updated accordingly.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant AuthService as EventAuthorizationService
  participant UploadRepo as UploadRepository
  participant Matrix as Matrix Homeserver

  Client->>AuthService: canAccessMedia(mediaId, userId)
  AuthService->>UploadRepo: findByMediaId(mediaId)
  UploadRepo-->>AuthService: Upload | null

  alt Upload found
    note over AuthService: Extract mrid from upload.federation.mrid
    AuthService->>Matrix: Verify user access to mrid
    Matrix-->>AuthService: allowed | denied
    AuthService-->>Client: result
  else No upload
    AuthService-->>Client: denied (not found)
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • ggazzo

Poem

I hop through fields of code so bright,
Snipping old bridges in gentle light.
A media trail, direct and clean—
mrid in paw, no maps between.
Biome naps on bundles’ edge,
While uploads whisper, “We’ve sworn our pledge.”
Thump-thump—refactors, fleet and keen!

Pre-merge checks and finishing touches

✅ Passed checks (3 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 primary change to restore upload functionality and is clear, concise, and directly related to the main fix in the pull request.
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 fix/upload-not-working

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.

@codecov-commenter
Copy link

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 81.07%. Comparing base (a96d047) to head (e9a338e).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #225   +/-   ##
=======================================
  Coverage   81.07%   81.07%           
=======================================
  Files          63       63           
  Lines        4719     4719           
=======================================
  Hits         3826     3826           
  Misses        893      893           

☔ View full report in Codecov by Sentry.
📢 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.

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

🧹 Nitpick comments (2)
packages/federation-sdk/src/repositories/upload.repository.ts (2)

8-11: New federation.mrid requires data backfill/validation.

Runtime will throw if older Upload docs lack federation.mrid. Confirm a migration/backfill exists, or ensure callers defensively handle missing mrid (see service comment).

Suggestion: add a small migration/index:

  • Backfill federation.mrid for existing uploads with federation.mediaId.
  • Create an index on "federation.mediaId" (unique if appropriate) to keep lookups fast.

20-22: Align return type with MongoDB driver and add index on federation.mediaId.

  • In packages/federation-sdk/src/repositories/upload.repository.ts change
    async findByMediaId(mediaId: string): Promise<Upload | null>
    to
    async findByMediaId(mediaId: string): Promise<WithId<Upload> | null> (import WithId from mongodb).
  • Add an index on federation.mediaId (e.g. in your DB initialization or repository constructor) to avoid full collection scans.
📜 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 3e6b856 and e9a338e.

📒 Files selected for processing (5)
  • biome.jsonc (1 hunks)
  • packages/federation-sdk/src/container.ts (0 hunks)
  • packages/federation-sdk/src/repositories/matrix-bridged-room.repository.ts (0 hunks)
  • packages/federation-sdk/src/repositories/upload.repository.ts (2 hunks)
  • packages/federation-sdk/src/services/event-authorization.service.ts (1 hunks)
💤 Files with no reviewable changes (2)
  • packages/federation-sdk/src/repositories/matrix-bridged-room.repository.ts
  • packages/federation-sdk/src/container.ts
🔇 Additional comments (1)
biome.jsonc (1)

49-49: Ensure ignore glob matches actual path(s).

If the bundle can appear outside the repo root, prefer a glob: "**/federation-bundle".

Apply this diff if needed:

-			"federation-bundle",
+			"**/federation-bundle",

Comment on lines +368 to 375
const rcUpload = await this.uploadRepository.findByMediaId(mediaId);
if (!rcUpload) {
this.logger.debug(`Media ${mediaId} not found in any room`);
return false;
}

const matrixRoomId =
await this.matrixBridgedRoomRepository.findMatrixRoomId(rcRoomId);
if (!matrixRoomId) {
this.logger.debug(`Media ${mediaId} not found in any room`);
return false;
}
const matrixRoomId = rcUpload.federation.mrid;

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

Guard against missing federation.mrid to prevent runtime crash.

Older upload docs may lack federation or mrid. Accessing rcUpload.federation.mrid can throw.

Apply this diff:

-			const rcUpload = await this.uploadRepository.findByMediaId(mediaId);
-			if (!rcUpload) {
+			const rcUpload = await this.uploadRepository.findByMediaId(mediaId);
+			if (!rcUpload) {
 				this.logger.debug(`Media ${mediaId} not found in any room`);
 				return false;
 			}
-
-			const matrixRoomId = rcUpload.federation.mrid;
+			const matrixRoomId = rcUpload.federation?.mrid;
+			if (!matrixRoomId) {
+				this.logger.debug(
+					`Media ${mediaId} found but missing federation.mrid; denying access`,
+				);
+				return 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
const rcUpload = await this.uploadRepository.findByMediaId(mediaId);
if (!rcUpload) {
this.logger.debug(`Media ${mediaId} not found in any room`);
return false;
}
const matrixRoomId =
await this.matrixBridgedRoomRepository.findMatrixRoomId(rcRoomId);
if (!matrixRoomId) {
this.logger.debug(`Media ${mediaId} not found in any room`);
return false;
}
const matrixRoomId = rcUpload.federation.mrid;
const rcUpload = await this.uploadRepository.findByMediaId(mediaId);
if (!rcUpload) {
this.logger.debug(`Media ${mediaId} not found in any room`);
return false;
}
const matrixRoomId = rcUpload.federation?.mrid;
if (!matrixRoomId) {
this.logger.debug(
`Media ${mediaId} found but missing federation.mrid; denying access`,
);
return false;
}
🤖 Prompt for AI Agents
In packages/federation-sdk/src/services/event-authorization.service.ts around
lines 368 to 375, accessing rcUpload.federation.mrid may throw for older upload
docs missing federation or mrid; guard by checking rcUpload.federation and
rcUpload.federation.mrid before reading it, log a debug/warn with the mediaId if
missing, and return false (or otherwise bail out) instead of dereferencing;
ensure matrixRoomId is only assigned after the presence check and keep typesafe
access (optional: narrow types or use optional chaining with a clear fallback
and early return).

@rodrigok rodrigok merged commit e83af5b into main Sep 25, 2025
3 checks passed
@rodrigok rodrigok deleted the fix/upload-not-working branch September 25, 2025 19:55
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.

4 participants