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

(WIP) feat: add list permission #1921

Draft
wants to merge 10 commits into
base: dev
Choose a base branch
from
Draft

Conversation

genu
Copy link
Contributor

@genu genu commented Dec 20, 2024

Resolves #982

This PR is an initial attempt to add a list permission. Putting here for visibility.

@ymc9 If you have some time, could you offer some guidance on the relevant code that would need to be updated, or anything else that would be helpful here.

Copy link
Contributor

coderabbitai bot commented Dec 20, 2024

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


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.

@ymc9
Copy link
Member

ymc9 commented Dec 23, 2024

Thank you for starting this @genu ! It's something wanted by many.

I think the basic implementation should be straightforward. The call path for findXXX proxy is:

PolicyProxyHandler.findXXX -> PolicyProxyHandler.doFind -> PolicyUtils.injectForRead

PolicyUtils.injectForRead is the unified function for injecting "read" related policies. Here' you can see currently only "read" policies are injected:

if (!this.injectAuthGuardAsWhere(db, injected, model, 'read')) {
args.where = this.makeFalse();
return false;
}

I think what needs to be done is to further inject "list" policies.

Also, the "list" policy should only govern "findFirst" and "findMany", not "findUnique". We should probably introduce a boolean flag to distinguish these two cases.

I guess the proxy code is not entirely easy to read and understand 😅. Let me know if you need more clarifications.

@ymc9
Copy link
Member

ymc9 commented Dec 23, 2024

Another complication is, whether "list" should govern groupBy call, since groupBy is partly "listing" data as well. What do you think?

@genu
Copy link
Contributor Author

genu commented Jan 2, 2025

Another complication is, whether "list" should govern groupBy call, since groupBy is partly "listing" data as well. What do you think?

I'm not exactly sure, but I think I would expect list to govern anything that "lists" things.

@genu genu force-pushed the feature/list_policy branch from 2278bf4 to 0161f57 Compare January 2, 2025 02:19
@genu
Copy link
Contributor Author

genu commented Jan 2, 2025

@ymc9 Do we need to distinguish between between findFirst and findMany here?

private async doFind(args: any, actionName: FindOperations, handleRejection: () => any) {
const origArgs = args;
const _args = this.policyUtils.safeClone(args);
if (!this.policyUtils.injectForRead(this.prisma, this.model, _args)) {
if (this.shouldLogQuery) {
this.logger.info(`[policy] \`${actionName}\` ${this.model}: unconditionally denied`);
}
return handleRejection();
}
this.policyUtils.injectReadCheckSelect(this.model, _args);
if (this.shouldLogQuery) {
this.logger.info(`[policy] \`${actionName}\` ${this.model}:\n${formatObject(_args)}`);
}
const result = await this.modelClient[actionName](_args);
return this.policyUtils.postProcessForRead(result, this.model, origArgs);
}

or should injectForRead be modified here to accept a findMany parameter to indicate that the list permission should apply?

Also, why would list apply to a findFirst?

@ymc9
Copy link
Member

ymc9 commented Jan 3, 2025

@ymc9 Do we need to distinguish between between findFirst and findMany here?

private async doFind(args: any, actionName: FindOperations, handleRejection: () => any) {
const origArgs = args;
const _args = this.policyUtils.safeClone(args);
if (!this.policyUtils.injectForRead(this.prisma, this.model, _args)) {
if (this.shouldLogQuery) {
this.logger.info(`[policy] \`${actionName}\` ${this.model}: unconditionally denied`);
}
return handleRejection();
}
this.policyUtils.injectReadCheckSelect(this.model, _args);
if (this.shouldLogQuery) {
this.logger.info(`[policy] \`${actionName}\` ${this.model}:\n${formatObject(_args)}`);
}
const result = await this.modelClient[actionName](_args);
return this.policyUtils.postProcessForRead(result, this.model, origArgs);
}

or should injectForRead be modified here to accept a findMany parameter to indicate that the list permission should apply?

Also, why would list apply to a findFirst?

I think 'list' should govern findFirst because otherwise you'll be able to iteratively call findFirst to simulate findMany:

let r = await db.foo.findFirst();
const knownIds: string[] = [];
while (r) {
  knownIds.push(r.id);
  r = await db.foo.findFirst({ where: { not: { id: { in: knownIds } } } });
}

We can probably introduce a boolean parameter to doFind to distinguish the two cases where "list" should be enforced or not.

@genu genu force-pushed the feature/list_policy branch from d18c2b6 to 1ccc6ac Compare January 7, 2025 14:04
Comment on lines 143 to 150
if (isList && !this.policyUtils.injectForList(this.prisma, this.model, _args)) {
if (this.shouldLogQuery) {
this.logger.info(`[policy] \`${actionName}\` ${this.model}: unconditionally denied`);
}

return handleRejection();
}

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 assuming this is the kind of check we need to do here?

Comment on lines 658 to 661
injectForList(_db: CrudContract, _model: string, _args: any) {
// make select and include visible to the injection
return true;
}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

@ymc9
I'm not exactly sure if this is needed. Should the list logic go inside of the injectForRead?

The isList flag is on the handler doFind I'm a little confused on how the flow is.

Copy link
Member

