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): enforcing concrete model policies when read from a delegate base #1726

Merged
merged 3 commits into from
Sep 22, 2024

Conversation

ymc9
Copy link
Member

@ymc9 ymc9 commented Sep 22, 2024

No description provided.

Copy link
Contributor

coderabbitai bot commented Sep 22, 2024

Caution

Review failed

The head commit changed during the review from 05f48ee to 943c953.

Walkthrough

Walkthrough

The changes introduced in this pull request enhance the functionality of the enhancement system within the codebase. Key modifications include the addition of a new function for processing relation payloads, updates to method signatures to improve type specificity, and adjustments to ensure asynchronous operations are properly handled. These changes collectively aim to improve the handling of relation fields and policy enforcement across various components of the system.

Changes

Files Change Summary
packages/runtime/src/enhancements/node/create-enhancement.ts Updated createEnhancement function to use DbClientContract, added processIncludeRelationPayload to InternalEnhancementOptions, and modified logic for handling relation payloads in policy and validation enhancements.
packages/runtime/src/enhancements/node/delegate.ts Updated withDelegate function to accept a context parameter, modified DelegateProxyHandler to store this context, and made several methods asynchronous to handle operations related to the Prisma client.
packages/runtime/src/enhancements/node/policy/index.ts Introduced policyProcessIncludeRelationPayload function for processing relation field payloads, and refined type constraints for the withPolicy function to use DbClientContract.
packages/runtime/src/enhancements/node/policy/policy-utils.ts Added logging for the findFirst method in PolicyUtil to enhance visibility when a model is not found in the database.
packages/runtime/src/enhancements/node/proxy.ts Updated method signatures in DefaultPrismaProxyHandler to improve type specificity by changing parameter types from general keys to specific action types, and refined the makeHandler function's parameter type to DbClientContract.
tests/integration/tests/enhancements/with-delegate/policy-interaction.test.ts Added test cases to validate the behavior of policies in a polymorphic system involving models User, Asset, and Post, ensuring that policies are respected during various database operations.

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

Outside diff range and nitpick comments (3)
packages/runtime/src/enhancements/node/create-enhancement.ts (2)

51-61: Specify a more precise type for payload parameter in processIncludeRelationPayload.

Currently, payload is typed as unknown, which reduces type safety. Consider defining a specific type or interface for payload to leverage TypeScript's type checking and improve code clarity.


129-131: Address TODO: Refactor global callback usage for better encapsulation.

The TODO comment indicates that sharing processIncludeRelationPayload globally is not ideal. I can assist in proposing a refactored design to improve encapsulation and modularity.

Would you like me to provide suggestions on refactoring this implementation or open a new GitHub issue to track this task?

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

465-465: Handle possible undefined properties safely

In line 465, you're accessing readAsset1.title, which may be undefined. Although this is part of the test to verify policy enforcement, consider adding explicit checks or comments to clarify the expected behavior.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between cb68815 and 732e7be.

Files selected for processing (6)
  • packages/runtime/src/enhancements/node/create-enhancement.ts (5 hunks)
  • packages/runtime/src/enhancements/node/delegate.ts (15 hunks)
  • packages/runtime/src/enhancements/node/policy/index.ts (3 hunks)
  • packages/runtime/src/enhancements/node/policy/policy-utils.ts (1 hunks)
  • packages/runtime/src/enhancements/node/proxy.ts (3 hunks)
  • tests/integration/tests/enhancements/with-delegate/policy-interaction.test.ts (1 hunks)
Additional context used
Biome
packages/runtime/src/enhancements/node/delegate.ts

[error] 361-361: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

Additional comments not posted (21)
packages/runtime/src/enhancements/node/proxy.ts (3)

72-72: LGTM!

The change from keyof PrismaProxyHandler to PrismaProxyActions for the method parameter improves type safety and clarity. It aligns with the usage of the method parameter within the method body.


87-87: LGTM!

The change from keyof PrismaProxyHandler to PrismaProxyActions for the method parameter improves type safety and clarity. It aligns with the usage of the method parameter within the method body and is consistent with the change in the withFluentCall method.


213-213: LGTM!

The change from object to DbClientContract for the prisma parameter improves type safety and clarity. It ensures that the passed argument conforms to the expected contract and reduces the likelihood of passing an incompatible object.

packages/runtime/src/enhancements/node/policy/policy-utils.ts (1)

1101-1103: Approved: The added logging enhances visibility into the function's behavior.

The introduced logging statement provides useful information when the specified model cannot be read back from the database. It enhances the observability of the readBack function by clearly indicating which model encountered an issue.

The logging is appropriately guarded by the shouldLogQuery flag, allowing it to be easily enabled or disabled based on the desired level of verbosity.

The log level of 'info' is suitable for this type of informational message.

packages/runtime/src/enhancements/node/policy/index.ts (2)

10-10: Import of PolicyUtil is appropriately added.

The import statement for PolicyUtil is necessary for the new functionality introduced in the code.


22-22: Verify that the updated type constraint on DbClient does not introduce incompatibilities.

Changing the generic type parameter from object to DbClientContract in the withPolicy function strengthens type safety. However, this may affect existing code that uses withPolicy with clients not extending DbClientContract. Please ensure all usages of withPolicy remain compatible with this new constraint.

Run the following script to identify all usages of withPolicy and check for type compatibility:

packages/runtime/src/enhancements/node/create-enhancement.ts (4)

4-10: Imports updated to include necessary types.

The added type imports from '../../types' ensure all required TypeScript types are available, improving type safety and code clarity.


16-16: Added imports from './policy' for policy enhancements.

Importing policyProcessIncludeRelationPayload and withPolicy from './policy' is necessary for implementing the new policy-related functionality.


