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

Add separate privilege for application approval #4655

Merged
merged 4 commits into from
Nov 1, 2024

Conversation

valentinyanakiev
Copy link
Member

@valentinyanakiev valentinyanakiev commented Oct 31, 2024

  • added separate privilege for updating the state of an application - if UPDATE is used, the user can approve own application
  • it doesn't seem that guards are executed at all - there is an issue with the machine setup
  • removed the mutation-level privilege check - the event authorization should go through the XState guards

Summary by CodeRabbit

  • New Features

    • Introduced new policy rule for community application approval.
    • Added a new privilege for accepting community applications.
    • New mutation methods for inviting contributors and managing role sets.
  • Bug Fixes

    • Enhanced error handling for role set membership invitations.
  • Refactor

    • Updated authorization checks for application events and role assignments.
  • Chores

    • Added new guard for application acceptance privileges.

Copy link
Contributor

coderabbitai bot commented Oct 31, 2024

Walkthrough

The pull request introduces several changes to enhance the authorization framework within the application. A new constant for community policy rules and an enumeration value for authorization privileges are added. Additionally, the ApplicationAuthorizationService class is updated with a new method to append privilege rules, while the RoleSetResolverMutations class sees multiple updates to mutation methods and authorization checks. Lastly, a new guard function is added to the RoleSetServiceLifecycleApplication class to verify application acceptance privileges.

Changes

File Path Change Summary
src/common/constants/authorization/policy.rule.constants.ts Added constant POLICY_RULE_COMMUNITY_APPROVE_APPLICATION = 'policyRule-communityApproveApplication';
src/common/enums/authorization.privilege.ts Added enum value COMMUNITY_APPLY_ACCEPT = 'community-apply-accept' in AuthorizationPrivilege.
src/domain/access/application/application.service.authorization.ts Added method appendPrivilegeRules in ApplicationAuthorizationService to enhance authorization logic.
src/domain/access/application/application.service.lifecycle.ts Updated guards for state transitions, replacing hasUpdatePrivilege with hasApplicationAcceptPrivilege.
src/domain/access/role-set/role.set.resolver.mutations.ts Updated authorization privileges in eventOnApplication, added error handling in joinRoleSet, modified role assignment logic, and introduced new mutation methods for inviting contributors.
src/domain/access/role-set/role.set.service.lifecycle.application.ts Added guard function hasApplicationAcceptPrivilege to check application acceptance privileges.

Possibly related PRs

  • allow auth reset on ai server #4579: The changes in this PR involve modifications to authorization privileges, which may relate to the new constant POLICY_RULE_COMMUNITY_APPROVE_APPLICATION added in the main PR, as both are focused on enhancing authorization logic within the application context.

Suggested reviewers

  • techsmyth

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>, please review it.
    • 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 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 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.
    • @coderabbitai help me debug CodeRabbit configuration file.

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

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.

@Comoque1
Copy link
Member

Tested OK locally:
image
image
image

@valentinyanakiev valentinyanakiev marked this pull request as ready for review October 31, 2024 16:29
Copy link
Contributor

@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: 1

🧹 Outside diff range and nitpick comments (2)
src/common/enums/authorization.privilege.ts (1)

33-33: Consider adding JSDoc comment for the new privilege.

To maintain consistency and clarity, consider adding documentation that explains the scope and intended usage of this privilege, similar to other documented privileges like PLATFORM_ADMIN or COMMUNITY_ADD_MEMBER.

+  /** Allows users to accept/approve applications within their scope */
   COMMUNITY_APPLY_ACCEPT = 'community-apply-accept',
src/domain/access/application/application.service.lifecycle.ts (1)

Line range hint 62-78: Consider simplifying the state machine flow.

The current flow from 'new' → 'approving' → 'approved' introduces an intermediate state that might be unnecessary. Unless there's a specific business requirement for the 'approving' state (e.g., async processing), consider simplifying to a direct transition from 'new' to 'approved'.

