Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

validate the community role changes to stop admins to revoke admin role from themeselvs #342

Merged
merged 4 commits into from
Apr 15, 2024

Conversation

Behzad-rabiei
Copy link
Member

@Behzad-rabiei Behzad-rabiei commented Apr 15, 2024

Summary by CodeRabbit

  • New Features
    • Enhanced community management by preventing admins from revoking their own admin roles.
  • Bug Fixes
    • Improved stability and fixed issues by updating the database library.
  • Tests
    • Added a new test scenario to ensure proper handling of role revocation among admins.

Copy link

coderabbitai bot commented Apr 15, 2024

Walkthrough

The recent updates focus on enhancing the security and integrity of the community management system. Key changes include preventing administrators from removing their own admin roles, updating dependencies for better performance and stability, and refining integration tests to cover new scenarios involving role management.

Changes

Files Change Summary
.../community.test.ts Updated integration tests to include scenarios for admin role revocation, ensuring it triggers a BAD_REQUEST response.
package.json Updated the @togethercrew.dev/db dependency from version 3.0.42 to 3.0.51.
src/controllers/community.controller.ts Added checks to validate role changes in community updates.
src/services/community.service.ts Enhanced role validation logic by importing necessary interfaces and adding a validateRoleChanges function.

🐇🌟
Oh hark! A change does come,
In code where logic hums.
No admin shall their crown remove,
A safeguard now, in code we prove.
Hop and skip, in bytes we trust,
For secure communities, adjust! 🌟🐇


Recent Review Details

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between ab4d70f and ccb2fd7.
Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
Files selected for processing (4)
  • tests/integration/community.test.ts (3 hunks)
  • package.json (1 hunks)
  • src/controllers/community.controller.ts (1 hunks)
  • src/services/community.service.ts (3 hunks)
Additional comments not posted (1)
package.json (1)

30-30: Version update of @togethercrew.dev/db approved.

The update from 3.0.42 to 3.0.51 for @togethercrew.dev/db appears appropriate. Ensure to verify that this version does not introduce breaking changes or dependencies that could affect the application's stability.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@Behzad-rabiei
Copy link
Member Author

@coderabbitai review

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Comment on lines +46 to +48
if (req.body.roles && req.community) {
await communityService.validateRoleChanges(req.user, req.community, req.body.roles);
}
Copy link

Choose a reason for hiding this comment

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

Ensure proper error handling for validateRoleChanges.

The new security check in updateCommunity correctly calls validateRoleChanges to prevent admins from revoking their own roles. However, it's crucial to ensure that any exceptions thrown by validateRoleChanges are caught and handled appropriately to avoid unhandled promise rejections and to provide meaningful feedback to the client.

Comment on lines +158 to +178
/**
* Validates role changes to ensure an admin cannot revoke their own admin role
* @param {HydratedDocument<IUser>} user - The user object representing the current user
* @param {HydratedDocument<ICommunity>} community - The community document
* @param {string[]} newRoles - The new roles to be assigned to the community
* @throws {ApiError} If an admin tries to revoke their own admin role
*/
const validateRoleChanges = async (
user: HydratedDocument<IUser>,
community: HydratedDocument<ICommunity>,
newRoles: ICommunityRoles[],
): Promise<void> => {
const initialUserRoles: string[] = await roleUtil.getUserRolesForCommunity(user, community);
const originalRoles = community.roles;
community.roles = newRoles;
const updatedUserRoles: string[] = await roleUtil.getUserRolesForCommunity(user, community);
community.roles = originalRoles;
if (initialUserRoles.includes('admin') && !updatedUserRoles.includes('admin')) {
throw new ApiError(httpStatus.BAD_REQUEST, 'Admin role cannot be revoked by the user themselves.');
}
};
Copy link

Choose a reason for hiding this comment

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

Review implementation of validateRoleChanges.

The function validateRoleChanges is critical for ensuring that admins cannot revoke their own admin roles. It's important to ensure that the logic correctly identifies the roles before and after the update, and that it properly uses the roles to determine if an admin role is being revoked. Additionally, consider edge cases such as changes in role names or IDs that might not directly match 'admin' but still carry administrative privileges.

Comment on lines +622 to +653
// test('should return 400 when admin users trys to revoke admin role from themselves', async () => {
// await insertCommunities([communityOne, communityTwo, communityThree]);
// await insertUsers([userOne, userTwo]);
// await insertPlatforms([platformOne, platformTwo, platformThree]);
// await insertGuildMembers(
// [discordGuildMember1, discordGuildMember2, discordGuildMember3, discordGuildMember4],
// connection,
// );
// await insertRoles([discordRole1, discordRole2, discordRole3, discordRole4], connection);

// const res1 = await request(app)
// .patch(`/api/v1/communities/${communityOne._id}`)
// .set('Authorization', `Bearer ${userTwoAccessToken}`)
// .send({ roles: [] })
// .expect(httpStatus.BAD_REQUEST);

// const res2 = await request(app)
// .patch(`/api/v1/communities/${communityOne._id}`)
// .set('Authorization', `Bearer ${userTwoAccessToken}`)
// .send({
// roles: [{
// roleType: 'admin',
// source: {
// platform: 'discord',
// identifierType: 'member',
// identifierValues: [userOne.discordId],
// platformId: platformOne._id,
// },
// },]
// })
// .expect(httpStatus.BAD_REQUEST);

Copy link

Choose a reason for hiding this comment

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

Add assertions to the new test scenario.

The new test scenario designed to trigger a BAD_REQUEST when an admin tries to revoke their own admin role is a good start. However, it's important to include assertions that verify the contents of the response to ensure that it contains the expected error message and that no changes were made to the user's roles.

@Behzad-rabiei Behzad-rabiei merged commit a6d2912 into development Apr 15, 2024
13 checks passed
@Behzad-rabiei Behzad-rabiei deleted the upv1 branch September 6, 2024 07:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant