Skip to content

Conversation

@KevLehman
Copy link
Member

@KevLehman KevLehman commented Oct 28, 2025

Proposed changes (including videos or screenshots)

Issue(s)

https://rocketchat.atlassian.net/browse/ABAC-8

Steps to test or reproduce

Further comments

Summary by CodeRabbit

  • New Features

    • Invite operations now validate against ABAC settings. When ABAC is enabled for a room, invite creation and token validation are blocked to enforce access control policies.
  • Tests

    • Added comprehensive test coverage for ABAC-managed room invite operations, including scenarios with ABAC enabled and disabled states.

@dionisio-bot
Copy link
Contributor

dionisio-bot bot commented Oct 28, 2025

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

changeset-bot bot commented Oct 28, 2025

⚠️ No Changeset found

Latest commit: dbf5cea

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 Oct 28, 2025

Walkthrough

ABAC validation is added to invite link creation and validation flows. When ABAC is enabled and a room has ABAC attributes, invite operations are rejected early with an error before permission checks. Test coverage validates the new behavior including setup/teardown with direct database manipulation.

Changes

Cohort / File(s) Summary
Invite ABAC Validation
apps/meteor/app/invites/server/functions/findOrCreateInvite.ts, apps/meteor/app/invites/server/functions/validateInviteToken.ts
Added early-exit validation checks that reject invite creation and token validation when ABAC is enabled and the room has ABAC attributes; throws error-invalid-room before proceeding with permission or expiry checks.
ABAC Invite Test Suite
apps/meteor/tests/end-to-end/api/abac.ts
Added comprehensive test coverage for invite link behavior under ABAC including: MongoDB connection setup/teardown, helper function to assign ABAC attributes directly, and test flows validating creation/validation/state-transitions for ABAC-managed rooms.

Sequence Diagram

sequenceDiagram
    participant Client
    participant InviteFunc as Invite Function
    participant RoomDB as Room Storage
    participant ABAC as ABAC Check

    rect rgb(200, 220, 240)
    Note over Client,ABAC: NEW: Early ABAC Validation
    Client->>InviteFunc: Create/Validate Invite
    InviteFunc->>RoomDB: Fetch Room
    RoomDB-->>InviteFunc: Room + abacAttributes
    InviteFunc->>ABAC: Check if ABAC_Enabled<br/>and has abacAttributes
    alt ABAC Match
        ABAC-->>InviteFunc: Reject
        InviteFunc-->>Client: error-invalid-room ❌
    else ABAC No Match
        ABAC-->>InviteFunc: Continue
        InviteFunc->>InviteFunc: Permission & Expiry Checks
        InviteFunc-->>Client: Success ✓
    end
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Test file complexity: The ABAC test suite introduces new database connection lifecycle management and direct collection manipulation; verify setup/teardown properly closes connections and doesn't leak resources.
  • ABAC attribute validation: Confirm both findOrCreateInvite and validateInviteToken consistently check the same conditions and error states.
  • Import addition: Verify settings import in validateInviteToken.ts correctly accesses ABAC_Enabled flag.

Possibly related PRs

Suggested labels

stat: ready to merge, stat: QA assured

Suggested reviewers

  • tassoevan
  • dougfabris

Poem

