Skip to content

Conversation

gmazoyer
Copy link
Contributor

@gmazoyer gmazoyer commented Jul 21, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a new permission allowing users to review proposed changes.
    • Added a reviewer role with the ability to approve or reject proposed changes.
  • Improvements

    • Streamlined and unified the creation of account roles and groups during initialization.
    • Enhanced permission checks for reviewing proposed changes to ensure only authorized users can perform this action.
  • Bug Fixes

    • Added tests to verify that users without the required permission cannot review proposed changes.

@github-actions github-actions bot added the group/backend Issue related to the backend (API Server, Git Agent) label Jul 21, 2025
Copy link

codspeed-hq bot commented Jul 21, 2025

CodSpeed Performance Report

Merging #6868 will not alter performance

Comparing gma-20250721-ifc1637 (309b024) with develop (87433f2)

Summary

✅ 10 untouched benchmarks

@gmazoyer gmazoyer force-pushed the gma-20250721-ifc1637 branch from 749101a to 18f1a97 Compare July 21, 2025 12:41
@gmazoyer gmazoyer marked this pull request as ready for review July 21, 2025 13:56
@gmazoyer gmazoyer requested a review from a team as a code owner July 21, 2025 13:56
@gmazoyer gmazoyer changed the title IFC-1637 Add permission to approve proposed changes IFC-1637 Add permission to review proposed changes Jul 21, 2025
@@ -0,0 +1 @@
Add a permission to allow users to review proposed changes (identifier `global:review_proposed_change:allow_all`). Users with existing Infrahub instances may need to create this permission to use it. No newline at end of file
Copy link
Contributor

Choose a reason for hiding this comment

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

is it possible to add a migration to add this permission?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'm unsure if this is the job of a migration or the one of the upgrade command (which setup the permissions if none of them exist).

Copy link
Collaborator

Choose a reason for hiding this comment

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

The function upgrade_permissions should take care of it automatically when executing the command infrahub upgrade, would be good to validate that

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It does setup the permissions and roles but only if none of them exist.

@gmazoyer gmazoyer force-pushed the gma-20250721-ifc1637 branch from c935336 to 561df5a Compare July 22, 2025 08:42
Copy link
Contributor

coderabbitai bot commented Jul 22, 2025

Walkthrough

The changes introduce a new global permission (REVIEW_PROPOSED_CHANGE) for reviewing proposed changes, refactor and modularize the creation of account roles and groups, and enforce permission checks for reviewing proposed changes in the GraphQL mutation. Supporting tests and documentation are updated to reflect these changes, and initialization logic is streamlined.

Changes

Cohort / File(s) Change Summary
Permission Constant Addition
backend/infrahub/core/constants/__init__.py, changelog/+ifc1637.added.md
Added the REVIEW_PROPOSED_CHANGE permission to the GlobalPermissions enum and documented it in the changelog.
Role and Group Initialization Refactor
backend/infrahub/core/initialization.py, backend/infrahub/cli/upgrade.py, backend/tests/helpers/test_app.py
Refactored and unified role/group creation logic, introduced create_default_account_groups, added a reviewer role, updated initialization and upgrade scripts to use new group creation logic.
Permission Enforcement in Mutations
backend/infrahub/graphql/mutations/proposed_change.py
Added a permission check for REVIEW_PROPOSED_CHANGE before allowing users to review proposed changes in the mutation.
Global Permission Helper Simplification
backend/infrahub/permissions/globals.py
Simplified the return statement of define_global_permission_from_branch to a single line.
Tests for Permission Enforcement
backend/tests/functional/proposed_change/test_proposed_change_review.py
Added a test to verify permission enforcement for reviewing proposed changes, updated type annotations, and tested permission denial scenarios.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant GraphQL API
    participant Permissions
    participant Database

    User->>GraphQL API: Submit reviewProposedChange mutation
    GraphQL API->>Permissions: Check REVIEW_PROPOSED_CHANGE permission
    alt Permission granted
        Permissions-->>GraphQL API: Allow
        GraphQL API->>Database: Process review (approve/reject)
        Database-->>GraphQL API: Update proposed change
        GraphQL API-->>User: Return result
    else Permission denied
        Permissions-->>GraphQL API: Deny
        GraphQL API-->>User: Raise permission error
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15–20 minutes

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 87433f2 and 309b024.

