Skip to content

Conversation

@MarcosSpessatto
Copy link
Contributor

@MarcosSpessatto MarcosSpessatto commented Apr 9, 2025

https://rocketchat.atlassian.net/browse/ARCH-1565

Proposed changes (including videos or screenshots)

Issue(s)

Steps to test or reproduce

Further comments


This pull request focuses on improving the token management system within the Rocket.Chat application. The changes involve the removal of indirect method calls for token management, specifically targeting the removal of other login tokens. Key updates include:

  1. Direct Function Call: In apps/meteor/app/api/server/v1/users.ts, the code now directly calls the removeOtherTokens function instead of using Meteor.callAsync, enhancing code maintainability by reducing indirection.

  2. New Function Implementation: A new function is introduced in apps/meteor/server/lib/removeOtherTokens.ts to remove non-login tokens, excluding the current one. However, this implementation currently lacks error handling and documentation.

  3. Security Enhancement: The apps/meteor/server/methods/saveUserProfile.ts file has been updated to import the new function and modify the token removal logic. This change improves security by directly removing other tokens rather than relying on a Meteor method.

  4. Interface Update: The packages/model-typings/src/models/IUsersModel.ts file now includes a new method, removeNonLoginTokensExcept, in the IUsersModel interface.

  5. Model Update: In packages/models/src/models/Users.ts, a new method has been added to remove non-login tokens except for a specified one, aligning with the interface update.

These changes collectively aim to streamline the token management process, enhance security, and improve code clarity within the Rocket.Chat application.

@MarcosSpessatto MarcosSpessatto added this to the 7.6.0 milestone Apr 9, 2025
@dionisio-bot
Copy link
Contributor

dionisio-bot bot commented Apr 9, 2025

Looks like this PR is not ready to merge, because of the following issues:

  • This PR is targeting the wrong base branch. It should target 7.7.0, but it targets 7.6.0

Please fix the issues and try again

If you have any trouble, please check the PR guidelines

@changeset-bot
Copy link

changeset-bot bot commented Apr 9, 2025

⚠️ No Changeset found

Latest commit: 66dcf2b

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

@github-actions
Copy link
Contributor

github-actions bot commented Apr 9, 2025

PR Preview Action v1.6.0

🚀 View preview at
https://RocketChat.github.io/Rocket.Chat/pr-preview/pr-35754/

Built to branch gh-pages at 2025-04-09 17:08 UTC.
Preview will be ready when the GitHub Pages deployment is complete.

@codecov
Copy link

codecov bot commented Apr 9, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 59.64%. Comparing base (87a1589) to head (3b2179d).
Report is 4 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff            @@
##           develop   #35754   +/-   ##
========================================
  Coverage    59.64%   59.64%           
========================================
  Files         2832     2832           
  Lines        68322    68322           
  Branches     15133    15133           
========================================
  Hits         40750    40750           
  Misses       24963    24963           
  Partials      2609     2609           
Flag Coverage Δ
unit 75.62% <ø> (ø)

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.

@MarcosSpessatto MarcosSpessatto marked this pull request as ready for review April 9, 2025 18:04
@MarcosSpessatto MarcosSpessatto requested review from a team as code owners April 9, 2025 18:04
@kody-ai
Copy link

kody-ai bot commented Apr 17, 2025

Code Review Completed! 🔥

The code review was successfully completed based on your current configurations.

Kody Guide: Usage and Configuration
Interacting with Kody
  • Request a Review: Ask Kody to review your PR manually by adding a comment with the @kody start-review command at the root of your PR.

  • Provide Feedback: Help Kody learn and improve by reacting to its comments with a 👍 for helpful suggestions or a 👎 if improvements are needed.

Current Kody Configuration
Review Options

The following review options are enabled or disabled:

Options Enabled
Security
Code Style
Kody Rules
Refactoring
Error Handling
Maintainability
Potential Issues
Documentation And Comments
Performance And Optimization
Breaking Changes

Access your configuration settings here.

