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

fixed guard usage in XState machines; removed APPLICATION_ACCEPT which is equivalent to GRANT #4675

Merged
merged 2 commits into from
Nov 6, 2024

Conversation

techsmyth
Copy link
Member

@techsmyth techsmyth commented Nov 6, 2024

The issue was the renaming of guard to guards in the machine definitions.

Once the guards were working then the new privilege was no longer required.

Summary by CodeRabbit

  • New Features

    • Streamlined authorization logic for role assignments and event handling.
    • Updated state machine definitions for organization verification and application lifecycles.
  • Bug Fixes

    • Enhanced error handling for role invitations and contributor assignments.
  • Refactor

    • Standardized naming conventions for guard properties in state transitions.
    • Removed deprecated privilege checks to simplify authorization processes.
  • Documentation

    • Added comments to clarify privilege usage in lifecycle transitions.

Copy link
Contributor

coderabbitai bot commented Nov 6, 2024

Walkthrough

The pull request includes modifications across multiple files, primarily focusing on changes to authorization privileges and state machine configurations. Key alterations involve the removal of the COMMUNITY_APPLY_ACCEPT privilege, the elimination of the appendPrivilegeRules method, and standardization of the guards property to guard in state transitions. Additional updates enhance authorization logic, error handling, and privilege checks within various service classes, streamlining the overall management of roles and lifecycle transitions.

Changes

File Path Change Summary
src/common/enums/authorization.privilege.ts Removed enum member: COMMUNITY_APPLY_ACCEPT from AuthorizationPrivilege.
src/domain/access/application/application.service.authorization.ts Removed method: appendPrivilegeRules. Updated applyAuthorizationPolicy to rely solely on extendAuthorizationPolicy.
src/domain/access/application/application.service.lifecycle.ts Renamed guards to guard in state transitions for new, approving, and rejected states.
src/domain/access/invitation/invitation.service.lifecycle.ts Renamed guards to guard in state transitions for invited, accepting, and rejected states.
src/domain/access/role-set/role.set.resolver.mutations.ts Updated authorization logic, error handling, and privilege checks in role assignment and event handling methods.
src/domain/access/role-set/role.set.service.lifecycle.application.ts Replaced hasApplicationAcceptPrivilege with hasGrantPrivilege. Updated privilege checks for lifecycle transitions.
src/domain/community/organization-verification/organization.verification.service.lifecycle.ts Renamed guards to guard in state transitions for organization verification states.

Possibly related PRs

  • Add separate privilege for application approval #4655: The changes in this PR introduce a new privilege for application approval, which is directly related to the removal of the COMMUNITY_APPLY_ACCEPT member from the AuthorizationPrivilege enum in the main PR, as both deal with authorization privileges in the context of application processes.
  • Allow roleSet invitation to an extra Role #4587: This PR modifies the invitedContributor field to invitedContributorID and introduces an extraRole field, which aligns with the changes in the main PR regarding the AuthorizationPrivilege enum, as both involve adjustments to how privileges and roles are managed in the system.

Suggested reviewers

  • Comoque1

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.

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 (7)
src/domain/access/role-set/role.set.service.lifecycle.application.ts (1)

Line range hint 27-36: LGTM! Consider enhancing the comment.

The implementation is correct and follows best practices. The comment clearly explains the privilege usage distinction.

Consider expanding the comment to include specific examples or scenarios:

-// UPDATE privilege is used to manage lifecycle transitions, EXCEPT those related to approving which require GRANT
+// UPDATE privilege is used to manage lifecycle transitions (e.g., draft -> submitted),
+// EXCEPT those related to approving (e.g., submitted -> approved) which require GRANT
src/domain/access/application/application.service.authorization.ts (2)

41-41: Fix typo in comment

There's a capitalization error in the word "iS".

-    // Note: the GRANT privilege iS NOT assigned to the user; that is what is actually used to approve the application
+    // Note: the GRANT privilege is NOT assigned to the user; that is what is actually used to approve the application

Line range hint 15-40: Good architectural improvement

The consolidation of authorization policy extension logic into extendAuthorizationPolicy and removal of appendPrivilegeRules has:

  • Simplified the authorization flow
  • Reduced code complexity
  • Made the privilege management more maintainable

Also applies to: 42-65

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

86-90: LGTM! Consider documenting privilege requirements.

