Skip to content

refactor(authorization): accept IUser in hasPermissionAsync wrappers#41340

Merged
ggazzo merged 1 commit into
developfrom
chore/authz-haspermission-accept-user
Jul 13, 2026
Merged

refactor(authorization): accept IUser in hasPermissionAsync wrappers#41340
ggazzo merged 1 commit into
developfrom
chore/authz-haspermission-accept-user

Conversation

@ggazzo

@ggazzo ggazzo commented Jul 13, 2026

Copy link
Copy Markdown
Member

Proposal

Authorization.hasPermission / hasAllPermission / hasAtLeastOnePermission already accept string | IUser. When a full user is passed, the service skips an internal Users.findOneById inside getRoles — saving a DB find per permission check on hot paths where the user is already in hand.

The hasPermissionAsync wrappers only typed userId: string, blocking that optimization. This widens them and starts migrating call sites one by one.

Changes

  • IAuthorization: add a string | IUser overload, declared last so the existing @deprecated string overload still flags plain-uid callers (keeps the migration nudge).
  • hasPermission.ts wrappers: hasPermissionAsync / hasAllPermissionAsync / hasAtLeastOnePermissionAsync now accept IUser['_id'] | IUser, plain passthrough.
  • Meteor.userAsync() typed Promise<IUser | null>: RC stores full user documents and all in-repo callers are no-arg (no field projection), so roles is always present at runtime.
  • Migrated first sites: crowd/server/methods.ts, reactions/server/setReaction.ts.

Safety

getRoles reads user.roles directly. IUser.roles is required, so TypeScript rejects passing a rolesless projection — preventing a silent zero-permission result. Only sites where the user is provably a complete IUser are migrated; the type checker gates the rest.

Follow-ups

  • Remaining X._id sites holding a full IUser — migrate incrementally.
  • String-only sites (~200) hold no user object; no benefit, left untouched.
  • Optional: key getRolesCached on _id instead of JSON.stringify(user) so object and string callers share cache entries.

Review in cubic

Task: ARCH-2248

Summary by CodeRabbit

  • Bug Fixes

    • Improved permission checks for connection testing, user synchronization, and reactions, including scenarios involving read-only rooms.
    • Authorization now leverages the complete signed-in user context when available, resulting in more reliable access decisions.
  • Enhancements

    • Added Meteor.userAsync() to retrieve the current signed-in user asynchronously (Promise of the user or null).

@dionisio-bot

dionisio-bot Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

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

@changeset-bot

changeset-bot Bot commented Jul 13, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: b2cfa5a

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

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Authorization contracts now accept user IDs or full user objects. Selected crowd and reaction permission checks pass full user objects, and Meteor.userAsync is typed to return IUser | null.

Changes

Authorization input migration

Layer / File(s) Summary
Authorization contracts and user typing
apps/meteor/server/lib/authorization/hasPermission.ts, packages/core-services/src/types/IAuthorization.ts, apps/meteor/definition/externals/meteor/meteor.d.ts
Async permission helpers and authorization interfaces accept user IDs or IUser objects, while Meteor.userAsync returns Promise<IUser | null>.
Server permission-check adoption
apps/meteor/app/crowd/server/methods.ts, apps/meteor/app/reactions/server/setReaction.ts
Crowd connection/user-sync checks and readonly-room reaction checks pass the full user object to authorization helpers.

Estimated code review effort: 2 (Simple) | ~10 minutes

Suggested labels: type: chore

Suggested reviewers: sampaiodiego, kevlehman, gabriellsh

🚥 Pre-merge checks | ✅ 5
✅ 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 accurately reflects the main change: authorization wrappers now accept IUser in hasPermissionAsync.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • ARCH-2248: Request failed with status code 401

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.

@ggazzo ggazzo added this to the 8.7.0 milestone Jul 13, 2026
@codecov

