diff --git a/packages/plugins/policy/src/expression-transformer.ts b/packages/plugins/policy/src/expression-transformer.ts index 847e7de46..c6cdf00cc 100644 --- a/packages/plugins/policy/src/expression-transformer.ts +++ b/packages/plugins/policy/src/expression-transformer.ts @@ -342,9 +342,12 @@ export class ExpressionTransformer { const rightFieldDef = this.getFieldDefFromFieldRef(normalizedRight, context); // Map ZModel operator to SQL operator string const sqlOp = op === '==' ? '=' : op; - // `before()` enums are text in the VALUES table and pg can't compare text to a native enum + // enums read from a VALUES table (`before()` rows, create input) are text, and pg can't + // compare text to a native enum const asText = - this.isBeforeEnumField(normalizedLeft, context) || this.isBeforeEnumField(normalizedRight, context); + this.isBeforeEnumField(normalizedLeft, context) || + this.isBeforeEnumField(normalizedRight, context) || + this.isCreateInputEnumComparison(normalizedLeft, normalizedRight, context); const operand = (node: OperationNode) => asText ? this.dialect.castText(new ExpressionWrapper(node)) : new ExpressionWrapper(node); return this.dialect @@ -1224,6 +1227,76 @@ export class ExpressionTransformer { return !!fieldDef && QueryUtils.isEnum(this.schema, fieldDef.type); } + /** + * Whether a comparison in a create rule needs both operands compared as text. + * + * Create rules are evaluated before the insert, against a `VALUES` table built from the input + * (see `enforcePreCreatePolicyForOne`). That table carries enum fields as `text`, while stored + * columns have the native enum type, and PostgreSQL has no `text = "Enum"` operator (42883). + * + * Returns true only when one operand is an enum field of the entity being created and the + * other is a stored field of the same enum, e.g. for `model Grant { permission Permission }`: + * - `permission == anchor.defaultPermission` (bare top-level field vs. related row) + * - `anchor.approvals?[permission == this.permission]` (stored row vs. `this`) + * + * Not for literals (`permission == EDIT`): the name mapper still translates `@map`-ed literals. + * Not for enums with `@map`-ed values: the input holds names (`ACTIVE`) but stored columns + * hold mapped values (`active`), so a text comparison would be wrong (#2867). + */ + private isCreateInputEnumComparison(left: Expression, right: Expression, context: ExpressionTransformerContext) { + // only create rules read from the input `VALUES` table + if (context.operation !== 'create') { + return false; + } + const leftInput = this.getCreateInputEnumField(left, context); + const rightInput = this.getCreateInputEnumField(right, context); + // exactly one operand must be create input: if both are, both are text; if neither is, + // both are stored native enums. Either way the types already match. + if (!leftInput === !rightInput) { + return false; + } + const inputDef = (leftInput ?? rightInput)!; + // the other operand must be a stored field of the same enum (a literal resolves to no field) + const storedDef = this.getFieldDefFromFieldRef(leftInput ? right : left, context); + return storedDef?.type === inputDef.type && !this.hasMappedEnumValues(inputDef.type); + } + + /** + * If the expression reads an enum field of the entity being created (i.e. a column of the input + * `VALUES` table), returns that field's definition; otherwise `undefined`. + * + * - `this.field` always refers to the entity the rule belongs to. A longer path such as + * `this.anchor.defaultPermission` goes through a relation and reads a stored row. + * - a bare `field` refers to the entity being created only at the top level of the rule. Inside + * a collection predicate (`relation?[field == ...]`) it refers to the related stored row. + */ + private getCreateInputEnumField(expr: Expression, context: ExpressionTransformerContext) { + let field: string | undefined; + if (ExpressionUtils.isMember(expr) && ExpressionUtils.isThis(expr.receiver) && expr.members.length === 1) { + // `this.field` + field = expr.members[0]; + } else if ( + ExpressionUtils.isField(expr) && + // still on the model the rule belongs to ... + context.modelOrType === context.thisType && + // ... and not inside a collection predicate: there (incl. self-relations, where the + // model is the same) a bare field is a stored row, aliased differently + context.alias === context.thisAlias + ) { + // bare top-level `field` + field = expr.field; + } + // `this` and top-level bare fields both resolve against the model being created + const fieldDef = field ? QueryUtils.getField(this.schema, context.thisType, field) : undefined; + return fieldDef && QueryUtils.isEnum(this.schema, fieldDef.type) ? fieldDef : undefined; + } + + // whether any member of the enum carries `@map`, i.e. its stored values differ from its names + private hasMappedEnumValues(enumType: string) { + const enumDef = QueryUtils.getEnum(this.schema, enumType); + return Object.values(enumDef?.fields ?? {}).some((f) => f.attributes?.some((attr) => attr.name === '@map')); + } + private getFieldDefFromFieldRef(expr: Expression, context: ExpressionTransformerContext): FieldDef | undefined { return this.resolveFieldRef(expr, context)?.fieldDef; } diff --git a/tests/regression/test/issue-2866.test.ts b/tests/regression/test/issue-2866.test.ts new file mode 100644 index 000000000..488e68219 --- /dev/null +++ b/tests/regression/test/issue-2866.test.ts @@ -0,0 +1,148 @@ +import { createPolicyTestClient } from '@zenstackhq/testtools'; +import { describe, expect, it } from 'vitest'; + +// https://github.com/zenstackhq/zenstack/issues/2866 +describe('Regression for issue #2866', () => { + const schema = ` +enum Permission { + VIEW + EDIT +} + +model Anchor { + id Int @id + defaultPermission Permission @default(VIEW) + approvals Approval[] + roles Role[] + grants Grant[] + @@allow('all', true) +} + +model Approval { + id Int @id + anchorId Int + anchor Anchor @relation(fields: [anchorId], references: [id]) + permission Permission @default(VIEW) + permissions Permission[] + @@allow('all', true) +} + +model Role { + id Int @id + anchorId Int + anchor Anchor @relation(fields: [anchorId], references: [id]) + permissions Permission[] + @@allow('read', true) + @@allow('create', anchor.approvals?[permissions == this.permissions]) + @@allow('update', anchor.approvals?[permissions != this.permissions]) +} + +model Grant { + id Int @id + anchorId Int + anchor Anchor @relation(fields: [anchorId], references: [id]) + permission Permission + @@allow('read', true) + @@allow('create', permission == anchor.defaultPermission || anchor.approvals?[permission == this.permission]) +} +`; + + async function setup() { + const db = await createPolicyTestClient(schema, { provider: 'postgresql', usePrismaPush: true }); + const raw = db.$unuseAll(); + await raw.anchor.create({ data: { id: 1 } }); + await raw.anchor.create({ data: { id: 2 } }); + await raw.approval.create({ data: { id: 1, anchorId: 1, permissions: ['VIEW', 'EDIT'] } }); + await raw.approval.create({ data: { id: 2, anchorId: 2, permission: 'EDIT' } }); + return db; + } + + it('compares a stored enum array with the create input', async () => { + const db = await setup(); + + await expect( + db.role.create({ data: { id: 1, anchorId: 1, permissions: ['VIEW', 'EDIT'] } }), + ).resolves.toMatchObject({ permissions: ['VIEW', 'EDIT'] }); + + // array equality keeps order and multiplicity + await expect( + db.role.create({ data: { id: 2, anchorId: 1, permissions: ['EDIT', 'VIEW'] } }), + ).toBeRejectedByPolicy(); + await expect(db.role.create({ data: { id: 3, anchorId: 1, permissions: ['VIEW'] } })).toBeRejectedByPolicy(); + await expect( + db.role.create({ data: { id: 4, anchorId: 1, permissions: ['VIEW', 'EDIT', 'EDIT'] } }), + ).toBeRejectedByPolicy(); + }); + + it('compares stored enum arrays on update', async () => { + const db = await setup(); + const raw = db.$unuseAll(); + await raw.role.create({ data: { id: 1, anchorId: 1, permissions: ['VIEW', 'EDIT'] } }); + await raw.role.create({ data: { id: 2, anchorId: 1, permissions: ['VIEW'] } }); + + await expect(db.role.update({ where: { id: 1 }, data: { permissions: ['EDIT'] } })).toBeRejectedNotFound(); + await expect(db.role.update({ where: { id: 2 }, data: { permissions: ['EDIT'] } })).resolves.toMatchObject({ + permissions: ['EDIT'], + }); + }); + + it('compares a stored enum with the create input', async () => { + const db = await setup(); + + // top-level field compared with a relation field + await expect(db.grant.create({ data: { id: 1, anchorId: 1, permission: 'VIEW' } })).resolves.toMatchObject({ + permission: 'VIEW', + }); + // `this` field compared inside a collection predicate + await expect(db.grant.create({ data: { id: 2, anchorId: 2, permission: 'EDIT' } })).resolves.toMatchObject({ + permission: 'EDIT', + }); + await expect(db.grant.create({ data: { id: 3, anchorId: 1, permission: 'EDIT' } })).toBeRejectedByPolicy(); + }); + + it('treats self-relation rows as stored rows', async () => { + const db = await createPolicyTestClient( + ` +enum Status { + ACTIVE @map("active") + INACTIVE @map("inactive") +} + +enum Kind { + FILE + DIR +} + +model Folder { + id Int @id + status Status + kind Kind + parentId Int? + parent Folder? @relation("tree", fields: [parentId], references: [id]) + children Folder[] @relation("tree") + @@allow('read', true) + @@allow('create', parentId == null || parent.children?[status != ACTIVE] || parent.children?[kind == this.kind]) +} +`, + { provider: 'postgresql', usePrismaPush: true }, + ); + const raw = db.$unuseAll(); + await raw.folder.create({ data: { id: 1, status: 'INACTIVE', kind: 'DIR' } }); + await raw.folder.create({ data: { id: 2, status: 'ACTIVE', kind: 'DIR', parentId: 1 } }); + await raw.folder.create({ data: { id: 3, status: 'INACTIVE', kind: 'DIR' } }); + await raw.folder.create({ data: { id: 4, status: 'INACTIVE', kind: 'DIR', parentId: 3 } }); + + // the only child is ACTIVE and of another kind + await expect( + db.folder.create({ data: { id: 10, status: 'INACTIVE', kind: 'FILE', parentId: 1 } }), + ).toBeRejectedByPolicy(); + // a child that is not ACTIVE + await expect( + db.folder.create({ data: { id: 11, status: 'INACTIVE', kind: 'FILE', parentId: 3 } }), + ).resolves.toMatchObject({ id: 11 }); + // a child of the same kind + await expect( + db.folder.create({ data: { id: 12, status: 'INACTIVE', kind: 'DIR', parentId: 1 } }), + ).resolves.toMatchObject({ id: 12 }); + }); +});