Here's a suggested simplification:

    new: {
      on: {
        APPROVE: {
          guards: 'hasApplicationAcceptPrivilege',
-         target: ApplicationLifecycleState.APPROVING,
+         target: ApplicationLifecycleState.APPROVED,
        },
        REJECT: {
          guards: 'hasUpdatePrivilege',
          target: ApplicationLifecycleState.REJECTED,
        },
      },
    },
-   approving: {
-     on: {
-       APPROVED: {
-         guards: 'hasApplicationAcceptPrivilege',
-         target: ApplicationLifecycleState.APPROVED,
-       },
-     },
-   },
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2e00759 and 6b5e839.

📒 Files selected for processing (6)
  • src/common/constants/authorization/policy.rule.constants.ts (1 hunks)
  • src/common/enums/authorization.privilege.ts (1 hunks)
  • src/domain/access/application/application.service.authorization.ts (3 hunks)
  • src/domain/access/application/application.service.lifecycle.ts (2 hunks)
  • src/domain/access/role-set/role.set.resolver.mutations.ts (1 hunks)
  • src/domain/access/role-set/role.set.service.lifecycle.application.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
src/common/constants/authorization/policy.rule.constants.ts (1)

Pattern src/**/*.{ts,js}: Review the TypeScript/JavaScript code for NestJS best practices, dependency injection, module structure, and potential bugs. Ensure that the code adheres to TypeScript's typing system and modern standards.

src/common/enums/authorization.privilege.ts (1)

Pattern src/**/*.{ts,js}: Review the TypeScript/JavaScript code for NestJS best practices, dependency injection, module structure, and potential bugs. Ensure that the code adheres to TypeScript's typing system and modern standards.

src/domain/access/application/application.service.authorization.ts (1)

Pattern src/**/*.{ts,js}: Review the TypeScript/JavaScript code for NestJS best practices, dependency injection, module structure, and potential bugs. Ensure that the code adheres to TypeScript's typing system and modern standards.

src/domain/access/application/application.service.lifecycle.ts (1)

Pattern src/**/*.{ts,js}: Review the TypeScript/JavaScript code for NestJS best practices, dependency injection, module structure, and potential bugs. Ensure that the code adheres to TypeScript's typing system and modern standards.

src/domain/access/role-set/role.set.resolver.mutations.ts (1)

Pattern src/**/*.{ts,js}: Review the TypeScript/JavaScript code for NestJS best practices, dependency injection, module structure, and potential bugs. Ensure that the code adheres to TypeScript's typing system and modern standards.

src/domain/access/role-set/role.set.service.lifecycle.application.ts (1)

Pattern src/**/*.{ts,js}: Review the TypeScript/JavaScript code for NestJS best practices, dependency injection, module structure, and potential bugs. Ensure that the code adheres to TypeScript's typing system and modern standards.

🔇 Additional comments (7)
src/common/constants/authorization/policy.rule.constants.ts (1)

30-31: LGTM! Verify constant usage.

The new policy rule constant follows the established naming conventions and formatting patterns. It aligns well with the PR objective of introducing a separate privilege for application approval.

Let's verify the usage of this new constant:

✅ Verification successful

Constant usage verified and properly implemented

The new policy rule constant is correctly used in the ApplicationAuthorizationService where it's integrated into the authorization policy through a privilege rule for community application approval. The implementation follows the established patterns:

  • Imported correctly from constants
  • Used to create an AuthorizationPolicyRulePrivilege
  • Associated with the appropriate COMMUNITY_APPLY_ACCEPT privilege
  • No hardcoded string values found in the codebase
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check where the new policy rule constant is being used
# Expected: Should be used in authorization service and guards

# Search for direct usage of the constant
rg -l "POLICY_RULE_COMMUNITY_APPROVE_APPLICATION"

# Search for the policy rule string value to catch any hardcoded usage
rg -l "policyRule-communityApproveApplication"

Length of output: 283


Script:

#!/bin/bash
# Let's check how the constant is used in the application service
rg -A 5 -B 5 "POLICY_RULE_COMMUNITY_APPROVE_APPLICATION" src/domain/access/application/application.service.authorization.ts

Length of output: 1274

src/domain/access/role-set/role.set.service.lifecycle.application.ts (1)