📒 Files selected for processing (8)
  • backend/infrahub/cli/upgrade.py (3 hunks)
  • backend/infrahub/core/constants/__init__.py (1 hunks)
  • backend/infrahub/core/initialization.py (9 hunks)
  • backend/infrahub/graphql/mutations/proposed_change.py (1 hunks)
  • backend/infrahub/permissions/globals.py (1 hunks)
  • backend/tests/functional/proposed_change/test_proposed_change_review.py (5 hunks)
  • backend/tests/helpers/test_app.py (2 hunks)
  • changelog/+ifc1637.added.md (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
backend/**/*

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

Run backend tests with pytest or via invoke tasks

Files:

  • backend/infrahub/permissions/globals.py
  • backend/infrahub/core/constants/__init__.py
  • backend/infrahub/core/initialization.py
  • backend/tests/helpers/test_app.py
  • backend/infrahub/cli/upgrade.py
  • backend/infrahub/graphql/mutations/proposed_change.py
  • backend/tests/functional/proposed_change/test_proposed_change_review.py
backend/tests/**/*

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

Place backend tests in backend/tests/

Files:

  • backend/tests/helpers/test_app.py
  • backend/tests/functional/proposed_change/test_proposed_change_review.py
🧬 Code Graph Analysis (1)
backend/infrahub/core/initialization.py (3)
backend/infrahub/core/protocols.py (1)
  • CoreAccountGroup (251-252)
backend/infrahub/database/__init__.py (1)
  • InfrahubDatabase (133-450)
backend/infrahub/core/node/standard.py (1)
  • save (88-94)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: markdown-lint
  • GitHub Check: python-lint
  • GitHub Check: scan
  • GitHub Check: Cloudflare Pages
🔇 Additional comments (24)
backend/infrahub/core/constants/__init__.py (1)

86-86: LGTM - New permission constant follows established patterns.

The addition of REVIEW_PROPOSED_CHANGE permission constant is well-placed and follows the existing naming conventions and structure of other global permissions.

changelog/+ifc1637.added.md (1)

1-1: Good documentation of upgrade requirements.

The changelog clearly documents the new permission and appropriately warns users about potential manual setup needs for existing instances. This addresses the upgrade concerns discussed in previous comments.

backend/infrahub/permissions/globals.py (1)

12-12: LGTM - Clean refactoring improves readability.

The single-line return statement maintains the same logic while improving code conciseness.

backend/infrahub/graphql/mutations/proposed_change.py (1)

231-235: Excellent permission enforcement implementation.

The permission check is properly placed at the method start and follows the established pattern used elsewhere in the file. The use of ALLOW_ALL decision and raise_for_permission ensures proper security enforcement.

backend/tests/helpers/test_app.py (3)

15-15: Good consolidation of imports.

The import change to use create_default_account_groups aligns with the refactored initialization pattern.


200-202: Improved variable handling.

Capturing the unprivileged account creation result in a variable instead of discarding it is a good practice improvement.


207-207: Excellent consolidation of account group setup.

Replacing separate role and group creation calls with create_default_account_groups improves maintainability and ensures consistent initialization across the codebase. This will automatically include the new review permission role.

backend/infrahub/cli/upgrade.py (4)

14-14: LGTM: Import consolidation aligns with refactoring.

The import consolidation from individual functions to create_default_account_groups aligns with the refactoring described in the AI summary, streamlining the initialization process.


16-16: LGTM: Protocol classes improve type safety.

Replacing schema constants (InfrahubKind.ACCOUNT, InfrahubKind.OBJECTPERMISSION) with protocol classes (CoreAccount, CoreObjectPermission) provides better type safety and follows the codebase's evolution toward protocol-based schema references.


115-115: LGTM: Consistent protocol usage.

The change from schema constant to CoreObjectPermission protocol is consistent with the import changes and maintains the same query logic.


125-127: LGTM: Simplified setup logic.

The simplification of setup_permissions by replacing multiple function calls with a single create_default_account_groups call reduces complexity while maintaining the same functionality. The logic for existing accounts is preserved correctly.

backend/tests/functional/proposed_change/test_proposed_change_review.py (4)

5-6: LGTM: Proper imports for new test.

The addition of pytest and GraphQLError imports are necessary for the new permission test that verifies error handling.


11-12: LGTM: Enhanced type annotations.

The addition of proper type annotations (NodeManager, CoreAccountGroup, SchemaBranch, InfrahubDatabase) improves code clarity and enables better IDE support and static type checking.

Also applies to: 17-18


30-36: LGTM: Consistent type annotation improvements.

The type annotations for test method parameters are consistent across all test methods and improve code documentation.

Also applies to: 97-103, 155-161


213-263: LGTM: Comprehensive permission test.

The new test_missing_permission test provides excellent coverage for the permission system:

  1. Setup: Creates a proposed change properly
  2. Permission removal: Correctly removes user from "Infrahub Users" group to revoke permissions
  3. Error verification: Properly catches GraphQLError and verifies the specific permission message
  4. State verification: Confirms no changes were made to the proposed change

The test follows the established pattern and thoroughly validates the permission enforcement.

backend/infrahub/core/initialization.py (9)

2-2: LGTM: Proper import for new type hints.

The addition of Sequence import supports the new function signatures that accept sequences of accounts and roles.


28-28: LGTM: Protocol imports align with refactoring.

The protocol imports (CoreAccount, CoreAccountGroup, CoreAccountRole) support the improved type safety throughout the initialization functions.


325-342: LGTM: Improved return type specification.

The change from generic return type to CoreAccountRole provides better type safety. The function logic remains unchanged and correct.


345-427: LGTM: Function renamed and simplified appropriately.

The rename from create_default_roles to create_default_role (singular) accurately reflects that it creates one role. The removal of embedded group creation logic aligns with the separation of concerns where group creation is now handled separately by create_default_account_groups. The permission creation logic remains intact.


430-446: LGTM: New reviewer role implementation is correct.

The new create_proposed_change_reviewer_role function:

  • Creates the appropriate global permission using GlobalPermissions.REVIEW_PROPOSED_CHANGE
  • Sets correct permission decision (ALLOW_ALL)
  • Follows the established pattern for role creation
  • Returns the properly typed CoreAccountRole

This implements the core requirement for the new permission system.


449-469: LGTM: Consistent return type improvement.

The return type change to CoreAccountRole improves type safety while maintaining the same function logic.


472-486: LGTM: Well-generalized group creation function.

The transformation from create_super_administrators_group to create_accounts_group is well-designed:

  • Flexibility: Accepts arbitrary group names, multiple roles, and multiple accounts
  • Type safety: Uses proper protocol types and Sequence for parameters
  • Logging: Maintains informative logging for both group creation and member assignment
  • Error handling: Preserves the existing save/add pattern

This generalization enables reuse while maintaining all necessary functionality.


488-500: LGTM: Excellent consolidation of account group creation.

The new create_default_account_groups function effectively consolidates the creation of standard groups:

  1. Super Administrators: Gets the super admin role and assigns admin accounts
  2. Infrahub Users: Gets both default role and reviewer role, handles optional accounts parameter

The function design is clean, follows the established patterns, and provides the flexibility needed for both initialization and upgrade scenarios.


552-554: LGTM: Streamlined initialization.

The replacement of multiple role/group creation calls with a single create_default_account_groups call simplifies the initialization flow while maintaining all necessary functionality. The comment update accurately reflects the consolidated approach.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch gma-20250721-ifc1637

🪧 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.
    • @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 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.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

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

@gmazoyer gmazoyer force-pushed the gma-20250721-ifc1637 branch 2 times, most recently from f82bdf4 to 9d085b9 Compare July 22, 2025 19:04
@gmazoyer gmazoyer requested a review from a team July 24, 2025 06:17
return role


async def create_proposed_change_reviewer_role(db: InfrahubDatabase) -> CoreAccountRole:
Copy link
Contributor

Choose a reason for hiding this comment

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

do we need a followup issue to make sure that this is executed on an existing system b/c first_time_initialization won't run?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

We have an internal issue about this, attached to the permission system in general.

@gmazoyer gmazoyer force-pushed the gma-20250721-ifc1637 branch 2 times, most recently from 8d05c5f to 0016278 Compare July 28, 2025 07:21
gmazoyer added 5 commits July 28, 2025 16:15
This change also reworks how default roles, groups and permissions are
populated when initializing infrahub or running the upgrade command.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
group/backend Issue related to the backend (API Server, Git Agent)
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants