Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
</a>
</div>

> V3 is currently in alpha phase and not ready for production use. Feedback and bug reports are greatly appreciated. Please visit this dedicated [discord channel](https://discord.com/channels/1035538056146595961/1352359627525718056) for chat and support.
> V3 is currently in beta phase and not ready for production use. Feedback and bug reports are greatly appreciated. Please visit this dedicated [discord channel](https://discord.com/channels/1035538056146595961/1352359627525718056) for chat and support.

# What's ZenStack

Expand Down
2 changes: 2 additions & 0 deletions TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,10 @@
- [x] Error system
- [x] Custom table name
- [x] Custom field name
- [ ] Global omit
- [ ] DbNull vs JsonNull
- [ ] Migrate to tsdown
- [ ] @default validation
- [ ] Benchmark
- [x] Plugin
- [x] Post-mutation hooks should be called after transaction is committed
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "zenstack-v3",
"version": "3.0.0-beta.3",
"version": "3.0.0-beta.4",
"description": "ZenStack",
"packageManager": "[email protected]",
"scripts": {
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"publisher": "zenstack",
"displayName": "ZenStack CLI",
"description": "FullStack database toolkit with built-in access control and automatic API generation.",
"version": "3.0.0-beta.3",
"version": "3.0.0-beta.4",
"type": "module",
"author": {
"name": "ZenStack Team"
Expand Down
2 changes: 1 addition & 1 deletion packages/common-helpers/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/common-helpers",
"version": "3.0.0-beta.3",
"version": "3.0.0-beta.4",
"description": "ZenStack Common Helpers",
"type": "module",
"scripts": {
Expand Down
2 changes: 1 addition & 1 deletion packages/create-zenstack/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "create-zenstack",
"version": "3.0.0-beta.3",
"version": "3.0.0-beta.4",
"description": "Create a new ZenStack project",
"type": "module",
"scripts": {
Expand Down
2 changes: 1 addition & 1 deletion packages/dialects/sql.js/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/kysely-sql-js",
"version": "3.0.0-beta.3",
"version": "3.0.0-beta.4",
"description": "Kysely dialect for sql.js",
"type": "module",
"scripts": {
Expand Down
2 changes: 1 addition & 1 deletion packages/eslint-config/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/eslint-config",
"version": "3.0.0-beta.3",
"version": "3.0.0-beta.4",
"type": "module",
"private": true,
"license": "MIT"
Expand Down
9 changes: 5 additions & 4 deletions packages/language/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@zenstackhq/language",
"description": "ZenStack ZModel language specification",
"version": "3.0.0-beta.3",
"version": "3.0.0-beta.4",
"license": "MIT",
"author": "ZenStack Team",
"files": [
Expand Down Expand Up @@ -59,13 +59,14 @@
},
"devDependencies": {
"@types/pluralize": "^0.0.33",
"@types/tmp": "catalog:",
"@zenstackhq/common-helpers": "workspace:*",
"@zenstackhq/eslint-config": "workspace:*",
"@zenstackhq/typescript-config": "workspace:*",
"@zenstackhq/common-helpers": "workspace:*",
"@zenstackhq/vitest-config": "workspace:*",
"glob": "^11.0.2",
"langium-cli": "catalog:",
"tmp": "catalog:",
"@types/tmp": "catalog:"
"tmp": "catalog:"
},
"volta": {
"node": "18.19.1",
Expand Down
90 changes: 73 additions & 17 deletions packages/language/src/validators/attribute-application-validator.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,29 @@
import { AstUtils, type ValidationAcceptor } from 'langium';
import pluralize from 'pluralize';
import type { BinaryExpr, DataModel, Expression } from '../ast';
import {
ArrayExpr,
Attribute,
AttributeArg,
AttributeParam,
DataModelAttribute,
DataField,
DataFieldAttribute,
DataModelAttribute,
InternalAttribute,
ReferenceExpr,
isArrayExpr,
isAttribute,
isDataModel,
isDataField,
isDataModel,
isEnum,
isReferenceExpr,
isTypeDef,
} from '../generated/ast';
import {
getAllAttributes,
getStringLiteral,
hasAttribute,
isAuthOrAuthMemberAccess,
isCollectionPredicate,
isDataFieldReference,
isDelegateModel,
isFutureExpr,
Expand All @@ -31,7 +33,6 @@ import {
typeAssignable,
} from '../utils';
import type { AstValidator } from './common';
import type { DataModel } from '../ast';

// a registry of function handlers marked with @check
const attributeCheckers = new Map<string, PropertyDescriptor>();
Expand Down Expand Up @@ -153,6 +154,7 @@ export default class AttributeApplicationValidator implements AstValidator<Attri
}
}

// TODO: design a way to let plugin register validation
@check('@@allow')
@check('@@deny')
// @ts-expect-error
Expand All @@ -166,10 +168,75 @@ export default class AttributeApplicationValidator implements AstValidator<Attri
}
this.validatePolicyKinds(kind, ['create', 'read', 'update', 'delete', 'all'], attr, accept);

// @encrypted fields cannot be used in policy rules
this.rejectEncryptedFields(attr, accept);
if ((kind === 'create' || kind === 'all') && attr.args[1]?.value) {
// "create" rules cannot access non-owned relations because the entity does not exist yet, so
// there can't possibly be a fk that points to it
this.rejectNonOwnedRelationInExpression(attr.args[1].value, accept);
}
}

private rejectNonOwnedRelationInExpression(expr: Expression, accept: ValidationAcceptor) {
const contextModel = AstUtils.getContainerOfType(expr, isDataModel);
if (!contextModel) {
return;
}

if (
AstUtils.streamAst(expr).some((node) => {
if (!isDataFieldReference(node)) {
// not a field reference, skip
return false;
}

// referenced field is not a member of the context model, skip
if (node.target.ref?.$container !== contextModel) {
return false;
}

const field = node.target.ref as DataField;
if (!isRelationshipField(field)) {
// not a relation, skip
return false;
}

if (isAuthOrAuthMemberAccess(node)) {
// field reference is from auth() or access from auth(), not a relation query
return false;
}

// check if the the node is a reference inside a collection predicate scope by auth access,
// e.g., `auth().foo?[x > 0]`

// make sure to skip the current level if the node is already an LHS of a collection predicate,
// otherwise we're just circling back to itself when visiting the parent
const startNode =
isCollectionPredicate(node.$container) && (node.$container as BinaryExpr).left === node
? node.$container
: node;
const collectionPredicate = AstUtils.getContainerOfType(startNode.$container, isCollectionPredicate);
if (collectionPredicate && isAuthOrAuthMemberAccess(collectionPredicate.left)) {
return false;
}

const relationAttr = field.attributes.find((attr) => attr.decl.ref?.name === '@relation');
if (!relationAttr) {
// no "@relation", not owner side of the relation, match
return true;
}

if (!relationAttr.args.some((arg) => arg.name === 'fields')) {
// no "fields" argument, can't be owner side of the relation, match
return true;
}

return false;
})
) {
accept('error', `non-owned relation fields are not allowed in "create" rules`, { node: expr });
}
}

// TODO: design a way to let plugin register validation
@check('@allow')
@check('@deny')
// @ts-expect-error
Expand Down Expand Up @@ -199,9 +266,6 @@ export default class AttributeApplicationValidator implements AstValidator<Attri
);
}
}

// @encrypted fields cannot be used in policy rules
this.rejectEncryptedFields(attr, accept);
}

@check('@@validate')
Expand Down Expand Up @@ -261,14 +325,6 @@ export default class AttributeApplicationValidator implements AstValidator<Attri
}
}