🐰 Invites now bow to ABAC's might,
Room attributes guarded tight,
Early checks say "nay!" with care,
No links for those who don't prepare!

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Linked Issues Check ⚠️ Warning The PR is linked to ABAC-8, which specifies two primary coding requirements: disabling invite links (backend rejection with HTTP 403 for creation and usage) and preventing message forwarding from ABAC rooms (also HTTP 403). The changes in this PR address the backend rejection of invite creation and token validation through modifications to findOrCreateInvite.ts and validateInviteToken.ts, fulfilling the invite-link backend requirement. However, the PR does not appear to implement the second requirement to prevent message forwarding from ABAC rooms, as there are no changes visible to message forwarding functionality. Additionally, while ABAC-8's acceptance criteria include hiding the "Invite via Link" UI in ABAC rooms, no frontend UI changes are evident in the file summaries provided. To achieve full compliance with ABAC-8, the PR should include: implementation of message forwarding prevention that returns HTTP 403 when forwarding from ABAC rooms, and UI changes to hide or disable the "Invite via Link" interface in ABAC-managed rooms. If this PR is intentionally implementing only the invite-link backend validation as a partial solution, it should be clarified whether a separate PR addresses the message forwarding requirement, or if the scope should be explicitly adjusted in the issue tracking.
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 (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "feat: Prevent invite links from being generated on abac rooms" is clear, concise, and directly describes the primary change in the changeset. It accurately reflects the main code modifications across the invite-related functions and ABAC test coverage, clearly summarizing the key objective without vagueness or unnecessary details. A teammate scanning the commit history would understand that this PR implements ABAC-based validation to block invite link generation in ABAC-managed rooms.
Out of Scope Changes Check ✅ Passed The code changes are focused on the stated PR objective of preventing invite link generation for ABAC-managed rooms. Modifications to findOrCreateInvite.ts and validateInviteToken.ts add ABAC-based validation checks that are directly aligned with blocking invite creation and token validation, and the extended test suite in abac.ts specifically covers invite-link and ABAC-management scenarios. All visible changes are directly related to the core objective without introducing unrelated modifications or extraneous code outside the scope of ABAC invite-link prevention.
✨ 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 feat/block-invite-link

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
Copy link

codecov bot commented Oct 28, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 70.10%. Comparing base (c2dadb9) to head (dbf5cea).
⚠️ Report is 1 commits behind head on feat/abac.

Additional details and impacted files

Impacted file tree graph

@@              Coverage Diff              @@
##           feat/abac   #37325      +/-   ##
=============================================
- Coverage      70.27%   70.10%   -0.18%     
=============================================
  Files           3039     3032       -7     
  Lines         104736   103987     -749     
  Branches       18586    18509      -77     
=============================================
- Hits           73602    72895     -707     
+ Misses         29177    29146      -31     
+ Partials        1957     1946      -11     
Flag Coverage Δ
e2e 57.47% <ø> (-0.04%) ⬇️
unit 71.61% <ø> (-0.26%) ⬇️

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.

@KevLehman KevLehman force-pushed the feat/block-invite-link branch from e63f7bc to 5ae7f4e Compare October 28, 2025 17:04
@KevLehman KevLehman marked this pull request as ready for review October 28, 2025 18:47
@KevLehman KevLehman requested a review from a team as a code owner October 28, 2025 18:47
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: 0

🧹 Nitpick comments (3)
apps/meteor/app/invites/server/functions/validateInviteToken.ts (1)

30-35: ABAC short-circuit is correct; minor type/helper nits.

  • Type the flag: settings.get<boolean>('ABAC_Enabled').
  • Optional: extract a shared isRoomAbacManaged(room) helper to avoid duplication with findOrCreateInvite.

Apply:

- if (settings.get('ABAC_Enabled') && room?.abacAttributes?.length) {
+ if (settings.get<boolean>('ABAC_Enabled') && room?.abacAttributes?.length) {
apps/meteor/tests/end-to-end/api/abac.ts (2)

15-26: Add cleanup for user ABAC attributes to avoid cross-test leakage.

Provide a counterpart helper to unset/reset abacAttributes and call it in the relevant after hook.

Apply:

 const addAbacAttributesToUserDirectly = async (userId: string, abacAttributes: IAbacAttributeDefinition[]) => {
   await connection.db().collection('users').updateOne(
     {
       // @ts-expect-error - collection types for _id
       _id: userId,
     },
     { $set: { abacAttributes } },
   );
 };
+
+const removeAbacAttributesFromUserDirectly = async (userId: string) => {
+  await connection.db().collection('users').updateOne(
+    { _id: userId as any },
+    { $unset: { abacAttributes: 1 } },
+  );
+};

1258-1412: Align tests with ABAC-8 (403 on creation/usage), add “use invite” test, and clean user ABAC attrs.

  • Expect 403 (not 400) when creating invites for ABAC rooms after changing server to error-action-not-allowed.
  • Add a test that attempts to use/join via the invite token against an ABAC room and asserts HTTP 403 (usage must be blocked).
  • Call removeAbacAttributesFromUserDirectly(credentials['X-User-Id']) in this block’s after to revert DB changes.

Proposed minimal diffs:

- .expect(400)
+ .expect(403)
  .expect((res) => {
-   expect(res.body).to.have.property('errorType', 'error-invalid-room');
-   expect(res.body).to.have.property('error').that.includes('Room is ABAC managed');
+   expect(res.body).to.have.property('errorType', 'error-action-not-allowed');
+   expect(res.body).to.have.property('error').that.includes('error-room-is-abac-managed');
  });
  after(async () => {
-   await Promise.all(createdInviteIds.map((id) => request.delete(`${v1}/removeInvite/${id}`).set(credentials)));
+   await Promise.all(createdInviteIds.map((id) => request.delete(`${v1}/removeInvite/${id}`).set(credentials)));
+   await removeAbacAttributesFromUserDirectly(credentials['X-User-Id']);
  });

And please add a new case:

  • “Using invite for ABAC room returns 403”: attempt the join/usage endpoint with the token and assert 403. If the endpoint name differs (e.g., /api/v1/invites.use or equivalent), use the appropriate one. Based on learnings.
📜 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 c2dadb9 and dbf5cea.

📒 Files selected for processing (3)
  • apps/meteor/app/invites/server/functions/findOrCreateInvite.ts (1 hunks)
  • apps/meteor/app/invites/server/functions/validateInviteToken.ts (2 hunks)
  • apps/meteor/tests/end-to-end/api/abac.ts (4 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: KevLehman
PR: RocketChat/Rocket.Chat#37303
File: apps/meteor/tests/end-to-end/api/abac.ts:1125-1137
Timestamp: 2025-10-27T14:38:46.994Z
Learning: In Rocket.Chat ABAC feature, when ABAC is disabled globally (ABAC_Enabled setting is false), room-level ABAC attributes are not evaluated when changing room types. This means converting a private room to public will succeed even if the room has ABAC attributes, as long as the global ABAC setting is disabled.
📚 Learning: 2025-10-24T17:32:05.348Z
Learnt from: KevLehman
PR: RocketChat/Rocket.Chat#37299
File: apps/meteor/ee/server/lib/ldap/Manager.ts:438-454
Timestamp: 2025-10-24T17:32:05.348Z
Learning: In Rocket.Chat, ABAC attributes can only be set on private rooms and teams (type 'p'), not on public rooms (type 'c'). Therefore, when checking for ABAC-protected rooms/teams during LDAP sync or similar operations, it's sufficient to query only private rooms using methods like `findPrivateRoomsByIdsWithAbacAttributes`.

Applied to files:

  • apps/meteor/tests/end-to-end/api/abac.ts
🧬 Code graph analysis (1)
apps/meteor/tests/end-to-end/api/abac.ts (2)
packages/core-typings/src/IAbacAttribute.ts (1)
  • IAbacAttributeDefinition (3-14)
apps/meteor/tests/data/api-data.ts (2)
  • request (10-10)
  • credentials (39-42)
🔇 Additional comments (4)
apps/meteor/app/invites/server/functions/validateInviteToken.ts (1)

4-5: LGTM on settings import.

apps/meteor/tests/end-to-end/api/abac.ts (2)

2-5: Imports look good.


45-46: Connection lifecycle is fine.

Also applies to: 59-62

apps/meteor/app/invites/server/functions/findOrCreateInvite.ts (1)

66-71: The review comment contains a factually incorrect assertion about HTTP status codes.

The review claims that using error-action-not-allowed will yield HTTP 403 per ABAC-8 spec. However, the codebase shows:

  1. All thrown Meteor.Error instances (regardless of error code) are caught by a generic exception handler in ApiClass.ts:failure() which hardcodes statusCode: 400.

  2. To return 403, code must explicitly call API.v1.forbidden() (line 378–380). This is not used for Meteor.Error exceptions.

  3. Both error-invalid-room and error-action-not-allowed thrown as Meteor.Error return 400, not 403.

The suggested change would not achieve the claimed 403 HTTP response. Additionally, the existing ABAC checks elsewhere in the codebase (e.g., saveRoomSettings.ts:73-74, 108-109) already use error-action-not-allowed for similar scenarios, showing no precedent for a special 403 requirement. The current error-invalid-room usage is consistent with other "room not accessible" patterns and is validated by existing tests.

Likely an incorrect or invalid review comment.

@tassoevan tassoevan merged commit 81c197b into feat/abac Oct 29, 2025
49 checks passed
@tassoevan tassoevan deleted the feat/block-invite-link branch October 29, 2025 13: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.

3 participants