Comment on lines +1327 to +1339
removeNonLoginTokensExcept(userId: IUser['_id'], authToken: string) {
return this.col.updateOne(
{
_id: userId,
},
{
$pull: {
'services.resume.loginTokens': {
hashedToken: { $ne: authToken },
},
},
},
);
Copy link

Choose a reason for hiding this comment

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

kody code-review Security high

removeNonLoginTokensExcept(userId: IUser['_id'], authToken: string) {
		if (!userId || !authToken || typeof authToken !== 'string' || authToken.trim() === '') {
			throw new Error('Invalid userId or authToken parameters');
		}
		return this.col.updateOne(
			{
				_id: userId,
			},
			{
				$pull: {
					'services.resume.loginTokens': {
						hashedToken: { $ne: authToken },
					},
				},
			},
		);
	}

The removeNonLoginTokensExcept method lacks validation for userId and authToken parameters, which could lead to security issues.

This issue appears in multiple locations:

  • packages/models/src/models/Users.ts: Lines 1327-1339
    Please add parameter validation to the removeNonLoginTokensExcept method to ensure userId and authToken are valid and non-empty strings.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

{
async post() {
return API.v1.success(await Meteor.callAsync('removeOtherTokens'));
return API.v1.success(await removeOtherTokens(this.userId, this.connection.id));
Copy link

Choose a reason for hiding this comment

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

kody code-review Error Handling high

try {
  const result = await removeOtherTokens(this.userId, this.connection.id);
  return API.v1.success(result);
} catch (error) {
  return API.v1.failure(error instanceof Error ? error.message : 'Unknown error occurred');
}

The removeOtherTokens function call lacks proper error handling, which could lead to unhandled exceptions and poor user experience.

This issue appears in multiple locations:

  • apps/meteor/app/api/server/v1/users.ts: Lines 1139-1139
    Please wrap the removeOtherTokens function call in a try-catch block to handle potential errors gracefully and provide meaningful error messages.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

Comment on lines +4 to +7
export const removeOtherTokens = async function (userId: string, connectionId: string): Promise<void> {
const currentToken = Accounts._getLoginToken(connectionId);

await Users.removeNonLoginTokensExcept(userId, currentToken);
Copy link

Choose a reason for hiding this comment

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

kody code-review Error Handling high

export const removeOtherTokens = async function (userId: string, connectionId: string): Promise<void> {
	try {
		const currentToken = Accounts._getLoginToken(connectionId);
		if (!currentToken) {
			throw new Error('No valid login token found');
		}
		await Users.removeNonLoginTokensExcept(userId, currentToken);
	} catch (error) {
		console.error(`Failed to remove tokens for user ${userId}:`, error);
		throw error;
	}
};

The removeOtherTokens function lacks error handling for token retrieval and removal operations, which could result in silent failures.

This issue appears in multiple locations:

  • apps/meteor/server/lib/removeOtherTokens.ts: Lines 4-7
    Please add try-catch blocks within the removeOtherTokens function to handle potential errors during token operations and log them appropriately.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.


removeNonPATLoginTokensExcept(userId: any, authToken: any): any;

removeNonLoginTokensExcept(userId: any, authToken: any): any;
Copy link

Choose a reason for hiding this comment

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

kody code-review Error Handling medium

removeNonLoginTokensExcept(userId: string, authToken: string): Promise<UpdateResult>;

The removeNonLoginTokensExcept method uses 'any' as the return type, which reduces type safety and makes error handling more difficult.

This issue appears in multiple locations:

  • packages/model-typings/src/models/IUsersModel.ts: Lines 184-184
    Please specify a more precise return type (Promise) for the removeNonLoginTokensExcept method to ensure better type safety and error handling.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.


removeNonPATLoginTokensExcept(userId: any, authToken: any): any;

removeNonLoginTokensExcept(userId: any, authToken: any): any;
Copy link

Choose a reason for hiding this comment

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

kody code-review Maintainability medium

removeNonLoginTokensExcept(userId: string, authToken: string): Promise<UpdateResult>;

The removeNonLoginTokensExcept method uses 'any' type for parameters, reducing type safety and potentially leading to runtime errors.

This issue appears in multiple locations:

  • packages/model-typings/src/models/IUsersModel.ts: Lines 184-184
    Please replace the 'any' type with specific types (string for userId and authToken) in the removeNonLoginTokensExcept method to improve type safety.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

@MarcosSpessatto MarcosSpessatto modified the milestones: 7.6.0, 7.7.0 Apr 25, 2025
@ggazzo ggazzo added the stat: QA assured Means it has been tested and approved by a company insider label Apr 29, 2025
@dionisio-bot dionisio-bot bot added the stat: ready to merge PR tested and approved waiting for merge label Apr 29, 2025
@ggazzo ggazzo merged commit 7e00caa into develop Apr 29, 2025
9 checks passed
@ggazzo ggazzo deleted the chore/remove-other-login-tokens-method branch April 29, 2025 16:47
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants