Skip to content

Conversation

Azzerty23
Copy link
Contributor

Draft for Permissions checker / issue #242

@Azzerty23
Copy link
Contributor Author

In policy, I am thinking of adding a permissions property that should look like this:

function permissionsChecker(args: any, user?: AuthUser) {
  return {
    post: {
      read: {
        OR: [
          {
            field: args.authorId,
            operator: "===", // or comparator ?
            value: user?.id,
          },
          {
            field: args.author?.id,
            operator: "===",
            value: user?.id,
          },
          {
            field: args.author?.name,
            operator: "===",
            value: user?.name,
          },
        ],
      },
      delete: {
        AND: [
          // {
          //     'author': { // or nested like this ?
          //         'name': {
          //             'operator': '===',
          //             'value': user.name
          //         }
          //     }
          // },
          // 'AND': [
          //         {
          //             'score': {
          //                 'operator': '<',
          //                 'value': 10
          //             }
          //         },
          //         {
          //             'role': {
          //                 'operator': 'in',
          //                 'value': ['ADMIN', 'REVIEWER']
          //             }
          //         }
          // ]
        ],
      },
      // note for myself
      create: { AND: [] }, // return true
      update: { OR: [] }, // return false
    },
    user: {
      create: true,
      update: false,
      read: true,
      delete: false,
    },
  };
}

const policy: PolicyDef = {
  guard: {...},
  validation: {...},
  permissions: permissionsChecker,
};
export default policy;

@Azzerty23
Copy link
Contributor Author

Azzerty23 commented Jan 29, 2024

Imagined implementation details / steps:

  • Generation of permissions from the zmodel AST, at the same level as other generated policy properties (guard, validation, etc.)
  • Addition of the check operation on the Prisma proxy, which takes the operation type (of type PolicyOperationKind) and the passed arguments (where/data...) as parameters and returns a boolean promise.
  • Modification of the API handler to handle CRUD operations
    Endpoint: api/model/[…path]/routes ⇒ e.g., api/model/user/check/read
    Or a new API handler on a specific endpoint?
  • Generation of hooks to fetch the check API.

@Azzerty23
Copy link
Contributor Author

Azzerty23 commented Jan 31, 2024

Thinking again about permissionsChecker()...

I should instead return an object with inline conditions, like this :

function permissionsChecker(args: any, user?: AuthUser) {
  return {
    post: {
      read: args.authorId === user?.id || args.author?.id === user?.id || args.author?.name === user?.name,
      delete: true,
     // ...
    },
    user: {
      // ...
    },
  };
}

I don't know why I love making things more complicated than they need to be ^^

To handle undefined args, does anyone have an elegant solution? I believe I have no choice but to create a wrapper for each one:

define(args.authorId) === user?.id || define(args.author?.id) === user?.id || define(args.author?.name) === user?.name

@b-barry
Copy link

b-barry commented Feb 2, 2024

Looking forward for this feature. At the moment do we have a workaround for this feature?

@Azzerty23
Copy link
Contributor Author

For now, the only solution I have is to manually check the property on the authenticated user/resources. This is problematic as it is not synchronized with our zmodel schemas.

I have planned to dedicate tomorrow to establishing the basics of this, I will share my progress in any case.

@Azzerty23
Copy link
Contributor Author

Azzerty23 commented Feb 2, 2024

What I have in mind to build the permissions themselves:

  1. Obtain policy rules from the zmodel AST.
  2. Resolve each one (with transformation rules below).
  3. Build complete conditions:
// `@@deny` / `@@allow` → deny first
!(denyCondition || denyCondition) && (allowCondition || allowCondition)

Transformation rules:

  1. transform auth() expressions with TypeScriptExpressionTransformer
    @@allow("read", auth().id == 1)
user?.id === 1
  1. append other expressions with args
    @@allow("read", status == "public")
args?.status === "public"
  1. transform null to undefined
    e.g. require login
    @@deny('all', auth() == null)
user?.id === undefined
  1. primary / foreign key / model → create conditions for primary / foreign key and all unique fields
    @@allow("read", auth().id == author.id)
    @@allow("read", auth() == author)
user?.id === (args?.author?.id || args?.authorId) || user?.email === args?.author?.email
  1. prevent undefined value → wrap each value with define guard
