Skip to content

Commit aa89ff5

Browse files
BetterAndBetterIIymc9claude
authored
fix(policy): do not treat Json kind keys as Kysely nodes (#2809)
Co-authored-by: Yuzhong Zhang <BetterAndBetterII@users.noreply.github.com> Co-authored-by: ymc9 <104139426+ymc9@users.noreply.github.com> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
1 parent 76dced2 commit aa89ff5

2 files changed

Lines changed: 99 additions & 11 deletions

File tree

‎packages/plugins/policy/src/policy-handler.ts‎

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
AndNode,
1414
BinaryOperationNode,
1515
ColumnNode,
16+
DefaultInsertValueNode,
1617
DeleteQueryNode,
1718
expressionBuilder,
1819
ExpressionWrapper,
@@ -33,6 +34,7 @@ import {
3334
sql,
3435
TableNode,
3536
UpdateQueryNode,
37+
ValueListNode,
3638
ValueNode,
3739
ValuesNode,
3840
WhereNode,
@@ -1070,10 +1072,16 @@ export class PolicyHandler<Schema extends SchemaDef> extends OperationNodeTransf
10701072
fields: string[],
10711073
isManyToManyJoinTable: boolean,
10721074
) {
1075+
// Whether row items are operation nodes is determined by the row node's kind:
1076+
// `ValueListNode` items are always nodes, `PrimitiveValueListNode` items are always
1077+
// raw values. Never inspect an item's shape, because user data (e.g., Json values)
1078+
// may legitimately carry a `kind` key.
10731079
if (ValuesNode.is(node)) {
1074-
return node.values.map((v) => this.unwrapCreateValueRow(v.values, model, fields, isManyToManyJoinTable));
1080+
return node.values.map((v) =>
1081+
this.unwrapCreateValueRow(v.values, model, fields, isManyToManyJoinTable, ValueListNode.is(v)),
1082+
);
10751083
} else if (PrimitiveValueListNode.is(node)) {
1076-
return [this.unwrapCreateValueRow(node.values, model, fields, isManyToManyJoinTable)];
1084+
return [this.unwrapCreateValueRow(node.values, model, fields, isManyToManyJoinTable, false)];
10771085
} else {
10781086
invariant(false, `Unexpected node kind: ${node.kind} for unwrapping create values`);
10791087
}
@@ -1084,27 +1092,25 @@ export class PolicyHandler<Schema extends SchemaDef> extends OperationNodeTransf
10841092
model: string,
10851093
fields: string[],
10861094
isImplicitManyToManyJoinTable: boolean,
1095+
itemsAreNodes: boolean,
10871096
) {
10881097
invariant(data.length === fields.length, 'data length must match fields length');
10891098
const result: { node: OperationNode; raw: unknown }[] = [];
10901099
for (let i = 0; i < data.length; i++) {
10911100
const item = data[i]!;
1092-
if (typeof item === 'object' && item && 'kind' in item) {
1093-
if (item.kind === 'DefaultInsertValueNode') {
1101+
if (itemsAreNodes) {
1102+
const itemNode = item as OperationNode;
1103+
if (DefaultInsertValueNode.is(itemNode)) {
10941104
result.push({ node: ValueNode.create(null), raw: null });
10951105
continue;
10961106
}
10971107
const fieldDef = QueryUtils.requireField(this.client.$schema, model, fields[i]!);
1098-
invariant(item.kind === 'ValueNode', 'expecting a ValueNode');
1108+
invariant(ValueNode.is(itemNode), `expecting a ValueNode, got ${itemNode.kind}`);
10991109
result.push({
11001110
node: ValueNode.create(
1101-
this.dialect.transformInput(
1102-
(item as ValueNode).value,
1103-
fieldDef.type as BuiltinType,
1104-
!!fieldDef.array,
1105-
),
1111+
this.dialect.transformInput(itemNode.value, fieldDef.type as BuiltinType, !!fieldDef.array),
11061112
),
1107-
raw: (item as ValueNode).value,
1113+
raw: itemNode.value,
11081114
});
11091115
} else {
11101116
let value: unknown = item;
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import { createPolicyTestClient } from '@zenstackhq/testtools';
2+
import { describe, expect, it } from 'vitest';
3+
4+
// https://github.com/zenstackhq/zenstack/issues/2791
5+
// Policy pre-create checks unwrap insert values and used to treat any object with a
6+
// `kind` key as a Kysely operation node. A Json payload like `{ kind: "artwork" }`
7+
// then failed with `Invariant failed: expecting a ValueNode`.
8+
const schema = `
9+
model User {
10+
id Int @id @default(autoincrement())
11+
}
12+
13+
model Item {
14+
id Int @id @default(autoincrement())
15+
payload Json
16+
17+
// non-constant: constant @@allow('all', true) skips pre-create value unwrapping
18+
@@allow('all', auth() == null)
19+
}
20+
`;
21+
22+
describe('Regression for issue 2791', () => {
23+
it('creates a Json value that has a top-level kind key', async () => {
24+
const db = await createPolicyTestClient(schema, { provider: 'postgresql' });
25+
26+
await expect(db.item.create({ data: { payload: { kind: 'artwork' } } })).resolves.toMatchObject({
27+
payload: { kind: 'artwork' },
28+
});
29+
});
30+
31+
it('creates many Json values that have a top-level kind key', async () => {
32+
const db = await createPolicyTestClient(schema, { provider: 'postgresql' });
33+
34+
await expect(
35+
db.item.createMany({ data: [{ payload: { kind: 'artwork' } }, { payload: { kind: 'photo' } }] }),
36+
).resolves.toMatchObject({ count: 2 });
37+
38+
await expect(db.item.findMany()).resolves.toEqual(
39+
expect.arrayContaining([
40+
expect.objectContaining({ payload: { kind: 'artwork' } }),
41+
expect.objectContaining({ payload: { kind: 'photo' } }),
42+
]),
43+
);
44+
});
45+
46+
it('does not mistake a Json value for a Kysely node when its kind matches a node name', async () => {
47+
const db = await createPolicyTestClient(schema, { provider: 'postgresql' });
48+
49+
// if the payload were treated as a `ValueNode`, the policy check would unwrap
50+
// `value` and the stored payload would not round-trip
51+
await expect(db.item.create({ data: { payload: { kind: 'ValueNode', value: 'x' } } })).resolves.toMatchObject({
52+
payload: { kind: 'ValueNode', value: 'x' },
53+
});
54+
55+
await expect(db.item.create({ data: { payload: { kind: 'DefaultInsertValueNode' } } })).resolves.toMatchObject({
56+
payload: { kind: 'DefaultInsertValueNode' },
57+
});
58+
});
59+
60+
it('still rejects creates that violate the policy regardless of Json shape', async () => {
61+
const db = await createPolicyTestClient(schema, { provider: 'postgresql' });
62+
const authDb = db.$setAuth({ id: 1 });
63+
64+
await expect(authDb.item.create({ data: { payload: { kind: 'artwork' } } })).toBeRejectedByPolicy();
65+
await expect(
66+
authDb.item.create({ data: { payload: { kind: 'ValueNode', value: 'x' } } }),
67+
).toBeRejectedByPolicy();
68+
await expect(
69+
authDb.item.createMany({ data: [{ payload: { kind: 'artwork' } }, { payload: { kind: 'photo' } }] }),
70+
).toBeRejectedByPolicy();
71+
await expect(db.item.findMany()).resolves.toHaveLength(0);
72+
});
73+
74+
it('still accepts the same Json payload via update', async () => {
75+
const db = await createPolicyTestClient(schema, { provider: 'postgresql' });
76+
77+
const item = await db.item.create({ data: { payload: {} } });
78+
await expect(
79+
db.item.update({ where: { id: item.id }, data: { payload: { kind: 'artwork' } } }),
80+
).resolves.toMatchObject({ payload: { kind: 'artwork' } });
81+
});
82+
});

0 commit comments

Comments
 (0)