Skip to content

refactor(api): pass this.user to permission checks in REST endpoints - #41367

Merged
ggazzo merged 2 commits into
developfrom
chore/authz-rest-this-user
Jul 16, 2026
Merged

refactor(api): pass this.user to permission checks in REST endpoints#41367
ggazzo merged 2 commits into
developfrom
chore/authz-rest-this-user

Conversation

@ggazzo

@ggazzo ggazzo commented Jul 14, 2026

Copy link
Copy Markdown
Member

What

REST endpoints run with this.user already loaded via getDefaultUserFields() — which includes roles (apps/meteor/app/utils/server/functions/getBaseUserFields.ts). So hasPermissionAsync(this.userId, …) forces a redundant Users.findOneById inside the check, when the full user is already in hand.

This swaps this.userIdthis.user in the permission helpers (hasPermissionAsync / hasAllPermissionAsync / hasAtLeastOnePermissionAsync and the Authorization.hasPermission* variants) across the v1 + EE API endpoints — one fewer DB round-trip per permission check on these hot paths.

Scope

~20 files under server/api/v1 and ee/server/api (channels, teams, users, groups, rooms, chat, settings, e2e, roles, oauthapps, omnichannel/*, licenses, ldap, …).

Safety

this.user carries roles at runtime AND is typed non-nullable IUser in the standard authenticated endpoint context, so each swap typechecks with no cast. Where the endpoint context types this.user as optional (anonymous-capable route, e.g. im.ts view-room-administration), the swap is left as this.userId — the type checker rejects the object form there, which is the safety gate. Every touched file was verified clean via diagnostics and prettier before pushing.

Not touched: custom-integration webhook API (integrations/server/api/api.ts) whose this.user population isn't the standard ApiClass; and sites whose in-scope user object is a rolesless projection.

Review in cubic

Task: ARCH-2252

Summary by CodeRabbit

  • Bug Fixes
    • Improved permission handling across messaging, channels, teams, users, settings, OAuth, LDAP, and livechat operations.
    • Authorization checks now consistently evaluate permissions using the full authenticated user context, helping ensure restricted actions and data are granted/denied correctly.
    • Existing access-denied behavior and API responses remain unchanged.

@dionisio-bot

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

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: a5ba182

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

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

This change updates API authorization calls to pass the authenticated user object (this.user) instead of the user id (this.userId) across Enterprise, channel, team, omnichannel, messaging, room, settings, and user-management routes.

Changes

Authorization principal updates

Layer / File(s) Summary
Enterprise permission routes
apps/meteor/ee/server/api/*.ts, apps/meteor/ee/server/api/v1/omnichannel/*
LDAP, license, role, unit, and livechat room checks now pass this.user to permission helpers.
Channel, group, and team routes
apps/meteor/server/api/v1/channels.ts, groups.ts, teams.ts
Channel, group, and team authorization checks use the authenticated user object.
Omnichannel permission routes
apps/meteor/server/api/v1/omnichannel/*
Agent, department, room, and livechat user checks use this.user.
Messaging and room authorization
apps/meteor/server/api/v1/chat.ts, e2e.ts, im.ts, oauthapps.ts, roles.ts, rooms.ts, settings.ts
Messaging, room, OAuth app, role, and settings permission checks pass this.user.
User management authorization
apps/meteor/server/api/v1/users.ts
Profile, visibility, key reset, team, logout, and status checks use this.user.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

Suggested labels: type: chore

Suggested reviewers: sampaiodiego, kevlehman

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: switching REST API permission checks to use this.user.

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • ARCH-2252: 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 14, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 59.18367% with 20 lines in your changes missing coverage. Please review.
✅ Project coverage is 68.44%. Comparing base (7720156) to head (a5ba182).
⚠️ Report is 2 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop   #41367      +/-   ##
===========================================
- Coverage    68.44%   68.44%   -0.01%     
===========================================
  Files         4092     4092              
  Lines       158213   158212       -1     
  Branches     28645    28682      +37     
===========================================
- Hits        108288   108281       -7     
- Misses       44890    44905      +15     
+ Partials      5035     5026       -9     
Flag Coverage Δ
e2e 59.21% <ø> (+0.03%) ⬆️
e2e-api 45.53% <59.18%> (+0.02%) ⬆️
unit 70.30% <ø> (-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.

REST endpoints already load `this.user` with getDefaultUserFields (which
includes `roles`), so passing it to the permission helpers instead of
`this.userId` skips an extra Users.findOneById per check on these hot paths.

Swapped `hasPermissionAsync(this.userId, …)` (and the hasAll/hasAtLeastOne
and Authorization.hasPermission variants) to pass `this.user` across the v1
and EE API endpoints where `this.user` is a non-nullable IUser in scope.

Left as `this.userId` where the endpoint context types `this.user` as
optional (e.g. im.ts view-room-administration) — the type checker gates those.
@ggazzo
ggazzo force-pushed the chore/authz-rest-this-user branch from ff2daea to 1dbe136 Compare July 14, 2026 16:10
@ggazzo

ggazzo commented Jul 14, 2026

Copy link
Copy Markdown
Member Author

/jira ARCH-1464

@ggazzo ggazzo modified the milestones: 8.8.0, 8.7.0 Jul 14, 2026
@ggazzo
ggazzo marked this pull request as ready for review July 14, 2026 16:35
@ggazzo
ggazzo requested a review from a team as a code owner July 14, 2026 16:35
KevLehman
KevLehman previously approved these changes Jul 14, 2026

@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.

1 issue found across 21 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="apps/meteor/server/api/v1/teams.ts">

<violation number="1" location="apps/meteor/server/api/v1/teams.ts:134">
P3: Permission checks now stringify the entire authenticated user to build the roles-cache key, including unrelated settings/custom fields and service data, on every call. Normalize object inputs to `{ _id, roles }` in `hasPermissionAsync`/related wrappers so hot-path cache-key work stays bounded to permission data.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

const { name, type, members, room, owner } = this.bodyParams;

if (room?.id && !(await hasAllPermissionAsync(this.userId, ['create-team', 'edit-room'], room.id))) {
if (room?.id && !(await hasAllPermissionAsync(this.user, ['create-team', 'edit-room'], room.id))) {

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.

P3: Permission checks now stringify the entire authenticated user to build the roles-cache key, including unrelated settings/custom fields and service data, on every call. Normalize object inputs to { _id, roles } in hasPermissionAsync/related wrappers so hot-path cache-key work stays bounded to permission data.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/meteor/server/api/v1/teams.ts, line 134:

<comment>Permission checks now stringify the entire authenticated user to build the roles-cache key, including unrelated settings/custom fields and service data, on every call. Normalize object inputs to `{ _id, roles }` in `hasPermissionAsync`/related wrappers so hot-path cache-key work stays bounded to permission data.</comment>

<file context>
@@ -131,7 +131,7 @@ const teamsEndpoints = API.v1
 			const { name, type, members, room, owner } = this.bodyParams;
 
-			if (room?.id && !(await hasAllPermissionAsync(this.userId, ['create-team', 'edit-room'], room.id))) {
+			if (room?.id && !(await hasAllPermissionAsync(this.user, ['create-team', 'edit-room'], room.id))) {
 				return API.v1.forbidden();
 			}
</file context>

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.

This is handled by #41371 (already merged): getRolesCached no longer stringifies the whole user — the cache key is now ${_id}/${scope} for string ids and ${_id}/${scope}/${JSON.stringify(roles)} for objects (just the roles array), and object-without-scope bypasses the cache entirely via resolveRoles. So the hot-path cache-key work is bounded to permission data.

@ggazzo ggazzo added the stat: QA assured Means it has been tested and approved by a company insider label Jul 14, 2026
@dionisio-bot dionisio-bot Bot added the stat: ready to merge PR tested and approved waiting for merge label Jul 14, 2026
@ggazzo
ggazzo requested a review from a team as a code owner July 16, 2026 01:48
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