private rejectEncryptedFields(attr: AttributeApplication, accept: ValidationAcceptor) {
AstUtils.streamAllContents(attr).forEach((node) => {
if (isDataFieldReference(node) && hasAttribute(node.target.ref as DataField, '@encrypted')) {
accept('error', `Encrypted fields cannot be used in policy rules`, { node });
}
});
}

private validatePolicyKinds(
kind: string,
candidates: string[],
Expand Down
4 changes: 2 additions & 2 deletions packages/language/src/validators/expression-validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,12 +207,12 @@ export default class ExpressionValidator implements AstValidator<Expression> {
isDataFieldReference(expr.left) &&
(isThisExpr(expr.right) || isDataFieldReference(expr.right))
) {
accept('error', 'comparison between model-typed fields are not supported', { node: expr });
accept('error', 'comparison between models is not supported', { node: expr });
} else if (
isDataFieldReference(expr.right) &&
(isThisExpr(expr.left) || isDataFieldReference(expr.left))
) {
accept('error', 'comparison between model-typed fields are not supported', { node: expr });
accept('error', 'comparison between models is not supported', { node: expr });
}
} else if (
(isDataModel(leftType) && !isNullExpr(expr.right)) ||
Expand Down
100 changes: 100 additions & 0 deletions packages/language/test/expression-validation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { describe, it } from 'vitest';
import { loadSchema, loadSchemaWithError } from './utils';

describe('Expression Validation Tests', () => {
it('should reject model comparison', async () => {
await loadSchemaWithError(
`
model User {
id Int @id
name String
posts Post[]
}

model Post {
id Int @id
title String
author User @relation(fields: [authorId], references: [id])
@@allow('all', author == this)
}
Comment on lines +15 to +19
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Relation requires the scalar FK field authorId.

Without authorId Int, schema validation may fail before reaching the expression validator, making the test flaky for the intended error.

             model Post {
                 id Int @id
                 title String
+                authorId Int
                 author User @relation(fields: [authorId], references: [id])
                 @@allow('all', author == this)
             }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
id Int @id
title String
author User @relation(fields: [authorId], references: [id])
@@allow('all', author == this)
}
model Post {
id Int @id
title String
authorId Int
author User @relation(fields: [authorId], references: [id])
@@allow('all', author == this)
}
🤖 Prompt for AI Agents
In packages/language/test/expression-validation.test.ts around lines 15 to 19,
the User relation is defined without the scalar foreign-key field authorId,
which causes schema validation to fail before the expression validator runs; add
a scalar field authorId Int to the model (and ensure it's included in the model
definition used by the test) and update any references if needed so the relation
uses fields: [authorId], references: [id] and the test will reliably reach the
expression validator.

`,
'comparison between models is not supported',
);
});

it('should reject model comparison', async () => {
await loadSchemaWithError(
`
model User {
id Int @id
name String
profile Profile?
address Address?
@@allow('read', profile == this)
}

model Profile {
id Int @id
bio String
user User @relation(fields: [userId], references: [id])
userId Int @unique
}

model Address {
id Int @id
street String
user User @relation(fields: [userId], references: [id])
userId Int @unique
}
`,
'comparison between models is not supported',
);
});

it('should allow auth comparison with auth type', async () => {
await loadSchema(
`
datasource db {
provider = 'sqlite'
url = 'file:./dev.db'
}

model User {
id Int @id
name String
profile Profile?
@@allow('read', auth() == this)
}

model Profile {
id Int @id
bio String
user User @relation(fields: [userId], references: [id])
userId Int @unique
@@allow('read', auth() == user)
}
`,
);
});

it('should reject auth comparison with non-auth type', async () => {
await loadSchemaWithError(
`
model User {
id Int @id
name String
profile Profile?
}

model Profile {
id Int @id
bio String
user User @relation(fields: [userId], references: [id])
userId Int @unique
@@allow('read', auth() == this)
}
`,
'incompatible operand types',
);
});
});
Loading