Choose a reason for hiding this comment

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

Yes, I agree this list logic should go inside injectForRead. Maybe we just rename it to injectFoReadOrList and pass in the flag there. I think the only difference is the call to this.injectAuthGuardAsWhere, for read the arg is "read", and "list" for list.

Copy link
Member

Choose a reason for hiding this comment

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

if (!this.injectAuthGuardAsWhere(db, injected, model, 'read')) {

Copy link
Member

Choose a reason for hiding this comment

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

That part of code is not entirely easy to comprehend 😄. Please feel free to pass the PR to me to finish when you reach a point where you feel the basics are working.

@genu
Copy link
Contributor Author

genu commented Jan 12, 2025

@ymc9 Here are some ideas from thinking through this:

findMany

  • Controlled by list permission since you're viewing multiple resources
  • Would attribute permissions be required to determine what fields are visible in a list context? (In the case that list is allowed and read is denied). Unless list implies read but that may not necessarily the case.

findFirst

  • Still governed by list permission even though returning single item
  • Because it involves scanning/viewing multiple items to find the match

Nested to-many relations during read

  • List permission required for the related collection (should a permission allow list, if parent allows a read? Similar to how check works currently)

Aggregate (This is kind of tricky)

  • List permission required as you're viewing/organizing multiple items
  • May need attribute permissions for the grouping fields, plus permissions for the fields being aggregated within groups

Count

  • Requires list permission as it reveals information about collection size
  • Maybe we have to treat this as a separated permission as count info is sensitive?

Maybe for an initial implementation we should stick to the obvious/straight forward approach and polish it later

thoughts?

@ymc9
Copy link
Member

ymc9 commented Jan 16, 2025

Hi @genu , sorry I almost missed this comment. I think my thoughts generally aligns with your description. I'm sharing the differences below.

@ymc9 Here are some ideas from thinking through this:

findMany

  • Controlled by list permission since you're viewing multiple resources
  • Would attribute permissions be required to determine what fields are visible in a list context? (In the case that list is allowed and read is denied). Unless list implies read but that may not necessarily the case.

I think field-level and model-level permissions should work independently (as they do today). Model-level "list" determines if you can list entities, and field-level rules determine what fields you can see. You can't define "list" rules at the field level because it's meaningless.

findFirst

  • Still governed by list permission even though returning single item
  • Because it involves scanning/viewing multiple items to find the match

Nested to-many relations during read

  • List permission required for the related collection (should a permission allow list, if parent allows a read? Similar to how check works currently)

The permission checking of fetching relations doesn't inherit from its parent, instead, for "read", the relation's model's "read" rules are evaluated to filter out items that shouldn't be seen, regardless if the parent is readable. I think "list" can behave the same way.

Aggregate (This is kind of tricky)

  • List permission required as you're viewing/organizing multiple items
  • May need attribute permissions for the grouping fields, plus permissions for the fields being aggregated within groups

Count

  • Requires list permission as it reveals information about collection size
  • Maybe we have to treat this as a separated permission as count info is sensitive?

I agree "count" should require "list" permission. I don't see a separate permission kind is needed for it for now. We can iterate in the future as we gather feedback.

Maybe for an initial implementation we should stick to the obvious/straight forward approach and polish it later

I totally agree. There're many details to sort out. Just having a single findMany to work will be a great start!

thoughts?

Another major problem is how we add the "list" permission without introducing breaking changes, plus allowing incremental adoption. Here are my thoughts:

  • If there're no "list" rules defined for a model, "list" is allowed if "read" is. This will allow people to continue using findMany etc. with only "read" rules defined.
  • If "list" rules are defined for a model, it then implies "read", and operations like findMany, aggregate, etc. will require "list" permissions to work. Basically, by starting using "list" permission you opt in the new behavior for that model.

What do you think?

@genu
Copy link
Contributor Author

genu commented Jan 22, 2025

@ymc9 Do you mind taking over this PR, I'm not exactly sure how to proceed.

I'll keep an eye out for an updates and review/test as needed.

@hongkongkiwi
Copy link

@ymc9 your comments above make sense on how you expect it to work. I do have a suggestion though.

If there're no "list" rules defined for a model, "list" is allowed if "read" is. This will allow people to continue using findMany etc. with only "read" rules defined.
If "list" rules are defined for a model, it then implies "read", and operations like findMany, aggregate, etc. will require "list" permissions to work. Basically, by starting using "list" permission you opt in the new behavior for that model.

What I'm gathering from this is that this will just transparently work and start filtering out entries if it's not specifically defined right but the user has read access? If I'm correct in this understanding then I recommend below.

The permission checking of fetching relations doesn't inherit from its parent, instead, for "read", the relation's model's "read" rules are evaluated to filter out items that shouldn't be seen, regardless if the parent is readable. I think "list" can behave the same way.

Since this is a breaking change for some users, I would recommend a flag to enable the filtering behaviour and have it off by default. This would allow people to do updates without items unexpectedly disappearing from their lists. E.g. it could be a feature flag in the zmodel as behaviour on or off globally (I don't mean for each model).

I'm really happy with that behaviour so I would switch it on, but since it would affect what shows up when users do a list, it's worth having it opt in imho.

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.

3 participants