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): delegate model's guards are not properly including concrete models #1932

Merged
merged 5 commits into from
Jan 2, 2025

Conversation

ymc9
Copy link
Member

@ymc9 ymc9 commented Dec 31, 2024

fixes #1930

Copy link
Contributor

coderabbitai bot commented Dec 31, 2024

Warning

Rate limit exceeded

@ymc9 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 18 minutes and 56 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between d6618c9 and bbd7cb5.

📒 Files selected for processing (2)
  • packages/schema/src/utils/ast-utils.ts (2 hunks)
  • tests/integration/tests/enhancements/with-delegate/policy-interaction.test.ts (1 hunks)
📝 Walkthrough

Walkthrough

The pull request introduces refactoring changes across several files in the schema and utilities packages. It focuses on centralizing and improving the handling of delegate models, discriminator fields, and policy generation. Key modifications include the addition of utility functions like getConcreteModels and getDiscriminatorField, updates to the PolicyGenerator and EnhancerGenerator classes to utilize these new functions, and enhancements to the logic for generating query guards and policy checks for delegate models.

Changes

File Change Summary
packages/schema/src/utils/ast-utils.ts Added getConcreteModels and getDiscriminatorField utility functions.
packages/schema/src/plugins/enhancer/enhance/index.ts Replaced local getDiscriminatorField method with imported utility function; updated processClientTypes to use getConcreteModels.
packages/schema/src/plugins/enhancer/policy/expression-writer.ts Refactored writeRelationCheck method to use writeFieldCondition.
packages/schema/src/plugins/enhancer/policy/policy-guard-generator.ts Introduced new conditional logic in writePolicyGuard for guard generation.
packages/schema/src/plugins/enhancer/policy/utils.ts Updated import statement for PolicyKind and PolicyOperationKind to type imports.
packages/schema/src/plugins/prisma/schema-generator.ts Replaced concrete model filtering with getConcreteModels function.
tests/integration/tests/enhancements/with-delegate/policy-interaction.test.ts Added two new test cases for policy interactions.
tests/regression/tests/issue-1930.test.ts Added new test suite for regression testing.

Assessment against linked issues

