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,63 @@
import type { IUser } from '@rocket.chat/core-typings';
import { Rooms, Users } from '@rocket.chat/models';
import { pick } from '@rocket.chat/tools';
import { Accounts } from 'meteor/accounts-base';
import { logger } from './logger';
import { createRoom } from '../rooms/createRoom';
type CASUserOptions = {
attributes: Record<string, string | undefined>;
casVersion: number;
flagEmailAsVerified: boolean;
};
export const createNewUser = async (username: string, { attributes, casVersion, flagEmailAsVerified }: CASUserOptions): Promise<IUser> => {
// Define new user
const newUser = {
username: attributes.username || username,
active: true,
globalRoles: ['user'],
emails: [attributes.email]
.filter((e) => e)
.map((address) => ({
address,
verified: flagEmailAsVerified,
})),
services: {
cas: {
external_id: username,
version: casVersion,
attrs: attributes,
},
},
...pick(attributes, 'name'),
};
// Create the user
logger.debug({ msg: 'User does not exist yet, creating it', username });
const userId = await Accounts.insertUserDoc({}, newUser);
// Fetch and use it
const user = await Users.findOneById(userId);
if (!user) {
throw new Error('Unexpected error: Unable to find user after its creation.');
}
logger.debug({ msg: 'Created new user', username, userId: user._id });
logger.debug({ msg: 'Joining user to attribute channels', rooms: attributes.rooms });
if (attributes.rooms) {
const roomNames = attributes.rooms.split(',');
for await (const roomName of roomNames) {
if (roomName) {
let room = await Rooms.findOneByNameAndType(roomName, 'c');
if (!room) {
room = await createRoom('c', roomName, user);
}
}
}
}
return user;
};

View File

@@ -0,0 +1,21 @@
import type { IUser } from '@rocket.chat/core-typings';
import { Users } from '@rocket.chat/models';
import { settings } from '../../settings';
export const findExistingCASUser = async (username: string): Promise<IUser | undefined> => {
const casUser = await Users.findOne({ 'services.cas.external_id': username });
if (casUser) {
return casUser;
}
if (!settings.get<boolean>('CAS_trust_username')) {
return;
}
// If that user was not found, check if there's any Rocket.Chat user with that username
// With this, CAS login will continue to work if the user is renamed on both sides and also if the user is renamed only on Rocket.Chat.
// It'll also allow non-CAS users to switch to CAS based login
// Update the user's external_id to reflect this new username.
return (await Users.setCasExternalIdByUsername(username)) ?? undefined;
};

View File

@@ -0,0 +1,3 @@
import { Logger } from '@rocket.chat/logger';
export const logger = new Logger('CAS');

View File

@@ -0,0 +1,60 @@
import { expect } from 'chai';
import { describe, it, beforeEach } from 'mocha';
import proxyquire from 'proxyquire';
import sinon from 'sinon';
const removeNotExpiredById = sinon.stub().resolves(null);
const findExistingCASUser = sinon.stub().resolves(null);
const settingsGet = sinon.stub().returns(true);
const { loginHandlerCAS: handler } = proxyquire.noCallThru().load('./loginHandler', {
'@rocket.chat/models': {
CredentialTokens: { removeNotExpiredById },
Users: { updateOne: sinon.stub().resolves() },
},
'meteor/accounts-base': {
Accounts: {
LoginCancelledError: { numericError: 403 },
},
},
'meteor/meteor': {
Meteor: { Error },
},
'./createNewUser': { createNewUser: sinon.stub().resolves({ _id: 'newUserId' }) },
'./findExistingCASUser': { findExistingCASUser },
'./logger': { logger: { debug: sinon.stub(), error: sinon.stub() } },
'../users/setRealName': { setRealName: sinon.stub().resolves() },
'../../settings': { settings: { get: settingsGet } },
});
describe('loginHandlerCAS', () => {
beforeEach(() => {
removeNotExpiredById.reset();
removeNotExpiredById.resolves(null);
findExistingCASUser.reset();
settingsGet.reset();
settingsGet.returns(true);
});
it('should reject non-string credentialToken and never query the database (NoSQL injection prevention)', async () => {
expect(await handler({ cas: { credentialToken: { $gt: '' } } })).to.be.undefined;
expect(await handler({ cas: { credentialToken: { $ne: null } } })).to.be.undefined;
expect(await handler({ cas: { credentialToken: 123 } })).to.be.undefined;
expect(await handler({ cas: { credentialToken: ['a'] } })).to.be.undefined;
expect(await handler({ cas: { credentialToken: null } })).to.be.undefined;
expect(removeNotExpiredById.called).to.be.false;
});
it('should consume the credential token and reject when no matching login attempt is found', async () => {
await expect(handler({ cas: { credentialToken: 'valid-token' } })).to.be.rejected;
expect(removeNotExpiredById.calledOnceWith('valid-token')).to.be.true;
});
it('should return undefined when CAS is disabled', async () => {
settingsGet.returns(false);
expect(await handler({ cas: { credentialToken: 'valid-token' } })).to.be.undefined;
expect(removeNotExpiredById.called).to.be.false;
});
});

