Skip to content

Conversation

@MallanagoudaB
Copy link
Collaborator

@MallanagoudaB MallanagoudaB commented Aug 8, 2025

Summary by CodeRabbit

  • New Features

    • Introduced enhanced admin role validation middleware for sensitive admin actions.
    • Added tenant scoping to entity deletion and group update operations.
  • Bug Fixes

    • Ensured entity deletions and related updates are properly restricted to the correct tenant.
  • Refactor

    • Renamed deletion logging methods for improved clarity.
    • Integrated admin role checks into routing middleware for better security enforcement.

@coderabbitai
Copy link

coderabbitai bot commented Aug 8, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This change refactors admin entity deletion to enforce tenant scoping and centralizes admin role validation in a new middleware. The admin role check is removed from the controller and instead applied as middleware in the routing layer. Deletion methods and audit logging are updated to include tenantId, and method names are aligned for consistency.

Changes

Cohort / File(s) Change Summary
Admin Controller Logic
src/controllers/v1/admin.js
Removed inline admin role check from entity deletion; deletion now proceeds directly without explicit role validation in controller.
Admin Database Queries
src/databaseQueries/admin.js
Updated pullEntityFromGroups method to accept and use tenantId as a filter in group update queries.
Deletion Audit Logging
src/databaseQueries/deletionAuditLogs.js
Renamed deletionAuditLogs method to create for audit log creation; updated JSDoc accordingly.
Admin Role Middleware
src/generics/middleware/checkAdminRole.js
Introduced new middleware to validate admin role using JWT and request path; exports async middleware function.
Admin Helper Logic
src/module/admin/helper.js
Added tenantId filtering to entity deletion and group unlinking; renamed log method to create; updated post-deletion logic.
Routing and Middleware Stack
src/routes/index.js
Added checkAdminRole middleware to admin routes; ensures admin validation before pagination; minor formatting adjustments.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Router
    participant checkAdminRole Middleware
    participant Authenticator Middleware
    participant AdminController
    participant AdminHelper
    participant Database

    Client->>Router: DELETE /admin/deleteResource
    Router->>checkAdminRole Middleware: Validate admin role via JWT
    alt Valid admin
        checkAdminRole Middleware->>Authenticator Middleware: Authenticate user
        Authenticator Middleware->>AdminController: Call deleteEntity
        AdminController->>AdminHelper: allowRecursiveDelete (with tenantId)
        AdminHelper->>Database: Delete entity, filter by tenantId
        AdminHelper->>Database: pullEntityFromGroups (with tenantId)
        AdminHelper->>Database: create deletion audit log
        AdminHelper->>AdminController: Return deletion result
        AdminController->>Router: Respond to client
    else Invalid admin
        checkAdminRole Middleware->>Router: Respond with forbidden error
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~18 minutes

Possibly related PRs

Poem

A rabbit hops through code so neat,
With tenant scopes and roles to greet.
Middleware checks on every trail,
Ensuring only admins prevail.
Logs renamed and queries tight,
This patch ensures deletions are right!
🐇✨

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch MiddleWareAdded

🪧 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>, please review it.
    • Explain this complex logic.
    • 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 explain this code block.
  • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration 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.

@MallanagoudaB
Copy link
Collaborator Author

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Aug 8, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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: 9

🔭 Outside diff range comments (1)
src/databaseQueries/admin.js (1)

36-42: Update JSDoc to document the new tenantId parameter.

The method signature was correctly updated to include tenant scoping, but the JSDoc comment needs to reflect this change.

 /**
  * Unlink an entity ID from all parent documents that reference it in their groups.
  *
  * @param {String} entityType - Type of the entity (e.g., 'block', 'cluster').
  * @param {ObjectId} entityId - MongoDB ObjectId of the entity to remove from groups.
+ * @param {String} tenantId - Tenant ID to scope the operation.
  * @returns {Promise<Object>} - MongoDB updateMany result containing modified count.
  */
🧹 Nitpick comments (1)
src/generics/middleware/checkAdminRole.js (1)

75-77: Remove unnecessary return statement.

The return after next() is redundant.

 next()
-return
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 249edc6 and 61f08bb.