codecov Bot commented Jul 13, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 40.00000% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.09%. Comparing base (d9fca72) to head (7fa87b7).
⚠️ Report is 2 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop   #41340      +/-   ##
===========================================
+ Coverage    68.98%   69.09%   +0.10%     
===========================================
  Files         3757     3759       +2     
  Lines       147735   147859     +124     
  Branches     26381    26477      +96     
===========================================
+ Hits        101919   102164     +245     
+ Misses       41317    41208     -109     
+ Partials      4499     4487      -12     
Flag Coverage Δ
unit 70.61% <40.00%> (+0.18%) ⬆️

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 marked this pull request as ready for review July 13, 2026 16:37
@ggazzo ggazzo requested a review from a team as a code owner July 13, 2026 16:37
@ggazzo

ggazzo commented Jul 13, 2026

Copy link
Copy Markdown
Member Author

/jira ARCH-2200

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

No issues found across 5 files

Re-trigger cubic

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/meteor/definition/externals/meteor/meteor.d.ts`:
- Around line 52-55: Update the userAsync declaration with overloads: keep
no-argument calls returning IUser | null, and add a fields/options overload
returning a partial user type that cannot be treated as a complete IUser. Ensure
projected calls preserve nullable typing while preventing access to
complete-user-only properties such as roles.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1fb26153-1e4b-436e-9a0f-5945b68be5e4

📥 Commits

Reviewing files that changed from the base of the PR and between d9fca72 and 4dc8580.

📒 Files selected for processing (5)
  • apps/meteor/app/crowd/server/methods.ts
  • apps/meteor/app/reactions/server/setReaction.ts
  • apps/meteor/definition/externals/meteor/meteor.d.ts
  • apps/meteor/server/lib/authorization/hasPermission.ts
  • packages/core-services/src/types/IAuthorization.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (2)
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: Hacktron Security Check
🧰 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/app/crowd/server/methods.ts
  • apps/meteor/app/reactions/server/setReaction.ts
  • apps/meteor/definition/externals/meteor/meteor.d.ts
  • apps/meteor/server/lib/authorization/hasPermission.ts
  • packages/core-services/src/types/IAuthorization.ts
🧠 Learnings (3)
📚 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/app/crowd/server/methods.ts
  • apps/meteor/app/reactions/server/setReaction.ts
  • apps/meteor/definition/externals/meteor/meteor.d.ts
  • apps/meteor/server/lib/authorization/hasPermission.ts
  • packages/core-services/src/types/IAuthorization.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/app/crowd/server/methods.ts
  • apps/meteor/app/reactions/server/setReaction.ts
  • apps/meteor/definition/externals/meteor/meteor.d.ts
  • apps/meteor/server/lib/authorization/hasPermission.ts
  • packages/core-services/src/types/IAuthorization.ts
📚 Learning: 2026-05-06T12:21:44.083Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 40256
File: apps/meteor/client/components/CreateDiscussion/CreateDiscussion.tsx:121-149
Timestamp: 2026-05-06T12:21:44.083Z
Learning: Field wrappers in rocket.chat/fuselage-forms (Field, FieldLabel, FieldRow, FieldError, FieldHint) auto-create htmlFor/id associations, aria-describedby, and role="alert" for errors. Do not manually set htmlFor, id, aria-describedby, or role attributes when using these wrappers. This automatic wiring does not apply to plain rocket.chat/fuselage components, which require explicit ID wiring per the accessibility docs. In code reviews, prefer using fuselage-forms wrappers for form fields and verify there is no unnecessary manual ID/aria wiring in files that use these wrappers. If a component uses plain fuselage components, ensure proper id wiring as per docs.

Applied to files:

  • apps/meteor/app/crowd/server/methods.ts
  • apps/meteor/app/reactions/server/setReaction.ts
  • apps/meteor/definition/externals/meteor/meteor.d.ts
  • apps/meteor/server/lib/authorization/hasPermission.ts
  • packages/core-services/src/types/IAuthorization.ts
🔇 Additional comments (5)
apps/meteor/definition/externals/meteor/meteor.d.ts (1)

2-2: LGTM!

apps/meteor/server/lib/authorization/hasPermission.ts (1)

4-21: LGTM!

packages/core-services/src/types/IAuthorization.ts (1)

13-24: LGTM!

apps/meteor/app/crowd/server/methods.ts (1)

27-27: LGTM! Both call sites correctly narrow user to non-null before forwarding it to hasPermissionAsync. Note: correctness here depends on Meteor.userAsync() reliably returning a full IUser with roles, which is flagged for verification at its type declaration in apps/meteor/definition/externals/meteor/meteor.d.ts (lines 52-55).

Also applies to: 59-59

apps/meteor/app/reactions/server/setReaction.ts (1)

34-43: 🎯 Functional Correctness

No action needed for setReaction callers

setReaction is only called from executeSetReaction, which loads the user with Users.findOneById(userId) before passing it through. No other in-repo callers pass a projected user here.

			> Likely an incorrect or invalid review comment.

Comment thread apps/meteor/definition/externals/meteor/meteor.d.ts Outdated
Comment thread packages/core-services/src/types/IAuthorization.ts Outdated
Comment thread packages/core-services/src/types/IAuthorization.ts Outdated
Comment thread packages/core-services/src/types/IAuthorization.ts Outdated
Comment thread apps/meteor/server/lib/authorization/hasPermission.ts Outdated
Comment thread apps/meteor/definition/externals/meteor/meteor.d.ts Outdated
Comment thread apps/meteor/definition/externals/meteor/meteor.d.ts Outdated
@ggazzo ggazzo force-pushed the chore/authz-haspermission-accept-user branch from 4dc8580 to 7fa87b7 Compare July 13, 2026 17:29
@ggazzo

ggazzo commented Jul 13, 2026

Copy link
Copy Markdown
Member Author

Thanks for the review @sampaiodiego! Addressed:

  • Removed the extra string | IUser overloads from IAuthorization — the wrappers now narrow with typeof so each call resolves against the existing IUser / string overloads. No public interface change.
  • Meteor.userAsync() typed with no arguments: function userAsync(): Promise<IUser | null>;
  • Dropped the explanatory comments.

The reason for the typeof narrowing (instead of just passing the union): core-services is consumed as its built dist, whose IAuthorization exposes only the IUser and string overloads — a union argument doesn't resolve against separate overloads, so narrowing is the clean way to pass through without touching the interface.

Authorization already resolves roles from a full IUser, so passing one
lets it skip an internal Users.findOneById. Widen the hasPermissionAsync /
hasAllPermissionAsync / hasAtLeastOnePermissionAsync wrappers to
`string | IUser` and start migrating call sites that already hold a
complete user document.

- IAuthorization: collapse the `IUser` / `@deprecated string` overload pairs
  into a single `string | IUser` signature so a union argument resolves
  without per-call narrowing.
- Type Meteor.userAsync() as Promise<IUser | null>: RC stores full user
  documents and every in-repo caller is no-arg, so roles are always present.
- Migrate crowd methods and setReaction as the first sites.

Remaining string-only call sites are intentionally left for follow-ups.
TypeScript rejects rolesless projections, preventing silent
zero-permission results.
@ggazzo ggazzo force-pushed the chore/authz-haspermission-accept-user branch from 7fa87b7 to b2cfa5a Compare July 13, 2026 17:49

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

10-12: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider using IUser['_id'] instead of bare string for the user parameter.

The wrapper functions in hasPermission.ts type the same parameter as IUser['_id'] | IUser, while this interface uses string | IUser. Both resolve to the same structural type, but IUser['_id'] is more semantically precise and keeps the interface aligned with its callers.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core-services/src/types/IAuthorization.ts` around lines 10 - 12,
Update the user parameter types in hasAllPermission, hasPermission, and
hasAtLeastOnePermission to use IUser['_id'] | IUser instead of string | IUser,
keeping the interface aligned with the wrapper functions in hasPermission.ts.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@packages/core-services/src/types/IAuthorization.ts`:
- Around line 10-12: Update the user parameter types in hasAllPermission,
hasPermission, and hasAtLeastOnePermission to use IUser['_id'] | IUser instead
of string | IUser, keeping the interface aligned with the wrapper functions in
hasPermission.ts.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a5cf7bd3-cd65-42af-a642-424f150fcf09

📥 Commits

Reviewing files that changed from the base of the PR and between 7fa87b7 and b2cfa5a.

📒 Files selected for processing (5)
  • apps/meteor/app/crowd/server/methods.ts
  • apps/meteor/app/reactions/server/setReaction.ts
  • apps/meteor/definition/externals/meteor/meteor.d.ts
  • apps/meteor/server/lib/authorization/hasPermission.ts
  • packages/core-services/src/types/IAuthorization.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • apps/meteor/app/reactions/server/setReaction.ts
  • apps/meteor/definition/externals/meteor/meteor.d.ts
  • apps/meteor/app/crowd/server/methods.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (4)
  • GitHub Check: 📦 Build Packages
  • GitHub Check: CodeQL-Build
  • GitHub Check: Hacktron Security Check
  • GitHub Check: CodeQL-Build
⚠️ CI failures not shown inline (2)

GitHub Check: Dionisio QA: Some checks did not pass

Conclusion: failure

View job details

**Conclusion:** failure
### Steps
- ✅ **No merge conflicts**
- ❌ **QA assured** — This PR is missing the 'stat: QA assured' label
- ✅ **Mergeable**
- ✅ **Has milestone or project**
- ✅ **Valid PR title**
- ✅ **Correct target version**

GitHub Check: Dionisio QA: Some checks did not pass

Conclusion: failure

View job details

**Conclusion:** failure
### Steps
- ✅ **No merge conflicts**
- ❌ **QA assured** — This PR is missing the 'stat: QA assured' label
- ✅ **Mergeable**
- ✅ **Has milestone or project**
- ✅ **Valid PR title**
- ✅ **Correct target version**
🧰 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/lib/authorization/hasPermission.ts
  • packages/core-services/src/types/IAuthorization.ts
🧠 Learnings (3)
📚 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/lib/authorization/hasPermission.ts
  • packages/core-services/src/types/IAuthorization.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/lib/authorization/hasPermission.ts
  • packages/core-services/src/types/IAuthorization.ts
📚 Learning: 2026-05-06T12:21:44.083Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 40256
File: apps/meteor/client/components/CreateDiscussion/CreateDiscussion.tsx:121-149
Timestamp: 2026-05-06T12:21:44.083Z
Learning: Field wrappers in rocket.chat/fuselage-forms (Field, FieldLabel, FieldRow, FieldError, FieldHint) auto-create htmlFor/id associations, aria-describedby, and role="alert" for errors. Do not manually set htmlFor, id, aria-describedby, or role attributes when using these wrappers. This automatic wiring does not apply to plain rocket.chat/fuselage components, which require explicit ID wiring per the accessibility docs. In code reviews, prefer using fuselage-forms wrappers for form fields and verify there is no unnecessary manual ID/aria wiring in files that use these wrappers. If a component uses plain fuselage components, ensure proper id wiring as per docs.

Applied to files:

  • apps/meteor/server/lib/authorization/hasPermission.ts
  • packages/core-services/src/types/IAuthorization.ts
🔇 Additional comments (1)
apps/meteor/server/lib/authorization/hasPermission.ts (1)

5-18: LGTM!

@ggazzo ggazzo added the stat: QA assured Means it has been tested and approved by a company insider label Jul 13, 2026
@dionisio-bot dionisio-bot Bot added the stat: ready to merge PR tested and approved waiting for merge label Jul 13, 2026
@dionisio-bot dionisio-bot Bot added this pull request to the merge queue Jul 13, 2026
@ggazzo ggazzo removed this pull request from the merge queue due to a manual request Jul 13, 2026
@ggazzo ggazzo merged commit b9b2228 into develop Jul 13, 2026
45 checks passed
@ggazzo ggazzo deleted the chore/authz-haspermission-accept-user branch July 13, 2026 18:38
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 type: chore

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants