snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s

This commit is contained in:
upstream-mirror
2026-09-16 01:21:02 +05:00
commit 30810eecd7
10161 changed files with 987110 additions and 0 deletions

View File

@@ -0,0 +1,139 @@
import { Authorization, License, Abac, Settings } from '@rocket.chat/core-services';
import type { RoomAccessValidator } from '@rocket.chat/core-services';
import { TeamType, AbacAccessOperation, AbacObjectType } from '@rocket.chat/core-typings';
import type { IUser, ITeam, IRoom } from '@rocket.chat/core-typings';
import { Subscriptions, Rooms, TeamMember, Team, Users } from '@rocket.chat/models';
import { canAccessRoomLivechat } from './canAccessRoomLivechat';
async function canAccessPublicRoom(user?: IUser): Promise<boolean> {
if (!user?._id) {
const anon = await Settings.get<boolean>('Accounts_AllowAnonymousRead');
return !!anon;
}
return Authorization.hasPermission(user, 'view-c-room');
}
type RoomAccessValidatorConverted = (
room?: Pick<IRoom, '_id' | 't' | 'teamId' | 'prid' | 'abacAttributes'>,
user?: IUser,
extraData?: Record<string, any>,
) => Promise<boolean>;
const roomAccessValidators: RoomAccessValidatorConverted[] = [
async function _validateAccessToPublicRoomsInTeams(room, user): Promise<boolean> {
if (!room) {
return false;
}
if (!room._id || !room.teamId || room.t !== 'c') {
// if the room doesn't belongs to a team || is not a public channel - skip
return false;
}
// if user is banned from this room, deny access
if (user?._id && (await Subscriptions.findOneBannedSubscription(room._id, user._id))) {
return false;
}
// if team is public, access is allowed if the user can access public rooms
const team = await Team.findOneById<Pick<ITeam, 'type'>>(room.teamId, {
projection: { type: 1 },
});
if (team?.type === TeamType.PUBLIC) {
return canAccessPublicRoom(user);
}
// otherwise access is allowed only to members of the team
const membership =
user?._id &&
(await TeamMember.findOneByUserIdAndTeamId(user._id, room.teamId, {
projection: { _id: 1 },
}));
return !!membership;
},
async function _validateAccessToPublicRooms(room, user): Promise<boolean> {
if (!room?._id || room.t !== 'c' || room?.teamId) {
return false;
}
// if user is banned from this room, deny access
if (user?._id && (await Subscriptions.findOneBannedSubscription(room._id, user._id))) {
return false;
}
return canAccessPublicRoom(user);
},
async function _validateIfAlreadyJoined(room, user, extraData): Promise<boolean> {
if (!room?._id || !user?._id) {
return false;
}
const [canViewJoined, canViewT] = await Promise.all([
Authorization.hasPermission(user, 'view-joined-room'),
Authorization.hasPermission(user, `view-${room.t}-room`),
]);
// When there's no ABAC setting, license or values on the room, fallback to previous behavior
if (!room?.abacAttributes?.length || !(await License.hasModule('abac')) || !(await Settings.get<boolean>('ABAC_Enabled'))) {
const includeInvitations = extraData?.includeInvitations ?? false;
if (!(await Subscriptions.countByRoomIdAndUserId(room._id, user._id, includeInvitations))) {
return false;
}
return canViewJoined || canViewT;
}
return (canViewJoined || canViewT) && Abac.canAccessObject(room, user, AbacAccessOperation.READ, AbacObjectType.ROOM);
},
async function _validateAccessToDiscussionsParentRoom(room, user): Promise<boolean> {
if (!room?.prid) {
return false;
}
const parentRoom = await Rooms.findOneById(room.prid);
if (!parentRoom) {
return false;
}
return Authorization.canAccessRoom(parentRoom, user);
},
canAccessRoomLivechat,
];
export const isPartialUser = (user: IUser | Pick<IUser, '_id'> | undefined): user is Pick<IUser, '_id'> => {
return Boolean(user && Object.keys(user).length === 1 && user._id);
};
export const canAccessRoom: RoomAccessValidator = async (room, user, extraData): Promise<boolean> => {
// TODO livechat can send both as null, so they we need to validate nevertheless
// if (!room || !user) {
// return false;
// }
// TODO: remove this after migrations
// if user only contains _id, convert it to a full IUser object
if (isPartialUser(user)) {
user = (await Users.findOneById(user._id)) || undefined;
if (!user) {
throw new Error('User not found');
}
if (process.env.NODE_ENV === 'development') {
console.log('User converted to full IUser object');
}
}
for await (const roomAccessValidator of roomAccessValidators) {
if (await roomAccessValidator(room, user as IUser, extraData)) {
return true;
}
}
return false;
};

View File