📒 Files selected for processing (6)
  • src/controllers/v1/admin.js (1 hunks)
  • src/databaseQueries/admin.js (2 hunks)
  • src/databaseQueries/deletionAuditLogs.js (1 hunks)
  • src/generics/middleware/checkAdminRole.js (1 hunks)
  • src/module/admin/helper.js (6 hunks)
  • src/routes/index.js (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-08-01T11:20:44.813Z
Learnt from: MallanagoudaB
PR: ELEVATE-Project/entity-management#172
File: src/generics/kafka/producers.js:22-37
Timestamp: 2025-08-01T11:20:44.813Z
Learning: In the ELEVATE-Project/entity-management service, the team consistently uses the async Promise executor pattern `return new Promise(async (resolve, reject) => { ... })` throughout the entire codebase including controllers, helpers, database queries, and services. This is an established coding standard that should be maintained for consistency.

Applied to files:

  • src/controllers/v1/admin.js
  • src/routes/index.js
  • src/module/admin/helper.js
📚 Learning: 2025-08-01T12:12:13.317Z
Learnt from: MallanagoudaB
PR: ELEVATE-Project/entity-management#172
File: src/module/admin/helper.js:222-224
Timestamp: 2025-08-01T12:12:13.317Z
Learning: In the ELEVATE-Project/entity-management repository, the Kafka implementation already includes built-in retry and error handling mechanisms at the client level, so additional retry logic in individual methods like pushEntityDeleteKafkaEvent is not necessary.

Applied to files:

  • src/module/admin/helper.js
🧬 Code Graph Analysis (2)
src/routes/index.js (2)
src/generics/middleware/checkAdminRole.js (1)
  • checkAdminRole (16-16)
src/generics/middleware/validator/index.js (1)
  • fs (10-10)
src/generics/middleware/checkAdminRole.js (1)
src/routes/index.js (1)
  • checkAdminRole (10-10)
🪛 Biome (2.1.2)
src/routes/index.js

[error] 77-77: This property is later overwritten by an object member with the same name.

Overwritten with this property.

If an object property with the same name is defined multiple times (except when combining a getter with a setter), only the last definition makes it into the object and previous definitions are ignored.
Unsafe fix: Remove this property.

(lint/suspicious/noDuplicateObjectKeys)

🔇 Additional comments (11)
src/databaseQueries/deletionAuditLogs.js (1)

13-13: LGTM! Clean method rename for better semantics.

The rename from deletionAuditLogs to create improves the method's semantic clarity and aligns with standard CRUD naming conventions.

Also applies to: 21-21

src/controllers/v1/admin.js (1)

76-81: LGTM! Clean separation of concerns.

Moving admin role validation from the controller to middleware is a good architectural decision. The controller now focuses on business logic while authentication/authorization is handled at the middleware layer.

src/databaseQueries/admin.js (1)

52-52: LGTM! Essential tenant scoping added.

Adding tenantId to the filter query is crucial for multi-tenant data isolation and prevents cross-tenant data access issues.

src/routes/index.js (1)

10-10: LGTM! Proper middleware integration.

The checkAdminRole middleware is correctly integrated into the middleware stack with proper ordering (authentication → admin role check → pagination).

Also applies to: 18-18

src/module/admin/helper.js (7)

82-83: LGTM! Proper tenant scoping added to entity filter.

The addition of tenantId to the filter ensures that entity lookups are properly scoped by tenant, which is essential for multi-tenant security and data isolation.


115-118: LGTM! Consistent tenant scoping in recursive deletion.

The tenantId filter is correctly applied to the bulk deletion operation for related entities, maintaining tenant isolation during recursive deletions.


139-142: LGTM! Tenant scoping applied to single entity deletion.

The single entity deletion now properly includes tenantId in the filter, ensuring consistent tenant scoping across both recursive and non-recursive deletion paths.


199-199: Improved promise resolution pattern.

The change from resolve() to return resolve() is consistent with good practices and provides clearer control flow, though both forms are functionally equivalent in this context.


188-188: Signature matches usage of pullEntityFromGroups
The static method in src/databaseQueries/admin.js is defined as

static pullEntityFromGroups(entityType, entityId, tenantId) {  }

which aligns with the three-argument call in src/module/admin/helper.js. No further changes needed.


191-191: Deletion audit log method rename validated

The deletionAuditLogs class in src/databaseQueries/deletionAuditLogs.js now exposes a static create method (no remaining logDeletion), matching the call in src/module/admin/helper.js. No further changes needed.


209-209: Confirmed: logDeletion fully replaced by create

All references to the old logDeletion method have been removed, and the database query class implements static create(logs) as expected. No further changes are needed.

@MallanagoudaB
Copy link
Collaborator Author

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Aug 8, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Collaborator

@VISHNUDAS-tunerlabs VISHNUDAS-tunerlabs left a comment

Choose a reason for hiding this comment

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

Reviewed on aug 8 - 4:21


module.exports = async function (req, res, next) {
// Define paths that require admin role validation
let adminPath = ['admin/deleteResource']
Copy link
Collaborator

Choose a reason for hiding this comment

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

@MallanagoudaB is this the only api in entity service which require admin role?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yes @VISHNUDAS-tunerlabs only API

}

let decodedToken
try {
Copy link
Collaborator

Choose a reason for hiding this comment

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

@MallanagoudaB we should also take the scenario of keycloak usage as well

Copy link
Collaborator

@VISHNUDAS-tunerlabs VISHNUDAS-tunerlabs left a comment

Choose a reason for hiding this comment

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

reviewed onaug 8, 5:10 PM

@VISHNUDAS-tunerlabs VISHNUDAS-tunerlabs merged commit d266cd8 into develop Aug 11, 2025
1 check passed
@coderabbitai coderabbitai bot mentioned this pull request Jan 20, 2026
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.

3 participants