zenstack
zenstack copied to clipboard
feat: permissions checker
Draft for Permissions checker / issue #242
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;
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
checkoperation 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.
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
Looking forward for this feature. At the moment do we have a workaround for this feature?
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.
What I have in mind to build the permissions themselves:
- Obtain policy rules from the zmodel AST.
- Resolve each one (with transformation rules below).
- Build complete conditions:
// `@@deny` / `@@allow` → deny first
!(denyCondition || denyCondition) && (allowCondition || allowCondition)
Transformation rules:
- transform auth() expressions with TypeScriptExpressionTransformer
@@allow("read", auth().id == 1)
user?.id === 1
- append other expressions with args
@@allow("read", status == "public")
args?.status === "public"
- transform
nulltoundefinede.g. require login@@deny('all', auth() == null)
user?.id === undefined
- 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
- prevent undefined value → wrap each value with
defineguard
define(args?.authorId) === user?.id || define(args?.author?.id) === user?.id
- 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)
- field policy → ignored I think
content String @deny('read', !published)
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?
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.
To address each of your points:
- This was the understanding I had following your comment.
- 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.
- 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
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.
[!IMPORTANT]
Auto Review Skipped
Draft detected.
Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository.To trigger a single review, invoke the
@coderabbitai reviewcommand.
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?
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
@coderabbitaiin 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
@coderabbitaiin 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 pauseto pause the reviews on a PR.@coderabbitai resumeto resume the paused reviews.@coderabbitai reviewto trigger a review. This is useful when automatic reviews are disabled for the repository.@coderabbitai resolveresolve all the CodeRabbit review comments.@coderabbitai helpto 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.yamlfile 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.
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.
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.