View File

@@ -0,0 +1,121 @@
import { CredentialTokens, Users } from '@rocket.chat/models';
import { getObjectKeys, wrapExceptions } from '@rocket.chat/tools';
import { Accounts } from 'meteor/accounts-base';
import { Meteor } from 'meteor/meteor';
import { createNewUser } from './createNewUser';
import { findExistingCASUser } from './findExistingCASUser';
import { logger } from './logger';
import { settings } from '../../settings';
import { setRealName } from '../users/setRealName';
export const loginHandlerCAS = async (options: any): Promise<undefined | Accounts.LoginMethodResult> => {
if (!settings.get('CAS_enabled') || !options.cas || typeof options.cas.credentialToken !== 'string') {
return undefined;
}
const credentials = await CredentialTokens.removeNotExpiredById(options.cas.credentialToken);
if (credentials === undefined || credentials === null) {
throw new Meteor.Error(Accounts.LoginCancelledError.numericError, 'no matching login attempt found');
}
const result = credentials.userInfo;
const syncUserDataFieldMap = settings.get<string>('CAS_Sync_User_Data_FieldMap').trim();
const casVersion = parseFloat(settings.get('CAS_version') ?? '1.0');
const syncEnabled = settings.get('CAS_Sync_User_Data_Enabled');
const flagEmailAsVerified = settings.get<boolean>('Accounts_Verify_Email_For_External_Accounts');
const userCreationEnabled = settings.get('CAS_Creation_User_Enabled');
const { username, attributes: credentialsAttributes } = result as { username: string; attributes: Record<string, string[]> };
// We have these
const externalAttributes: Record<string, string> = {
username,
};
// We need these
const internalAttributes: Record<string, string | undefined> = {
email: undefined,
name: undefined,
username: undefined,
rooms: undefined,
};
// Import response attributes
if (casVersion >= 2.0) {
// Clean & import external attributes
for await (const [externalName, value] of Object.entries(credentialsAttributes)) {
if (value) {
externalAttributes[externalName] = value[0];
}
}
}
// Source internal attributes
if (syncUserDataFieldMap) {
// Our mapping table: key(int_attr) -> value(ext_attr)
// Spoken: Source this internal attribute from these external attributes
const attributeMap = wrapExceptions(() => JSON.parse(syncUserDataFieldMap) as Record<string, any>).catch((err) => {
logger.error({ msg: 'Invalid JSON for attribute mapping', err });
throw err;
});
for await (const [internalName, source] of Object.entries(attributeMap)) {
if (!source || typeof source.valueOf() !== 'string') {
continue;
}
let replacedValue = source as string;
for await (const externalName of getObjectKeys(externalAttributes)) {
replacedValue = replacedValue.replace(`%${externalName}%`, externalAttributes[externalName]);
}
if (source !== replacedValue) {
internalAttributes[internalName] = replacedValue;
logger.debug({ msg: 'Sourced internal attribute', internalName, value: replacedValue });
} else {
logger.debug({ msg: 'Sourced internal attribute skipped', internalName });
}
}
}
// Search existing user by its external service id
logger.debug({ msg: 'Looking up user by id', username });
// First, look for a user that has logged in from CAS with this username before
const user = await findExistingCASUser(username);
if (user) {
logger.debug({ msg: 'Using existing user', username, userId: user._id });
if (syncEnabled) {
logger.debug('Syncing user attributes');
// Update name
if (internalAttributes.name) {
await setRealName(user._id, internalAttributes.name);
}
// Update email
if (internalAttributes.email) {
await Users.updateOne(
{ _id: user._id },
{ $set: { emails: [{ address: internalAttributes.email, verified: flagEmailAsVerified }] } },
);
}
}
return { userId: user._id };
}
if (!userCreationEnabled) {
// Should fail as no user exist and can't be created
logger.debug({ msg: 'User does not exist yet, will fail as no user creation is enabled', username });
throw new Meteor.Error(Accounts.LoginCancelledError.numericError, 'no matching user account found');
}
const newUser = await createNewUser(username, {
attributes: internalAttributes,
casVersion,
flagEmailAsVerified,
});
return { userId: newUser._id };
};