@@ -0,0 +1,31 @@
import type { IAuthorizationLivechat, RoomAccessValidator } from '@rocket.chat/core-services';
import { proxify } from '@rocket.chat/core-services';
import type { IOmnichannelRoom } from '@rocket.chat/core-typings';
import { Rooms } from '@rocket.chat/models';
const AuthorizationLivechat = proxify<IAuthorizationLivechat>('authorization-livechat');
export const canAccessRoomLivechat: RoomAccessValidator = async (room, user, extraData): Promise<boolean> => {
// If we received a partial room and its type is not `l` or `v`, skip all checks.
if (room && room.t !== 'l') {
return false;
}
// if we received a partial room, load the full IOmnichannelRoom data for it
// Otherwise, try to load the data from the extraData (this is the case for file uploads)
const rid = room?._id || extraData?.rid;
const livechatRoom = rid && (await Rooms.findOneById(rid));
// if the roomId is invalid skip checks and fail
if (!livechatRoom) {
return false;
}
// Check the type again in case the room parameter was not received
if (livechatRoom.t !== 'l') {
return false;
}
// Call back core temporarily
return AuthorizationLivechat.canAccessRoom(livechatRoom as IOmnichannelRoom, user, extraData);
};

View File

@@ -0,0 +1,25 @@
import type { RoomAccessValidator } from '@rocket.chat/core-services';
import { Authorization } from '@rocket.chat/core-services';
import { Subscriptions, Users } from '@rocket.chat/models';
import { canAccessRoom, isPartialUser } from './canAccessRoom';
export const canReadRoom: RoomAccessValidator = async (...args) => {
const [room, user] = args;
const userArgument = isPartialUser(user) ? await Users.findOneById(user._id) : user;
if (!(await canAccessRoom(...args))) {
return false;
}
if (
userArgument &&
room?.t === 'c' &&
!(await Authorization.hasPermission(userArgument, 'preview-c-room')) &&
!(await Subscriptions.findOneByRoomIdAndUserId(room?._id, userArgument._id, { projection: { _id: 1 } }))
) {
return false;
}
return true;
};

View File