74-74: Enhanced type safety in createEnhancement function signature.

Changing the generic constraint to DbClient extends DbClientContract ensures that the prisma client provided conforms to the expected contract, enhancing type safety and preventing potential runtime errors.


110-110: Applied withDelegate enhancement with appropriate parameters.

The withDelegate function is correctly called with result, options, and context, ensuring that delegate enhancements are properly applied when the 'delegate' kind is enabled.

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

Line range hint 486-510: Good use of field-level policies in testing

The test case starting at line 486 effectively verifies field-level policies for different user contexts. The use of @allow and @deny directives at the field level is correctly implemented and tested.

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

506-506: Ensure asynchronous call to injectSelectIncludeHierarchy in doCreate is handled properly

In the doCreate method, the call to injectSelectIncludeHierarchy has been updated to use await. Confirm that this change maintains the desired execution order and that any dependent code handles the asynchronous behavior appropriately.


728-728: Verify asynchronous handling after updating injectSelectIncludeHierarchy in upsert

The method injectSelectIncludeHierarchy is now awaited in the upsert function. Ensure that this change does not introduce any side effects and that the overall logic remains consistent.


747-747: Confirm correct async behavior in doUpdate with injectSelectIncludeHierarchy

The call to injectSelectIncludeHierarchy within doUpdate is now awaited. Verify that this modification preserves the method's correctness and that all asynchronous operations are properly managed.


941-941: Handle new async behavior in delete method with buildSelectIncludeHierarchy

The delete method now awaits buildSelectIncludeHierarchy. Please ensure that this change integrates seamlessly with the existing logic and that any asynchronous dependencies are handled correctly.


993-993: Validate asynchronous call to injectSelectIncludeHierarchy in doDelete

In the doDelete method, injectSelectIncludeHierarchy is now called with await. Confirm that this addition does not disrupt the deletion process and that all promises are appropriately resolved.


Line range hint 178-232: Confirm correct handling of asynchronous injectSelectIncludeHierarchy

The method injectSelectIncludeHierarchy has been converted to an async function, and calls to it have been updated with await. Please ensure that all invocations of this method within the codebase are properly awaited to prevent unhandled promise rejections and maintain correct execution flow.

#!/bin/bash
# Description: Verify all calls to `injectSelectIncludeHierarchy` are awaited.

# Find calls to `injectSelectIncludeHierarchy` that are not preceded by `await`.
rg --type ts --pcre2 '^\s*(?!await\s+)(\w+\.)?injectSelectIncludeHierarchy\(' --files-with-matches

Line range hint 236-260: Ensure proper usage of asynchronous buildSelectIncludeHierarchy

The buildSelectIncludeHierarchy method is now asynchronous. Verify that all calls to this method are using await to handle the returned promise correctly.

#!/bin/bash
# Description: Find all calls to `buildSelectIncludeHierarchy` that might not be awaited.

# Search for calls to `buildSelectIncludeHierarchy` not using `await`.
rg --type ts --pcre2 '^\s*(?!await\s+)(\w+\.)?buildSelectIncludeHierarchy\(' --files-with-matches

Line range hint 331-365: Check asynchronous handling in injectConcreteIncludeRecursively

The method injectConcreteIncludeRecursively is now an async function, and internal calls have been updated accordingly. Please confirm that all invocations of this method are properly awaited and that any asynchronous operations within are correctly handled.

#!/bin/bash
# Description: Verify all calls to `injectConcreteIncludeRecursively` are awaited.

# Find calls to `injectConcreteIncludeRecursively` that are not preceded by `await`.
rg --type ts --pcre2 '^\s*(?!await\s+)(\w+\.)?injectConcreteIncludeRecursively\(' --files-with-matches
Tools
Biome

[error] 361-361: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


42-47: Verify DelegateProxyHandler instantiations include context parameter

The constructor of DelegateProxyHandler now requires a context parameter. Ensure all instances where DelegateProxyHandler is instantiated pass the context argument to avoid potential errors.

Verification successful

All DelegateProxyHandler instantiations include the required context parameter.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all instantiations of `DelegateProxyHandler` missing the `context` parameter.

# Search for `new DelegateProxyHandler` and check for missing fourth argument.
rg --type ts --pcre2 'new\s+DelegateProxyHandler\(([^,]+\s*,\s*[^,]+\s*,\s*[^,]+)(\))' --replace '$1$2' --files-with-matches

Length of output: 207


Script:

#!/bin/bash
# Description: Find all instantiations of `DelegateProxyHandler` missing the `context` parameter.

# Using ast-grep to match `new DelegateProxyHandler` with exactly three arguments.
ast-grep --lang typescript --pattern 'new DelegateProxyHandler($_arg1, $_arg2, $_arg3)' --files-with-matches

Length of output: 346


Script:

#!/bin/bash
# Description: Find all instantiations of `DelegateProxyHandler` missing the `context` parameter.

# Using ripgrep to search for 'new DelegateProxyHandler' with exactly three arguments.
rg --type ts --pcre2 'new\s+DelegateProxyHandler\(\s*[^,]+\s*,\s*[^,]+\s*,\s*[^,]+\s*\)' --files-with-matches

Length of output: 111


25-29: Ensure all calls to withDelegate include the new context parameter

The function withDelegate now accepts an additional context parameter. Please verify that all invocations of withDelegate throughout the codebase have been updated to include this new parameter to prevent runtime errors.

@ymc9 ymc9 merged commit 738bba6 into dev Sep 22, 2024
13 checks passed
@ymc9 ymc9 deleted the fix/delegate-sub-rules branch September 22, 2024 21:41
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