View File

@@ -0,0 +1,98 @@
import type { IncomingMessage, ServerResponse } from 'node:http';
import url from 'node:url';
import { validate } from '@rocket.chat/cas-validate';
import type { ICredentialToken, RequiredField } from '@rocket.chat/core-typings';
import { CredentialTokens } from '@rocket.chat/models';
import { Meteor } from 'meteor/meteor';
import _ from 'underscore';
import { logger } from './logger';
import { settings } from '../../settings';
const closePopup = function (res: ServerResponse): void {
res.writeHead(200, { 'Content-Type': 'text/html' });
const content = '<html><head><script>window.close()</script></head></html>';
res.end(content, 'utf-8');
};
type IncomingMessageWithUrl = RequiredField<IncomingMessage, 'url'>;
const casTicket = function (req: IncomingMessageWithUrl, token: string, callback: () => void): void {
// get configuration
if (!settings.get('CAS_enabled')) {
logger.error('Got ticket validation request, but CAS is not enabled');
callback();
}
// get ticket and validate.
const parsedUrl = url.parse(req.url, true);
const ticketId = parsedUrl.query.ticket as string;
const baseUrl = settings.get<string>('CAS_base_url');
const version = parseFloat(settings.get('CAS_version') ?? '1.0') as 1.0 | 2.0;
const appUrl = Meteor.absoluteUrl().replace(/\/$/, '') + __meteor_runtime_config__.ROOT_URL_PATH_PREFIX;
logger.debug({ msg: 'Using CAS_base_url', baseUrl });
validate(
{
base_url: baseUrl,
version,
service: `${appUrl}/_cas/${token}`,
},
ticketId,
async (err, status, username, details) => {
if (err) {
logger.error({ msg: 'error when trying to validate', err });
} else if (status) {
logger.info({ msg: 'Validated user', username });
const userInfo: Partial<ICredentialToken['userInfo']> = { username: username as string };
// CAS 2.0 attributes handling
if (details?.attributes) {
_.extend(userInfo, { attributes: details.attributes });
}
await CredentialTokens.create(token, userInfo);
} else {
logger.error({ msg: 'Unable to validate ticket', ticketId });
}
// logger.debug("Received response: " + JSON.stringify(details, null , 4));
callback();
},
);
};
export const middlewareCAS = function (req: IncomingMessage, res: ServerResponse, next: (err?: any) => void) {
// Make sure to catch any exceptions because otherwise we'd crash
// the runner
try {
if (!req.url) {
throw new Error('Invalid request url');
}
const barePath = req.url.substring(0, req.url.indexOf('?'));
const splitPath = barePath.split('/');
// Any non-cas request will continue down the default
// middlewares.
if (splitPath[1] !== '_cas') {
next();
return;
}
// get auth token
const credentialToken = splitPath[2];
if (!credentialToken) {
closePopup(res);
return;
}
// validate ticket
casTicket(req as IncomingMessageWithUrl, credentialToken, () => {
closePopup(res);
});
} catch (err) {
logger.error({ msg: 'Unexpected error', err });
closePopup(res);
}
};

View File

@@ -0,0 +1,30 @@
import type { LoginServiceConfiguration } from '@rocket.chat/core-typings';
import { ServiceConfiguration } from 'meteor/service-configuration';
import { logger } from './logger';
import { settings } from '../../settings/cached';
export async function updateCasServices(): Promise<void> {
const data: Partial<LoginServiceConfiguration> = {
// These will pe passed to 'node-cas' as options
enabled: settings.get('CAS_enabled'),
base_url: settings.get('CAS_base_url'),
login_url: settings.get('CAS_login_url'),
// Rocketchat Visuals
buttonLabelText: settings.get('CAS_button_label_text'),
buttonLabelColor: settings.get('CAS_button_label_color'),
buttonColor: settings.get('CAS_button_color'),
width: settings.get('CAS_popup_width'),
height: settings.get('CAS_popup_height'),
autoclose: settings.get('CAS_autoclose'),
};
// Either register or deregister the CAS login service based upon its configuration
if (data.enabled) {
logger.info('Enabling CAS login service');
await ServiceConfiguration.configurations.upsertAsync({ service: 'cas' }, { $set: data });
} else {
logger.info('Disabling CAS login service');
await ServiceConfiguration.configurations.removeAsync({ service: 'cas' });
}
}