36-44: LGTM! The new guard implementation looks solid.

The implementation:

  • Correctly extracts agentInfo and authorizationPolicy from the event
  • Properly uses the authorization service to check privileges
  • Follows the same pattern as the existing guard for consistency
  • Is well-typed with TypeScript interfaces

Let's verify the new privilege is properly defined:

✅ Verification successful

The new privilege is properly defined and consistently used across the codebase

The verification confirms:

  • COMMUNITY_APPLY_ACCEPT is correctly defined in the authorization privileges enum
  • The privilege is used consistently in relevant files:
    • Authorization service for access control
    • Role set resolver for mutations
    • Role set lifecycle service for application handling
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify COMMUNITY_APPLY_ACCEPT privilege is defined in enums
# and used consistently

# Check the privilege definition
rg "COMMUNITY_APPLY_ACCEPT" -A 2 "src/common/enums/authorization.privilege.ts"

# Check for other usages of this privilege
rg "COMMUNITY_APPLY_ACCEPT" --type ts

Length of output: 720

src/common/enums/authorization.privilege.ts (1)

33-33: Verify the privilege scope and guards.

The new privilege follows the naming convention and is properly placed within the community-related privileges section. However, since this privilege grants application approval rights, we should verify its implementation.

Let's verify the implementation of guards and usage:

✅ Verification successful

Privilege implementation is properly secured and integrated

The new COMMUNITY_APPLY_ACCEPT privilege is well-implemented with appropriate security controls:

  • Used in conjunction with GRANT privilege in the authorization service
  • Integrated into the application lifecycle state machine
  • Properly logged and verified during application events
  • Protected by policy rules for community application approval
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check implementation of guards and usage of the new privilege

# Check for guard implementations
echo "Checking for guard implementations..."
rg -l "COMMUNITY_APPLY_ACCEPT.*guard" 

# Check for direct usage of the privilege
echo "Checking for privilege usage..."
rg "COMMUNITY_APPLY_ACCEPT" --type ts

Length of output: 692


Script:

#!/bin/bash
# Let's examine the implementation details of the privilege usage

# Check the authorization service implementation
echo "=== Authorization Service Implementation ==="
rg -A 10 "COMMUNITY_APPLY_ACCEPT" src/domain/access/application/application.service.authorization.ts

# Check the role set service lifecycle implementation
echo "=== Role Set Service Lifecycle Implementation ==="
rg -A 10 "COMMUNITY_APPLY_ACCEPT" src/domain/access/role-set/role.set.service.lifecycle.application.ts

# Check the role set resolver mutations
echo "=== Role Set Resolver Mutations ==="
rg -A 10 "COMMUNITY_APPLY_ACCEPT" src/domain/access/role-set/role.set.resolver.mutations.ts

Length of output: 1507

src/domain/access/application/application.service.lifecycle.ts (1)

63-63: LGTM: Guard changes align with privilege separation.

The replacement of hasUpdatePrivilege with hasApplicationAcceptPrivilege for approval flows correctly implements the separation of privileges while maintaining update privileges for rejection flows.

Let's verify the guard implementation and its registration:

Also applies to: 75-75

✅ Verification successful

Guard implementation verified and properly integrated

The verification confirms:

  • Guard hasApplicationAcceptPrivilege is properly implemented in role.set.service.lifecycle.application.ts using the authorization service
  • The guard is correctly referenced in the state machine transitions
  • Implementation follows the authorization pattern using AgentInfo and IAuthorizationPolicy
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the guard implementation and registration
# Expected: Find the guard implementation and its registration with the state machine

# Search for guard implementation
echo "Searching for guard implementation..."
ast-grep --pattern 'hasApplicationAcceptPrivilege = $$$'

# Search for guard registration
echo "Searching for guard registration with the state machine..."
rg -A 5 "createMachine.*applicationLifecycleMachine.*{.*guards.*}"

Length of output: 523


Script:

#!/bin/bash
# Let's try a different approach to find the guard implementation and registration

# Search for files containing the guard name
echo "Files containing hasApplicationAcceptPrivilege:"
rg "hasApplicationAcceptPrivilege"