The standardization of the guard property is correct. Consider adding a comment documenting why both REOPEN and ARCHIVE actions require the same privilege level.

 rejected: {
+  // Both REOPEN and ARCHIVE actions require update privilege as they modify the application state
   on: {
     REOPEN: {
       guard: 'hasUpdatePrivilege',

Line range hint 63-90: Consider enhancing type safety for the state machine.

The state machine configuration could benefit from stronger TypeScript typing to prevent potential errors in state/event names and guard references.

Consider defining interfaces for the context and events:

interface ApplicationContext {
  // Add relevant context properties
}

type ApplicationEvents = 
  | { type: 'APPROVE' }
  | { type: 'REJECT' }
  | { type: 'APPROVED' }
  | { type: 'REOPEN' }
  | { type: 'ARCHIVE' };

const applicationLifecycleMachine = createMachine<ApplicationContext, ApplicationEvents>({
  // ... existing configuration
});
src/domain/access/invitation/invitation.service.lifecycle.ts (2)

Line range hint 16-20: Update return type of getState method to InvitationLifecycleState

As per issue #4645, the return type should be more specific to improve type safety.

-  public getState(lifecycle: ILifecycle): string {
+  public getState(lifecycle: ILifecycle): InvitationLifecycleState {

Line range hint 41-44: Consider refactoring to reduce maintenance overhead

The comment indicates a maintenance risk where two machines need to be kept in sync. Consider extracting the machine configuration to a shared constant and deriving both machines from it to ensure they stay synchronized.

const baseConfig = {
  states: invitationLifecycleMachine.states,
  initial: invitationLifecycleMachine.initial,
};

// Main machine with guards
const mainMachine = createMachine({
  ...baseConfig,
  guards: {
    // guard implementations
  }
});

// States-only machine
const statesOnlyMachine = createMachine(baseConfig);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3731456 and a44e5f6.

📒 Files selected for processing (7)
  • src/common/enums/authorization.privilege.ts (0 hunks)
  • src/domain/access/application/application.service.authorization.ts (1 hunks)
  • src/domain/access/application/application.service.lifecycle.ts (2 hunks)
  • src/domain/access/invitation/invitation.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 (2 hunks)
  • src/domain/community/organization-verification/organization.verification.service.lifecycle.ts (3 hunks)
💤 Files with no reviewable changes (1)
  • src/common/enums/authorization.privilege.ts
🧰 Additional context used
📓 Path-based instructions (6)
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/invitation/invitation.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.

src/domain/community/organization-verification/organization.verification.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.

📓 Learnings (1)
src/domain/access/invitation/invitation.service.lifecycle.ts (1)
Learnt from: valentinyanakiev
PR: alkem-io/server#4629
File: src/domain/access/invitation/invitation.service.lifecycle.ts:16-21
Timestamp: 2024-10-29T11:35:28.113Z
Learning: In `src/domain/access/invitation/invitation.service.lifecycle.ts`, the method `getState` in `InvitationLifecycleService` will have its return type updated from `string` to `InvitationLifecycleState` as per issue #4645.
🔇 Additional comments (8)
src/domain/access/role-set/role.set.service.lifecycle.application.ts (1)

37-44: Verify consistent usage of GRANT privilege across state transitions.

The implementation correctly replaces the old COMMUNITY_APPLY_ACCEPT privilege with GRANT.

Let's verify this change is consistently applied across all state transitions:

✅ Verification successful

The GRANT privilege is consistently used for application approval across state transitions

The verification confirms that:

  1. The hasGrantPrivilege guard is correctly implemented using AuthorizationPrivilege.GRANT
  2. The state machine transitions requiring approval consistently use the hasGrantPrivilege guard
  3. No references to the old COMMUNITY_APPLY_ACCEPT privilege remain in the codebase
  4. The implementation follows the same pattern used in other similar authorization checks
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining references to COMMUNITY_APPLY_ACCEPT
# and verify consistent usage of hasGrantPrivilege in state machines

# Check for any remaining references to COMMUNITY_APPLY_ACCEPT
rg -i "COMMUNITY_APPLY_ACCEPT|ApplicationAccept"

# Check state machine configurations for guard usage
ast-grep --pattern 'createMachine({
  $$$
  states: {
    $$$
    guard: $$$
    $$$
  }
})'

Length of output: 145


Script:

#!/bin/bash
# Let's try a different approach to verify the state transitions and privilege usage

# Search for state machine configurations and transitions
rg -A 5 "createMachine\({" 

# Search for authorization privilege usage
rg -A 2 "AuthorizationPrivilege\." 

# Search specifically for grant-related guards or transitions
rg -A 3 "hasGrantPrivilege|GRANT"

Length of output: 176399

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

Line range hint 1-13: LGTM! Class structure follows NestJS best practices

The service is properly decorated with @Injectable(), follows dependency injection principles, and maintains clear separation of concerns.


41-41: Verify the removal of APPLICATION_ACCEPT privilege

The comment indicates that GRANT privilege is now used for application approval. This aligns with the PR objective of removing APPLICATION_ACCEPT, but we should verify that all related code has been updated accordingly.

✅ Verification successful

Let me gather more information by checking for any references to application approval or grant-related privileges.


Let me check for any remaining references to application acceptance in the state machine transitions and authorization code.


Based on the gathered information, I can now provide the final response:

Verification of APPLICATION_ACCEPT privilege removal completed

The codebase has been properly updated to use GRANT privilege for application approval:

  • No references to APPLICATION_ACCEPT or COMMUNITY_APPLY_ACCEPT privileges found
  • State machine transitions for application approval correctly use hasGrantPrivilege guard
  • Authorization code shows GRANT privilege is consistently used for approval actions
  • Comment accurately reflects the current implementation where GRANT privilege is used for application approval
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining references to APPLICATION_ACCEPT
# or COMMUNITY_APPLY_ACCEPT in the codebase

echo "Checking for any remaining references to removed privileges..."
rg -i "APPLICATION_ACCEPT|COMMUNITY_APPLY_ACCEPT"

echo "Checking for any state machine transitions that might need updating..."
ast-grep --pattern 'target: "accept"' 

Length of output: 377


Script:

#!/bin/bash
# Check for references to grant privileges and application approval
echo "Checking for GRANT privilege references..."
rg -i "GRANT.*privilege" -A 2 -B 2

echo "Checking state machine or workflow related files..."
fd "workflow|state" --type f

echo "Checking for application approval related code..."
rg -i "application.*approv|approv.*application" -A 2 -B 2

Length of output: 64756


Script:

#!/bin/bash
# Check for application state transitions and authorization
echo "Checking application state transitions..."
rg -i "APPLICATION.*STATE|state.*APPLICATION" -A 2 -B 2

echo "Checking application authorization..."
ast-grep --pattern 'class $_ {
  $$$
  hasAcceptPrivilege($$$) {
    $$$
  }
  $$$
}'

Length of output: 13114

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

75-75: LGTM! Guard property standardization is correct.

The transition correctly uses the standardized guard property with hasGrantPrivilege.


63-67: LGTM! Verify privilege replacement across codebase.

The change from hasApplicationAcceptPrivilege to hasGrantPrivilege aligns with the PR objective of standardizing privileges.

Let's verify the consistent replacement of APPLICATION_ACCEPT with GRANT privileges:

✅ Verification successful

Privilege replacement verified successfully

The verification confirms:

  • No remaining references to ApplicationAccept or apply_accept in the codebase
  • hasGrantPrivilege is consistently used across relevant services:
    • Application lifecycle
    • Role set lifecycle
    • Organization verification lifecycle

The changes align perfectly with the standardization effort.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining references to ApplicationAccept privilege
# Expect: No occurrences of ApplicationAccept in the codebase

# Search for any remaining references to ApplicationAccept
rg -i "applicationaccept|apply_accept"

# Search for the new grant privilege usage to ensure consistency
rg "hasGrantPrivilege"

Length of output: 1060

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

64-70: LGTM! Correct usage of XState guard property

The changes properly standardize the guard property name in state transitions, aligning with XState's expected configuration.

Also applies to: 76-78, 87-93

src/domain/community/organization-verification/organization.verification.service.lifecycle.ts (2)

Line range hint 1-86: LGTM! Well-structured state machine implementation.

The state machine configuration follows best practices with:

  • Proper dependency injection
  • Clear separation of concerns
  • Type-safe authorization checks
  • Well-defined guard conditions

Line range hint 87-120: State transitions correctly standardized to use 'guard' property.

The changes consistently apply the correct guard privileges:

  • Update privilege for verification requests
  • Grant privilege for verification status changes

This aligns with the PR objective of standardizing guard usage in XState machines.

Let's verify that all state machines in the codebase follow this pattern:

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