define(args?.authorId) === user?.id || define(args?.author?.id) === user?.id
  1. collection predicate expression
    @@allow('read', members?[user == auth()]
// enhancedDb.space.check("read", { where: {id: 1} })
args?.id === define(user?.spaceId)

// enhancedDb.space.check("read", { where: {name: "best-space"} })
args?.name === define(user?.space?.name)
  1. field policy → ignored I think
    content String @deny('read', !published)

@ymc9
Copy link
Member

ymc9 commented Feb 3, 2024

Hi @Azzerty23 , thanks for continuing to work on it. My apologies for the late response.

I've been thinking about this feature for a while, and I think there are several questions to be answered before getting into details.

1. What's the semantic of "check"?

Let's say if we call db.model.check('read'). When should it return true (without making a database call)? My proposed definition is:

Whether there can exist any database record satisfying the "read" policy.

This effectively means whether the "read" policy has any self-contradiction, like:

@@allow('read', x > 0 && x <= 0)

Note that this can also involve relations like:

@@allow('read', a.x > 0 && a.x <= 0)

If we accept this semantic, other CRUD operations should be consistent:

  • create: whether there can exist an input args satisfying the "create" policy.
  • update: whether there can exist a database record satisfying the "update" policy.
  • delete: whether there can exist a database record satisfying the "delete" policy.

2. Should we allow more fine-grained checks?

Just checking for CRUD is very coarse, and I believe there will be many scenarios where one wants to check for a smaller scope by providing "partial conditions". Like:

db.model.check('read', { x: { gt: 0 } });
db.model.check('create', { x: 1 });

To support that, we can simply merge the user-provided conditions with policy rules and check if it's satisfiable.

3. How to implement the check?

With the interpretation above, permission checking seems to become "constraint solving". The policy rules and user-provided conditions together form a set of constraints to satisfy. If we can find a model value (a solution) that satisfies the conditions, we can return true.

Implementing such a solver can be quite tricky. We should probably use an existing constraint solver library (like Microsoft Z3) to get the job done. In a nut shell it let's you do things like:

const x = Int.const('x');
const solver = new Solver();
solver.add(And(x.ge(0), x.le(9)));
console.log(await solver.check());

If so we can just encode the policy expressions into constraint solver's input and let it do the magic.


Over all things, I'm most unsure about #2. To be honest I don't have very good ideas about how the API will be used in real-world applications. Maybe we should create a channel/thread to gather from people who need it?

@Azzerty23
Copy link
Contributor Author

Thank you @ymc9 I had not imagined such a use case where we would add constraints/conditions to the permission checker. In my understanding, all 'constraints' were supposed to be present in the zmodel schema, and we would check their equality against actual values/available values at runtime. But you are absolutely right; let me take a closer look at this constraint solver library.

@Azzerty23
Copy link
Contributor Author

Azzerty23 commented Feb 3, 2024

To address each of your points:

  1. This was the understanding I had following your comment.
  2. Now that you've mentioned it, I don't see how to skip the "partial conditions." As soon as we want to compare sets of values, it becomes essential.
  3. I am exploring this avenue.

Let me create the thread in Discord.

EDIT: please share your feedbacks here: https://discord.com/channels/1035538056146595961/1090570544186933258/threads/1203297724921946162

@Azzerty23
Copy link
Contributor Author

I compared kiwi and Z3 and decided to proceed with Z3 because the syntax is simpler, and there are many missing features in Kiwi (such as the OR condition). Here are my experiments with Z3: https://github.com/Azzerty23/z3-test/blob/main/src/solver.ts. I faced challenges before finding the solution to handle the process that is not automatically terminated. However, I now have a better idea how to implement the feature. Hopefully, I will find time in a week or two to continue working on it and complete the task.

Copy link
Contributor

coderabbitai bot commented Feb 19, 2024

Important

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

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:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit-tests for this file.
  • 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 tests 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 generate interesting stats about this repository from git and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • 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/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

@Azzerty23 Azzerty23 force-pushed the feature/permission-checker branch from 39aad38 to e1497c0 Compare February 19, 2024 20:26
@ymc9
Copy link
Member

ymc9 commented Feb 23, 2024

Hi @Azzerty23 , I went through Z3 documentation and thought about how to model constraints with it too. I've captured my thoughts in this repo: https://github.com/ymc9/z3-exp

I think it overlaps with your draft implementation in many ways, but with some differences too. Hope it helps. There might be things we need to discuss in more details.

@Azzerty23
Copy link
Contributor Author

I went through Z3 documentation and thought about how to model constraints with it too. I've captured my thoughts in this repo: https://github.com/ymc9/z3-exp

No, Z3 handles string and array constraints natively :o I used the playground as a reference and dove headfirst into the high-level API, knowing it had limitations, but without delving into them in detail... Thank you for taking the time to explain everything and for looking at my implementation. I'll study it more carefully tonight.

@ymc9 ymc9 deleted the branch zenstackhq:feat/permission-checker April 24, 2024 13:19
@ymc9 ymc9 closed this Apr 24, 2024
@ymc9 ymc9 reopened this Apr 24, 2024
@ymc9 ymc9 changed the base branch from v2 to feat/permission-checker April 26, 2024 02:54
@ymc9 ymc9 deleted the branch zenstackhq:feat/permission-checker May 7, 2024 14:38
@ymc9 ymc9 closed this May 7, 2024
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