@@ -0,0 +1,244 @@
import type { IAuthorization, RoomAccessValidator, UserWithRoles } from '@rocket.chat/core-services';
import { License, ServiceClass } from '@rocket.chat/core-services';
import type { IUser, IRole, IRoom, ISubscription } from '@rocket.chat/core-typings';
import { Subscriptions, Rooms, Users, Roles, Permissions } from '@rocket.chat/models';
import mem from 'mem';
import { canAccessRoom } from './canAccessRoom';
import { canReadRoom } from './canReadRoom';
import { AuthorizationUtils } from '../../../app/authorization/lib/AuthorizationUtils';
import './canAccessRoomLivechat';
// Register as class
export class Authorization extends ServiceClass implements IAuthorization {
protected name = 'authorization';
private getRolesCached = mem(this.getRoles.bind(this), {
maxAge: 1000,
cacheKey: (args: unknown[]) => {
const [user, scope] = args as [string | UserWithRoles, IRoom['_id']?];
return typeof user === 'string' ? `${user}/${scope ?? ''}` : `${user._id}/${scope ?? ''}/${JSON.stringify(user.roles ?? [])}`;
},
});
private rolesHasPermissionCached = mem(this.rolesHasPermission.bind(this), {
cacheKey: JSON.stringify,
...((process.env.TEST_MODE === 'true' || process.env.TEST_MODE === 'api') && { maxAge: 1 }),
});
constructor() {
super();
const clearCache = (): void => {
mem.clear(this.getRolesCached);
mem.clear(this.rolesHasPermissionCached);
};
this.onEvent('watch.roles', clearCache);
this.onEvent('permission.changed', clearCache);
this.onEvent('authorization.guestPermissions', (permissions: string[]) => {
AuthorizationUtils.addRolePermissionWhiteList('guest', permissions);
});
}
override async started(): Promise<void> {
try {
if (!(await License.hasValidLicense())) {
return;
}
const permissions = await License.getGuestPermissions();
if (!permissions) {
return;
}
AuthorizationUtils.addRolePermissionWhiteList('guest', permissions);
} catch (error) {
console.error('Authorization Service did not start correctly', error);
}
}
async hasAllPermission(userId: string | UserWithRoles, permissions: string[], scope?: string): Promise<boolean> {
if (!userId) {
return false;
}
return this.all(userId, permissions, scope);
}
async hasPermission(userId: string | UserWithRoles, permissionId: string, scope?: string): Promise<boolean> {
if (!userId) {
return false;
}
return this.all(userId, [permissionId], scope);
}
async hasAtLeastOnePermission(userId: string | UserWithRoles, permissions: string[], scope?: string): Promise<boolean> {
if (!userId) {
return false;
}
return this.atLeastOne(userId, permissions, scope);
}
async canAccessRoom(...args: Parameters<RoomAccessValidator>): Promise<boolean> {
return canAccessRoom(...args);
}
async canReadRoom(...args: Parameters<RoomAccessValidator>): Promise<boolean> {
return canReadRoom(...args);
}
async canAccessRoomId(rid: IRoom['_id'], user: IUser['_id']): Promise<boolean> {
const room = await Rooms.findOneById<Pick<IRoom, '_id' | 't' | 'teamId' | 'prid' | 'abacAttributes'>>(rid, {
projection: {
_id: 1,
t: 1,
teamId: 1,
prid: 1,
abacAttributes: 1,
},
});
if (!room) {
return false;
}
return this.canAccessRoom(room, { _id: user });
}
async canAccessRoomIds(rids: IRoom['_id'][], user: UserWithRoles): Promise<boolean> {
const uniqueRids = [...new Set(rids)];
if (!uniqueRids.length) {
return false;
}
if (!user) {
return false;
}
const rooms = await Rooms.findByIds<Pick<IRoom, '_id' | 't' | 'teamId' | 'prid' | 'abacAttributes'>>(uniqueRids, {
projection: {
_id: 1,
t: 1,
teamId: 1,
prid: 1,
abacAttributes: 1,
},
}).toArray();
if (rooms.length !== uniqueRids.length) {
return false;
}
const allowed = await Promise.all(rooms.map((room) => this.canAccessRoom(room, user)));
return allowed.every(Boolean);
}
async getUsersFromPublicRoles(): Promise<
{
_id: string;
username: string;
roles: string[];
}[]
> {
const roleIds = await this.getPublicRoles();
return this.getUserFromRoles(roleIds);
}
private getPublicRoles = mem(
async (): Promise<string[]> => {
const roles = Roles.find<Pick<IRole, '_id'>>({ scope: 'Users', description: { $exists: true, $ne: '' } }, { projection: { _id: 1 } });
return roles.map(({ _id }) => _id).toArray();
},
{ maxAge: 10000 },
);
private getUserFromRoles = mem(
async (roleIds: string[]) => {
const users = Users.findUsersInRoles<Pick<Required<IUser>, '_id' | 'username' | 'roles'>>(roleIds, null, {
sort: {
username: 1,
},
projection: {
_id: 1,
username: 1,
roles: 1,
},
});
return users
.map((user) => ({
...user,
roles: user.roles.filter((roleId: string) => roleIds.includes(roleId)),
}))
.toArray();
},
{ maxAge: 10000 },
);
private async rolesHasPermission(permission: string, roles: IRole['_id'][]): Promise<boolean> {
if (AuthorizationUtils.isPermissionRestrictedForRoleList(permission, roles)) {
return false;
}
const result = await Permissions.findOne({ _id: permission, roles: { $in: roles } }, { projection: { _id: 1 } });
return !!result;
}
private async getRoles(user: string | UserWithRoles, scope?: IRoom['_id']): Promise<string[]> {
const { roles: userRoles = [] } = typeof user === 'string' ? (await Users.findOneById(user, { projection: { roles: 1 } })) || {} : user;
const { roles: subscriptionsRoles = [] } =
(scope &&
(await Subscriptions.findOne<Pick<ISubscription, 'roles'>>(
{ 'rid': scope, 'u._id': typeof user === 'string' ? user : user._id },
{ projection: { roles: 1 } },
))) ||
{};
return [...userRoles, ...subscriptionsRoles].sort((a, b) => a.localeCompare(b));
}
private async resolveRoles(user: string | UserWithRoles, scope?: IRoom['_id']): Promise<string[]> {
if (typeof user !== 'string' && !scope) {
return [...(user.roles ?? [])].sort((a, b) => a.localeCompare(b));
}
return this.getRolesCached(user, scope);
}
private async atLeastOne(user: string | UserWithRoles, permissions: string[] = [], scope?: string): Promise<boolean> {
const sortedRoles = await this.resolveRoles(user, scope);
for await (const permission of permissions) {
if (await this.rolesHasPermissionCached(permission, sortedRoles)) {
return true;
}
}
return false;
}
private async all(user: string | UserWithRoles, permissions: string[] = [], scope?: string): Promise<boolean> {
const sortedRoles = await this.resolveRoles(user, scope);
for await (const permission of permissions) {
if (!(await this.rolesHasPermissionCached(permission, sortedRoles))) {
return false;
}
}
return true;
}
async hasAnyRole(userId: IUser['_id'], roleIds: IRole['_id'][], scope?: IRoom['_id']): Promise<boolean> {
if (!Array.isArray(roleIds)) {
throw new Error('error-invalid-arguments');
}
if (!userId) {
return false;
}
return Roles.isUserInRoles(userId, roleIds, scope);
}
}