Objective Addressed Explanation
Handle interaction between check() function and polymorphism [#1930]
Validate policy checks for delegate models
Ensure correct content access for deleted/private entities

Possibly related PRs


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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

🧹 Nitpick comments (3)
packages/schema/src/plugins/enhancer/policy/utils.ts (2)

314-316: Delegate guard routing logic.
Using isDelegateModel(model) to switch to the delegate guard is a clear approach. If there's any plan to support field-level policies for delegates, consider addressing that here or in a separate helper.


452-505: Implementation of generateDelegateQueryGuardFunction.
This new function correctly iterates through the concrete models, applies an AND block containing (1) a discriminator check and (2) a reference to the concrete model’s guard. One corner case to consider is when concreteModels.length === 0—the function defaults to returning TRUE. Verify that this is desired behavior (i.e., for a delegate model with no subtypes). If you expect a strict denial for unknown subtypes or a fallback scenario, consider returning FALSE instead. Otherwise, implementation details here are sound.

packages/schema/src/utils/ast-utils.ts (1)

5-5: New utility functions: getConcreteModels and getDiscriminatorField.
Both functions logically support delegate handling. If a model isn’t a delegate, getConcreteModels returns an empty array—this is consistent. For getDiscriminatorField, consider logging a warning or throwing if multiple attributes are defined, ensuring you don’t silently pick the first one. Otherwise, these utilities appear to meet the delegate-based inheritance requirements.

Also applies to: 19-19, 315-338

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b477ad8 and ff86ce0.

📒 Files selected for processing (8)
  • packages/schema/src/plugins/enhancer/enhance/index.ts (3 hunks)
  • packages/schema/src/plugins/enhancer/policy/expression-writer.ts (1 hunks)
  • packages/schema/src/plugins/enhancer/policy/policy-guard-generator.ts (2 hunks)
  • packages/schema/src/plugins/enhancer/policy/utils.ts (5 hunks)
  • packages/schema/src/plugins/prisma/schema-generator.ts (2 hunks)
  • packages/schema/src/utils/ast-utils.ts (2 hunks)
  • tests/integration/tests/enhancements/with-delegate/policy-interaction.test.ts (1 hunks)
  • tests/regression/tests/issue-1930.test.ts (1 hunks)
🔇 Additional comments (9)
packages/schema/src/plugins/enhancer/policy/utils.ts (1)

2-2: Imports and references look consistent.
These additions cleanly introduce isDelegateModel, lowerCaseFirst, getConcreteModels, and getDiscriminatorField. Ensure there are no circular dependencies with other modules. Otherwise, everything looks in order.

Also applies to: 18-18, 43-43, 46-52

packages/schema/src/plugins/enhancer/policy/policy-guard-generator.ts (1)

28-28: Conditional checks for delegate vs. non-delegate models.
By placing a top-level isDelegate check, the code gracefully bypasses the current model-level optimizations and defers guard generation to the utils.ts logic for delegate models. This properly addresses the need to include all concrete models in the guard logic. The sequence of constant guard checks remains correct for non-delegate models. Consider adding a small code comment clarifying scenarios when a delegate model has no policies defined (and how it's handled).

Also applies to: 458-495

tests/regression/tests/issue-1930.test.ts (1)

1-91: Comprehensive test for deleted/private article access.
The test thoroughly verifies creation, reading, and denial of access for deleted and private articles. Including coverage for partial reads or updates could further strengthen this regression test. Otherwise, this suite is a solid test that ensures correct guard behavior.

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

575-613: Test for optional relation reading with a private sub-model.
The test confirms that the parent record acknowledges the child’s record at a delegate level (base type) while the policy enforces that it’s not visible to standard queries. This provides an essential coverage of “optional” relations for private items.


615-651: Test for required relation reading with a private sub-model.
Similarly, this ensures that a user’s required relation is hidden if the sub-model is private. The test coverage is robust for end-to-end policy validation of mandatory associations.

packages/schema/src/plugins/enhancer/policy/expression-writer.ts (1)

842-854: Ensure consistency when skipping delegation for postUpdate.
The new logic sets the policy to a constant false for postUpdate operations. If there's ever a use case where post-update checks need some sort of delegation, you'll need to revisit this line to allow custom validations. Otherwise, this is consistent and clear.

packages/schema/src/plugins/enhancer/enhance/index.ts (1)

47-47: Centralized utility usage for model discrimination.
The newly added import for getConcreteModels and getDiscriminatorField suggests that you are shifting toward a more centralized approach for retrieving model details. If this aligns with other refactors, it will help avoid duplicating logic across files.

packages/schema/src/plugins/prisma/schema-generator.ts (2)

60-60: Reusing the unified helper for model retrieval.
Importing getConcreteModels helps remove duplicated code that filters concrete models. This centralizes logic and improves maintainability.


324-324: Simplified delegate base model detection.
Replacing manual filtering logic with getConcreteModels(decl) clarifies your intent to retrieve only concrete models inheriting from the delegate. This change is a nice step toward keeping the codebase DRY.

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

🧹 Nitpick comments (4)
tests/regression/tests/issue-1930.test.ts (2)

7-50: Add documentation comments to explain the model hierarchy and access control rules.

The schema defines a complex hierarchy with delegate models and access control rules. Adding documentation comments would help other developers understand:

  • The purpose of each model
  • The relationship between models
  • The access control rules and their implications

Add documentation comments like this:

+/**
+ * Represents an organization that owns entities
+ */
 model Organization {
   id       String   @id @default(cuid())
   entities Entity[]

   @@allow('all', true)
 }

+/**
+ * Base model for all entities with common fields and access control
+ * @property entityType - Discriminator field for delegate models
+ */
 model Entity {
   // ... rest of the model
 }

53-78: Improve test organization with describe blocks.

The test implementation is thorough but could benefit from better organization using nested describe blocks to group related test cases.

Consider restructuring the test like this:

 describe('issue 1930', () => {
+  describe('normal article', () => {
     it('can create and read contents', async () => {
       // ... existing test code for normal article
     });
+  });
+
+  describe('deleted article', () => {
     it('cannot read contents', async () => {
       // ... existing test code for deleted article
     });
+  });
 });
tests/integration/tests/enhancements/with-delegate/policy-interaction.test.ts (2)

579-618: Enhance test readability with better documentation and assertions.

While the test effectively validates policy enforcement for optional relations, its purpose and expectations could be more clearly documented.

Consider these improvements:

-    it('respects concrete policies when read as base optional relation', async () => {
+    it('should hide private post fields when accessed through optional base relation', async () => {
         const { enhance } = await loadSchema(`...`);
 
         const fullDb = enhance(undefined, { kinds: ['delegate'] });
         await fullDb.user.create({ data: { id: 1 } });
         await fullDb.post.create({ data: { title: 'Post1', private: true, user: { connect: { id: 1 } } } });
+        // First verify the record exists with full access
         await expect(fullDb.user.findUnique({ where: { id: 1 }, include: { asset: true } })).resolves.toMatchObject({
             asset: expect.objectContaining({ type: 'Post' }),
         });
 
         const db = enhance();
         const read = await db.user.findUnique({ where: { id: 1 }, include: { asset: true } });
-        expect(read.asset).toBeTruthy();
-        expect(read.asset.title).toBeUndefined();
+        expect(read.asset).toBeTruthy(); // Asset should be accessible
+        expect(read.asset.type).toBe('Post'); // Base fields should be visible
+        expect(read.asset.title).toBeUndefined(); // Private post fields should be hidden
     });

620-657: Add error case validation and improve test documentation.

The test effectively validates the happy path but could be more comprehensive.

Consider these improvements:

-    it('respects concrete policies when read as base required relation', async () => {
+    it('should handle private posts correctly in required relations while preserving referential integrity', async () => {
         const { enhance } = await loadSchema(`...`);
 
         const fullDb = enhance(undefined, { kinds: ['delegate'] });
         await fullDb.post.create({ data: { id: 1, title: 'Post1', private: true, user: { create: { id: 1 } } } });
+        // Verify the record exists with full access
         await expect(fullDb.user.findUnique({ where: { id: 1 }, include: { asset: true } })).resolves.toMatchObject({
             asset: expect.objectContaining({ type: 'Post' }),
         });
 
         const db = enhance();
         const read = await db.user.findUnique({ where: { id: 1 }, include: { asset: true } });
-        expect(read).toBeTruthy();
-        expect(read.asset.title).toBeUndefined();
+        expect(read).toBeTruthy(); // User should be accessible
+        expect(read.asset).toBeTruthy(); // Required relation should be preserved
+        expect(read.asset.type).toBe('Post'); // Base fields should be visible
+        expect(read.asset.title).toBeUndefined(); // Private post fields should be hidden
+
+        // Add error case validation
+        await expect(
+            db.user.create({
+                data: {
+                    id: 2,
+                    asset: {
+                        create: {
+                            type: 'Post',
+                            title: 'Post2',
+                            private: true
+                        }
+                    }
+                }
+            })
+        ).toResolveTruthy(); // Should succeed as creation is allowed
     });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ff86ce0 and d6618c9.

📒 Files selected for processing (4)
  • packages/schema/src/plugins/enhancer/policy/policy-guard-generator.ts (1 hunks)
  • packages/schema/src/plugins/enhancer/policy/utils.ts (1 hunks)
  • tests/integration/tests/enhancements/with-delegate/policy-interaction.test.ts (2 hunks)
  • tests/regression/tests/issue-1930.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/schema/src/plugins/enhancer/policy/utils.ts
  • packages/schema/src/plugins/enhancer/policy/policy-guard-generator.ts

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