# Search for machine creation with better regex
echo -e "\nState machine definition:"
rg -A 10 "createMachine\({" "src/domain/access/application/application.service.lifecycle.ts"

# Search for guard implementations in service files
echo -e "\nPotential guard implementations:"
rg -A 5 "const\s+hasApplicationAcceptPrivilege|function\s+hasApplicationAcceptPrivilege"

Length of output: 920


Script:

#!/bin/bash
# Let's fix the regex and try one more time

# Check the implementation in role.set.service.lifecycle.application.ts
echo "Guard implementation:"
rg -A 5 "hasApplicationAcceptPrivilege" "src/domain/access/role-set/role.set.service.lifecycle.application.ts"

# Check the machine creation with fixed regex
echo -e "\nState machine definition:"
rg -A 10 "createMachine" "src/domain/access/application/application.service.lifecycle.ts"

# Look for any other related guards for context
echo -e "\nRelated guards:"
rg "guards.*hasApplicationAcceptPrivilege|hasApplicationAcceptPrivilege.*guards"

Length of output: 1544

src/domain/access/application/application.service.authorization.ts (3)

9-10: LGTM: New imports are properly organized

The new imports for privilege rules are correctly placed and follow the project's import organization pattern.


71-84: 🛠️ Refactor suggestion

Consider adding input validation and flexible privilege operations

While the implementation is functional, there are a few suggestions for improvement:

  1. Add null/undefined check for the authorization parameter
  2. Consider making the privilege operation (GRANT) configurable rather than hardcoded
  3. Add logging to help diagnose the reported guard execution issues

Consider this improved implementation:

 private appendPrivilegeRules(
   authorization: IAuthorizationPolicy
 ): IAuthorizationPolicy {
+  if (!authorization) {
+    throw new Error('Authorization policy is required');
+  }
+
   const approveApplicationPrivilege = new AuthorizationPolicyRulePrivilege(
     [AuthorizationPrivilege.COMMUNITY_APPLY_ACCEPT],
     AuthorizationPrivilege.GRANT,
     POLICY_RULE_COMMUNITY_APPROVE_APPLICATION
   );
+
+  // Add debug logging to help diagnose guard execution issues
+  this.logger.debug(
+    `Appending application approval privilege rule: ${POLICY_RULE_COMMUNITY_APPROVE_APPLICATION}`
+  );

   return this.authorizationPolicyService.appendPrivilegeAuthorizationRules(
     authorization,
     [approveApplicationPrivilege]
   );
 }
#!/bin/bash
# Check if similar privilege rules in other services include validation
rg "new AuthorizationPolicyRulePrivilege" -B 2 -A 2 --type ts

29-32: Verify the authorization policy application order

The privilege rules are now applied before extending the authorization policy with credentials, which is the correct sequence. However, let's verify that this order is consistent across other authorization services.

✅ Verification successful

The authorization policy application order is correct

The code review shows that appendPrivilegeRules is consistently called after inheriting the parent authorization policy and before extending with credentials across all authorization services. This pattern is followed in the application service as well as other services like forum, whiteboard, storage bucket etc.

The sequence:

  1. Inherit parent authorization
  2. Append privilege rules
  3. Extend with credentials

is the standard pattern used throughout the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for similar authorization policy application patterns in other services
rg -A 5 "applyAuthorizationPolicy.*IAuthorizationPolicy" --type ts

Length of output: 13088


Script:

#!/bin/bash
# Search for authorization policy application patterns
rg -B 5 -A 5 "appendPrivilegeRules|applyAuthorizationPolicy" --type ts

Length of output: 235413


Script:

#!/bin/bash
# Search for appendPrivilegeRules pattern in authorization services
rg -B 5 -A 5 "appendPrivilegeRules" --type ts

Length of output: 20383

@valentinyanakiev valentinyanakiev merged commit c8a12ef into develop Nov 1, 2024
3 checks passed
@valentinyanakiev valentinyanakiev deleted the fix-privilege-self-user branch November 1, 2024 08:48
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.

2 participants