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

fix(delegate): policies inherited from delegate base models are not injected into proper hierarchy #1776

Merged
merged 3 commits into from
Oct 15, 2024

Conversation

ymc9
Copy link
Member

@ymc9 ymc9 commented Oct 14, 2024

Fixes #1770

Copy link
Contributor

coderabbitai bot commented Oct 14, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request primarily enhance the DelegateProxyHandler class in the delegate.ts file, improving the handling of delegate models during CRUD operations. Updates include enhanced validation, error handling, and logic for hierarchy injection and field selection. Additionally, new tests have been introduced to validate policy enforcement in model interactions. A regression test has also been added to ensure the correct behavior of schema-defined models. Overall, these changes aim to improve robustness and ensure compliance with delegate model constraints.

Changes

File Path Change Summary
packages/runtime/src/enhancements/node/delegate.ts Enhanced methods in DelegateProxyHandler for CRUD operations, improved error handling, and refined hierarchy injection logic. Updated method signatures to use override.
packages/schema/src/utils/ast-utils.ts Modified cloneAst function to improve the assignment of the $inheritedFrom property for cloned AST nodes.
packages/sdk/src/utils.ts Updated isDiscriminatorField function to utilize getInheritedFromDelegate for better model determination.
tests/integration/tests/enhancements/with-delegate/policy-interaction.test.ts Added a new test case for policy enforcement when creating and querying Post models extending Asset.
tests/regression/tests/issue-1770.test.ts Introduced a new regression test for a schema defined using ZenStack, validating the behavior of model relationships and queries.

Assessment against linked issues

Objective Addressed Explanation
Ensure proper policy enforcement for polymorphic models (#1770)

Possibly related issues

Possibly related PRs


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 55ae94e and 686538e.

📒 Files selected for processing (1)
  • packages/schema/src/utils/ast-utils.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/schema/src/utils/ast-utils.ts

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:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

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

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.

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

🧹 Outside diff range and nitpick comments (4)
tests/regression/tests/issue-1770.test.ts (1)

46-48: Test logic addresses the core issue, but could be more comprehensive.

The test correctly attempts to query resources, which is the primary concern in issue #1770. However, consider the following improvements:

  1. Add data setup to create some resources before querying.
  2. Verify the content of the query results, not just that it resolves.
  3. Test different scenarios, such as querying with different user contexts.

Consider expanding the test like this:

const db = enhance();

// Setup test data
await db.user.create({ data: { id: 'user1' } });
await db.organization.create({ 
  data: { 
    id: 'org1',
    users: { create: { userId: 'user1' } },
    resources: { create: { name: 'Resource 1' } }
  } 
});

// Test as authenticated user
const result = await db.resource.findMany();
expect(result).toHaveLength(1);
expect(result[0].name).toBe('Resource 1');

// Test as unauthenticated user
const unauthenticatedDb = enhance(undefined);
await expect(unauthenticatedDb.resource.findMany()).rejects.toThrow();

This expansion would provide more comprehensive coverage of the issue.

tests/integration/tests/enhancements/with-delegate/policy-interaction.test.ts (1)

487-532: LGTM! Consider adding an explanatory comment.

The new test case effectively validates the policy interactions between the base Asset model and the derived Post model. It covers crucial scenarios such as policy rejection and successful creation.

Consider adding a brief comment before the test case to explain its purpose and the specific scenario it's testing. This would enhance the readability and maintainability of the test suite. For example:

// This test case verifies that policies from both the base Asset model and the derived Post model
// are correctly applied when performing operations on Post entities through the Asset interface.
it('respects sub model policies when queried from a base: case 3', async () => {
    // ... (existing test code)
});
packages/schema/src/utils/ast-utils.ts (1)

120-126: Consider adding tests to verify the new inheritance resolution logic

The updated assignment of clone.$inheritedFrom improves how inherited fields are resolved in the AST cloning process. Adding unit tests or integration tests to cover various inheritance scenarios can help ensure that this change behaves as expected and prevent future regressions.

packages/runtime/src/enhancements/node/delegate.ts (1)

369-370: Reminder to Address the TODO Comment on Redundant Policy Rule Injection

There's a TODO comment indicating that both the delegate base's policy rules and the concrete model's rules are being injected, which may be redundant. Resolving this can improve performance and prevent potential conflicts.

Would you like assistance in refactoring the code to eliminate this redundancy? I can help provide a solution or open a GitHub issue to track this task.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ff997e7 and e4129f7.

📒 Files selected for processing (4)
  • packages/runtime/src/enhancements/node/delegate.ts (1 hunks)
  • packages/schema/src/utils/ast-utils.ts (1 hunks)
  • tests/integration/tests/enhancements/with-delegate/policy-interaction.test.ts (1 hunks)
  • tests/regression/tests/issue-1770.test.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (4)
tests/regression/tests/issue-1770.test.ts (3)

1-1: LGTM: Import statement is correct.

The import of loadSchema from '@zenstackhq/testtools' is appropriate for this test file.


3-4: LGTM: Test suite structure is well-defined.

The test suite is correctly structured using Jest conventions. It's appropriately labeled with the issue number, and the test case is correctly marked as asynchronous.


5-44: Schema structure aligns with issue #1770.

The schema definition accurately represents the polymorphic model structure described in issue #1770. Key points:

  1. The abstract BaseAuth model with its authorization rules.
  2. The Resource model extending BaseAuth and using the @@delegate attribute.
  3. The Personnel model extending Resource.

This structure should allow for testing the policy injection in the proper hierarchy.

To ensure the schema aligns with the issue description, let's verify the presence of key models and attributes:

✅ Verification successful

Schema verification successful for issue #1770.

All key models, attributes, and authorization rules are present as expected.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the presence of key models and attributes in the schema

# Test 1: Check for BaseAuth, Resource, and Personnel models
echo "Checking for key models:"
rg -q 'model BaseAuth|model Resource|model Personnel' tests/regression/tests/issue-1770.test.ts && echo "Key models found" || echo "Key models missing"

# Test 2: Check for @@delegate attribute
echo "Checking for @@delegate attribute:"
rg -q '@@delegate' tests/regression/tests/issue-1770.test.ts && echo "@@delegate attribute found" || echo "@@delegate attribute missing"

# Test 3: Check for authorization rule
echo "Checking for authorization rule:"
rg -q '@@allow' tests/regression/tests/issue-1770.test.ts && echo "Authorization rule found" || echo "Authorization rule missing"

Length of output: 594

packages/runtime/src/enhancements/node/delegate.ts (1)

374-375: Confirmed Correct Merging of Select/Include Hierarchy into Result

The code correctly builds the select/include hierarchy with buildSelectIncludeHierarchy and merges it into the result. This ensures that the proper hierarchy is maintained during processing.

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