Skip to content

refactor(authorization): forward only { _id, roles } from hasPermission wrappers - #41413

Merged
ggazzo merged 1 commit into
developfrom
chore/authz-minimal-subject-wrappers
Jul 16, 2026
Merged

refactor(authorization): forward only { _id, roles } from hasPermission wrappers#41413
ggazzo merged 1 commit into
developfrom
chore/authz-minimal-subject-wrappers

Conversation

@ggazzo

@ggazzo ggazzo commented Jul 16, 2026

Copy link
Copy Markdown
Member

Why

Follow-up to the permission-check migration (#41346, #41367) — the systemic part of the P2 review finding. The hasPermissionAsync family accepts a full user object so callers can skip an internal Users.findOneById, but only _id and roles are ever consumed by the check. Passing the whole IUser means credential-bearing fields (services, e2e.private_key, custom fields, settings…) are serialized to the authorization service whenever it runs out of process (e.g. ee/apps/authorization-service).

Change

server/lib/authorization/hasPermission.ts: normalize object inputs to a minimal { _id, roles } subject before calling Authorization.*. String ids pass through unchanged. Behavior-preserving — the check already reads only _id/roles.

const toSubject = (user) => (typeof user === 'string' ? user : { _id: user._id, roles: user.roles });

Effect

Direct Authorization.hasPermission callers outside these wrappers (already minimal: FederationMatrix passes { _id, roles }; room/service and canAccessRoom pass an id) are unaffected.

Review in cubic

Task: ARCH-2260

Summary by CodeRabbit

  • Bug Fixes
    • Improved permission checks by using only the account identity and applicable roles when evaluating access.
    • Reduced unnecessary account data passed during authorization, resulting in more consistent and focused access decisions.

…on wrappers

The `hasPermissionAsync` / `hasAllPermissionAsync` / `hasAtLeastOnePermissionAsync`
helpers accept a full user object but only `_id` and `roles` are ever used by the
check. Passing the whole document means credential-bearing fields (`services`,
`e2e.private_key`, …) get serialized to the authorization service when it runs
out of process. Normalize object inputs to a minimal `{ _id, roles }` subject
before the call; string ids pass through unchanged.
@dionisio-bot

dionisio-bot Bot commented Jul 16, 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 16, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 92a6905

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 16, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c9532e7a-9ed3-4fae-8e42-a0302d08a91a

📥 Commits

Reviewing files that changed from the base of the PR and between cff23f9 and 92a6905.

📒 Files selected for processing (1)
  • apps/meteor/server/lib/authorization/hasPermission.ts
📜 Recent review details
⏰ Context from checks skipped due to timeout. (7)
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: Hacktron Security Check
  • GitHub Check: 🔨 Test API Livechat (EE) / MongoDB 8.0 coverage (1/1)
  • GitHub Check: 🔨 Test UI (CE) / MongoDB 8.0 (4/4)
  • GitHub Check: 🔨 Test UI (CE) / MongoDB 8.0 (2/4)
  • GitHub Check: 🔨 Test API Apps (node-runtime - EE) / MongoDB 8.0 coverage (1/1)
  • GitHub Check: 🔨 Test Federation Matrix
🧰 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
🧠 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
📚 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
📚 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

Walkthrough

Permission-check helpers now convert user inputs into reduced authorization subjects containing _id and, when available, roles before invoking authorization checks.

Changes

Authorization subject narrowing

Layer / File(s) Summary
Reduce permission-check subjects
apps/meteor/server/lib/authorization/hasPermission.ts
Adds toSubject and updates all three asynchronous permission helpers to pass only _id and optional roles to Authorization.

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

Possibly related PRs

Suggested labels: type: chore

Suggested reviewers: sampaiodiego, kevlehman

🚥 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 summarizes the main change: the permission wrappers now forward only {_id, roles} to authorization.
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-2260: 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.

@codecov

codecov Bot commented Jul 16, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 68.46%. Comparing base (cff23f9) to head (92a6905).

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop   #41413      +/-   ##
===========================================
- Coverage    68.48%   68.46%   -0.03%     
===========================================
  Files         4092     4092              
  Lines       158216   158218       +2     
  Branches     28678    28650      -28     
===========================================
- Hits        108351   108317      -34     
- Misses       44827    44869      +42     
+ Partials      5038     5032       -6     
Flag Coverage Δ
e2e 59.18% <ø> (-0.11%) ⬇️
e2e-api 45.75% <100.00%> (+0.25%) ⬆️
unit 70.31% <20.00%> (-0.03%) ⬇️

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 added this to the 8.7.0 milestone Jul 16, 2026
@ggazzo

ggazzo commented Jul 16, 2026

Copy link
Copy Markdown
Member Author

/jira ARCH-1464

@ggazzo
ggazzo marked this pull request as ready for review July 16, 2026 12:51
@ggazzo
ggazzo requested a review from a team as a code owner July 16, 2026 12:51

@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 1 file

Re-trigger cubic

@hacktron-app hacktron-app Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

1 issue found across 1 file

Severity Count
MEDIUM 1

View full scan results

Comment on lines +7 to +8
const toSubject = (user: IUser['_id'] | UserWithRoles): IUser['_id'] | UserWithRoles =>
typeof user === 'string' ? user : { _id: user._id, roles: user.roles };

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

MEDIUM Unhandled TypeError / Denial of Service via null/undefined user in permission checks

The helper function toSubject in apps/meteor/server/lib/authorization/hasPermission.ts converts a user object or user ID into a subject representation for permission checks. However, it does not check if the user argument is null or undefined. If user is null or undefined (e.g., when a user is unauthenticated or when a database lookup fails), typeof user === 'string' evaluates to false. The function then attempts to evaluate { _id: user._id, roles: user.roles }, which throws a TypeError: Cannot read properties of null (reading '_id') or TypeError: Cannot read properties of undefined (reading '_id'). Previously, passing null or undefined to permission check functions like hasPermissionAsync was safe because the downstream Authorization service explicitly checked if (!userId) { return false; }. Introducing toSubject without a null/undefined check causes unhandled exceptions (500 errors) in calling contexts, leading to Denial of Service or broken application flows for anonymous/guest access.

Steps to Reproduce
  1. Invoke any Meteor method or API endpoint that performs a permission check using hasPermissionAsync(userId, ...) or hasAllPermissionAsync(userId, ...) while unauthenticated (where userId is null or undefined).
  2. The helper function toSubject will fail to handle the null or undefined value, throwing a TypeError: Cannot read properties of null (reading '_id').
  3. This unhandled exception crashes the execution context of the request, returning a 500 Internal Server Error instead of gracefully returning false.
Fix with AI

Open in Cursor Open in Claude

A security vulnerability was found by Hacktron.

File: apps/meteor/server/lib/authorization/hasPermission.ts
Lines: 7-8
Severity: medium

Vulnerability: Unhandled TypeError / Denial of Service via null/undefined user in permission checks

Description:
The helper function `toSubject` in `apps/meteor/server/lib/authorization/hasPermission.ts` converts a user object or user ID into a subject representation for permission checks. However, it does not check if the `user` argument is null or undefined. If `user` is null or undefined (e.g., when a user is unauthenticated or when a database lookup fails), `typeof user === 'string'` evaluates to `false`. The function then attempts to evaluate `{ _id: user._id, roles: user.roles }`, which throws a `TypeError: Cannot read properties of null (reading '_id')` or `TypeError: Cannot read properties of undefined (reading '_id')`. Previously, passing `null` or `undefined` to permission check functions like `hasPermissionAsync` was safe because the downstream `Authorization` service explicitly checked `if (!userId) { return false; }`. Introducing `toSubject` without a null/undefined check causes unhandled exceptions (500 errors) in calling contexts, leading to Denial of Service or broken application flows for anonymous/guest access.

Proof of Concept:
**Steps to Reproduce**

1. Invoke any Meteor method or API endpoint that performs a permission check using `hasPermissionAsync(userId, ...)` or `hasAllPermissionAsync(userId, ...)` while unauthenticated (where `userId` is `null` or `undefined`).
2. The helper function `toSubject` will fail to handle the `null` or `undefined` value, throwing a `TypeError: Cannot read properties of null (reading '_id')`.
3. This unhandled exception crashes the execution context of the request, returning a 500 Internal Server Error instead of gracefully returning `false`.

Affected Code:
const toSubject = (user: IUser['_id'] | UserWithRoles): IUser['_id'] | UserWithRoles =>
	typeof user === 'string' ? user : { _id: user._id, roles: user.roles };

Acceptance criteria:
- Acceptance is defined by the **actual reported behavior**, not by tests passing.
- Reproduce the issue, or narrow the exact code path that produces it, *before* changing code. State what you confirmed.
- Fix the underlying cause. Mitigations that paper over the reported behavior do not count as a fix.
- Add a regression test that fails on the unpatched code and passes on the fix. If a regression test is genuinely impractical (e.g. race condition, infra-level issue), say so and explain why.
- Existing tests passing is **not** the bar. Do not declare done on tests-pass theatre.

Only change what is necessary to fix this vulnerability. Do not refactor adjacent code or modify unrelated files.

Triage: Reply !fp <reason> (false positive), !valid (confirmed), !accepted_risk <reason>, or !fixed (resolved). Any other reply is saved as a triage note.
Reason is optional but improves future scans — e.g. !fp internal endpoint, not user-facing.

View finding in Hacktron

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

!fp there is no away to have undefined at that point

@ggazzo ggazzo added the stat: QA assured Means it has been tested and approved by a company insider label Jul 16, 2026
@dionisio-bot dionisio-bot Bot added the stat: ready to merge PR tested and approved waiting for merge label Jul 16, 2026
@ggazzo
ggazzo merged commit ae72939 into develop Jul 16, 2026
48 checks passed
@ggazzo
ggazzo deleted the chore/authz-minimal-subject-wrappers branch July 16, 2026 14:32
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.

3 participants