Skip to content

fix: issue 961, incorrect policy injection for nested updateMany #962

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 25, 2024
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 package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "zenstack-monorepo",
"version": "1.7.0",
"version": "1.7.1",
"description": "",
"scripts": {
"build": "pnpm -r build",
Expand Down
2 changes: 1 addition & 1 deletion packages/ide/jetbrains/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ plugins {
}

group = "dev.zenstack"
version = "1.7.0"
version = "1.7.1"

repositories {
mavenCentral()
Expand Down
2 changes: 1 addition & 1 deletion packages/ide/jetbrains/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "jetbrains",
"version": "1.7.0",
"version": "1.7.1",
"displayName": "ZenStack JetBrains IDE Plugin",
"description": "ZenStack JetBrains IDE plugin",
"homepage": "https://zenstack.dev",
Expand Down
2 changes: 1 addition & 1 deletion packages/language/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@zenstackhq/language",
"version": "1.7.0",
"version": "1.7.1",
"displayName": "ZenStack modeling language compiler",
"description": "ZenStack modeling language compiler",
"homepage": "https://zenstack.dev",
Expand Down
2 changes: 1 addition & 1 deletion packages/misc/redwood/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@zenstackhq/redwood",
"displayName": "ZenStack RedwoodJS Integration",
"version": "1.7.0",
"version": "1.7.1",
"description": "CLI and runtime for integrating ZenStack with RedwoodJS projects.",
"repository": {
"type": "git",
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/openapi/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@zenstackhq/openapi",
"displayName": "ZenStack Plugin and Runtime for OpenAPI",
"version": "1.7.0",
"version": "1.7.1",
"description": "ZenStack plugin and runtime supporting OpenAPI",
"main": "index.js",
"repository": {
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/swr/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@zenstackhq/swr",
"displayName": "ZenStack plugin for generating SWR hooks",
"version": "1.7.0",
"version": "1.7.1",
"description": "ZenStack plugin for generating SWR hooks",
"main": "index.js",
"repository": {
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/tanstack-query/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@zenstackhq/tanstack-query",
"displayName": "ZenStack plugin for generating tanstack-query hooks",
"version": "1.7.0",
"version": "1.7.1",
"description": "ZenStack plugin for generating tanstack-query hooks",
"main": "index.js",
"exports": {
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/trpc/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@zenstackhq/trpc",
"displayName": "ZenStack plugin for tRPC",
"version": "1.7.0",
"version": "1.7.1",
"description": "ZenStack plugin for tRPC",
"main": "index.js",
"repository": {
Expand Down
2 changes: 1 addition & 1 deletion packages/runtime/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@zenstackhq/runtime",
"displayName": "ZenStack Runtime Library",
"version": "1.7.0",
"version": "1.7.1",
"description": "Runtime of ZenStack for both client-side and server-side environments.",
"repository": {
"type": "git",
Expand Down
5 changes: 5 additions & 0 deletions packages/runtime/src/cross/model-meta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@ export type FieldInfo = {
* Mapping from foreign key field names to relation field names
*/
foreignKeyMapping?: Record<string, string>;

/**
* If the field is an auto-increment field
*/
isAutoIncrement?: boolean;
};

/**
Expand Down
130 changes: 89 additions & 41 deletions packages/runtime/src/enhancements/policy/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -523,29 +523,16 @@ export class PolicyProxyHandler<DbClient extends DbClientContract> implements Pr
let createResult = await Promise.all(
enumerate(args.data).map(async (item) => {
if (args.skipDuplicates) {
// check unique constraint conflicts
// we can't rely on try/catch/ignore constraint violation error: https://github.com/prisma/prisma/issues/20496
// TODO: for simple cases we should be able to translate it to an `upsert` with empty `update` payload

// for each unique constraint, check if the input item has all fields set, and if so, check if
// an entity already exists, and ignore accordingly
const uniqueConstraints = this.utils.getUniqueConstraints(model);
for (const constraint of Object.values(uniqueConstraints)) {
if (constraint.fields.every((f) => item[f] !== undefined)) {
const uniqueFilter = constraint.fields.reduce((acc, f) => ({ ...acc, [f]: item[f] }), {});
const existing = await this.utils.checkExistence(db, model, uniqueFilter);
if (existing) {
if (this.shouldLogQuery) {
this.logger.info(`[policy] skipping duplicate ${formatObject(item)}`);
}
return undefined;
}
if (await this.hasDuplicatedUniqueConstraint(model, item, db)) {
if (this.shouldLogQuery) {
this.logger.info(`[policy] \`createMany\` skipping duplicate ${formatObject(item)}`);
}
return undefined;
}
}

if (this.shouldLogQuery) {
this.logger.info(`[policy] \`create\` ${model}: ${formatObject(item)}`);
this.logger.info(`[policy] \`create\` for \`createMany\` ${model}: ${formatObject(item)}`);
}
return await db[model].create({ select: this.utils.makeIdSelection(model), data: item });
})
Expand All @@ -564,6 +551,26 @@ export class PolicyProxyHandler<DbClient extends DbClientContract> implements Pr
};
}

private async hasDuplicatedUniqueConstraint(model: string, createData: any, db: Record<string, DbOperations>) {
// check unique constraint conflicts
// we can't rely on try/catch/ignore constraint violation error: https://github.com/prisma/prisma/issues/20496
// TODO: for simple cases we should be able to translate it to an `upsert` with empty `update` payload

// for each unique constraint, check if the input item has all fields set, and if so, check if
// an entity already exists, and ignore accordingly
const uniqueConstraints = this.utils.getUniqueConstraints(model);
for (const constraint of Object.values(uniqueConstraints)) {
if (constraint.fields.every((f) => createData[f] !== undefined)) {
const uniqueFilter = constraint.fields.reduce((acc, f) => ({ ...acc, [f]: createData[f] }), {});
const existing = await this.utils.checkExistence(db, model, uniqueFilter);
if (existing) {
return true;
}
}
}
return false;
}

//#endregion

//#region Update & Upsert
Expand Down Expand Up @@ -707,17 +714,22 @@ export class PolicyProxyHandler<DbClient extends DbClientContract> implements Pr
postWriteChecks.push(...checks);
};

const _createMany = async (model: string, args: any, context: NestedWriteVisitorContext) => {
if (context.field?.backLink) {
// handles the connection to upstream entity
const reversedQuery = this.utils.buildReversedQuery(context);
for (const item of enumerate(args.data)) {
Object.assign(item, reversedQuery);
const _createMany = async (
model: string,
args: { data: any; skipDuplicates?: boolean },
context: NestedWriteVisitorContext
) => {
for (const item of enumerate(args.data)) {
if (args.skipDuplicates) {
if (await this.hasDuplicatedUniqueConstraint(model, item, db)) {
if (this.shouldLogQuery) {
this.logger.info(`[policy] \`createMany\` skipping duplicate ${formatObject(item)}`);
}
continue;
}
}
await _create(model, item, context);
}
// proceed with the create and collect post-create checks
const { postWriteChecks: checks } = await this.doCreateMany(model, args, db);
postWriteChecks.push(...checks);
};

const _connectDisconnect = async (model: string, args: any, context: NestedWriteVisitorContext) => {
Expand Down Expand Up @@ -797,9 +809,6 @@ export class PolicyProxyHandler<DbClient extends DbClientContract> implements Pr
},

updateMany: async (model, args, context) => {
// injects auth guard into where clause
this.utils.injectAuthGuard(db, args, model, 'update');

// prepare for post-update check
if (this.utils.hasAuthGuard(model, 'postUpdate') || this.utils.getZodSchema(model)) {
let select = this.utils.makeIdSelection(model);
Expand All @@ -809,10 +818,12 @@ export class PolicyProxyHandler<DbClient extends DbClientContract> implements Pr
}
const reversedQuery = this.utils.buildReversedQuery(context);
const currentSetQuery = { select, where: reversedQuery };
this.utils.injectAuthGuard(db, currentSetQuery, model, 'read');
this.utils.injectAuthGuardAsWhere(db, currentSetQuery, model, 'read');

if (this.shouldLogQuery) {
this.logger.info(`[policy] \`findMany\` ${model}:\n${formatObject(currentSetQuery)}`);
this.logger.info(
`[policy] \`findMany\` for post update check ${model}:\n${formatObject(currentSetQuery)}`
);
}
const currentSet = await db[model].findMany(currentSetQuery);

Expand All @@ -825,6 +836,27 @@ export class PolicyProxyHandler<DbClient extends DbClientContract> implements Pr
}))
);
}

const updateGuard = this.utils.getAuthGuard(db, model, 'update');
if (this.utils.isTrue(updateGuard) || this.utils.isFalse(updateGuard)) {
// injects simple auth guard into where clause
this.utils.injectAuthGuardAsWhere(db, args, model, 'update');
} else {
// we have to process `updateMany` separately because the guard may contain
// filters using relation fields which are not allowed in nested `updateMany`
const reversedQuery = this.utils.buildReversedQuery(context);
const updateWhere = this.utils.and(reversedQuery, updateGuard);
if (this.shouldLogQuery) {
this.logger.info(
`[policy] \`updateMany\` ${model}:\n${formatObject({
where: updateWhere,
data: args.data,
})}`
);
}
await db[model].updateMany({ where: updateWhere, data: args.data });
delete context.parent.updateMany;
}
},

create: async (model, args, context) => {
Expand Down Expand Up @@ -931,9 +963,21 @@ export class PolicyProxyHandler<DbClient extends DbClientContract> implements Pr
},

deleteMany: async (model, args, context) => {
// inject delete guard
const guard = await this.utils.getAuthGuard(db, model, 'delete');
context.parent.deleteMany = this.utils.and(args, guard);
if (this.utils.isTrue(guard) || this.utils.isFalse(guard)) {
// inject simple auth guard
context.parent.deleteMany = this.utils.and(args, guard);
} else {
// we have to process `deleteMany` separately because the guard may contain
// filters using relation fields which are not allowed in nested `deleteMany`
const reversedQuery = this.utils.buildReversedQuery(context);
const deleteWhere = this.utils.and(reversedQuery, guard);
if (this.shouldLogQuery) {
this.logger.info(`[policy] \`deleteMany\` ${model}:\n${formatObject({ where: deleteWhere })}`);
}
await db[model].deleteMany({ where: deleteWhere });
delete context.parent.deleteMany;
}
},
});

Expand All @@ -958,13 +1002,17 @@ export class PolicyProxyHandler<DbClient extends DbClientContract> implements Pr
}
for (const k of Object.keys(args)) {
const field = resolveField(this.modelMeta, model, k);
if (field?.isId || field?.isForeignKey) {
if (this.isAutoIncrementIdField(field) || field?.isForeignKey) {
return true;
}
}
return false;
}

private isAutoIncrementIdField(field: FieldInfo) {
return field.isId && field.isAutoIncrement;
}

async updateMany(args: any) {
if (!args) {
throw prismaClientValidationError(this.prisma, 'query argument is required');
Expand All @@ -976,7 +1024,7 @@ export class PolicyProxyHandler<DbClient extends DbClientContract> implements Pr
this.utils.tryReject(this.prisma, this.model, 'update');

args = this.utils.clone(args);
this.utils.injectAuthGuard(this.prisma, args, this.model, 'update');
this.utils.injectAuthGuardAsWhere(this.prisma, args, this.model, 'update');

if (this.utils.hasAuthGuard(this.model, 'postUpdate') || this.utils.getZodSchema(this.model)) {
// use a transaction to do post-update checks
Expand All @@ -989,7 +1037,7 @@ export class PolicyProxyHandler<DbClient extends DbClientContract> implements Pr
select = { ...select, ...preValueSelect };
}
const currentSetQuery = { select, where: args.where };
this.utils.injectAuthGuard(tx, currentSetQuery, this.model, 'read');
this.utils.injectAuthGuardAsWhere(tx, currentSetQuery, this.model, 'read');

if (this.shouldLogQuery) {
this.logger.info(`[policy] \`findMany\` ${this.model}: ${formatObject(currentSetQuery)}`);
Expand Down Expand Up @@ -1118,7 +1166,7 @@ export class PolicyProxyHandler<DbClient extends DbClientContract> implements Pr

// inject policy conditions
args = args ?? {};
this.utils.injectAuthGuard(this.prisma, args, this.model, 'delete');
this.utils.injectAuthGuardAsWhere(this.prisma, args, this.model, 'delete');

// conduct the deletion
if (this.shouldLogQuery) {
Expand All @@ -1139,7 +1187,7 @@ export class PolicyProxyHandler<DbClient extends DbClientContract> implements Pr
args = this.utils.clone(args);

// inject policy conditions
this.utils.injectAuthGuard(this.prisma, args, this.model, 'read');
this.utils.injectAuthGuardAsWhere(this.prisma, args, this.model, 'read');

if (this.shouldLogQuery) {
this.logger.info(`[policy] \`aggregate\` ${this.model}:\n${formatObject(args)}`);
Expand All @@ -1155,7 +1203,7 @@ export class PolicyProxyHandler<DbClient extends DbClientContract> implements Pr
args = this.utils.clone(args);

// inject policy conditions
this.utils.injectAuthGuard(this.prisma, args, this.model, 'read');
this.utils.injectAuthGuardAsWhere(this.prisma, args, this.model, 'read');

if (this.shouldLogQuery) {
this.logger.info(`[policy] \`groupBy\` ${this.model}:\n${formatObject(args)}`);
Expand All @@ -1166,7 +1214,7 @@ export class PolicyProxyHandler<DbClient extends DbClientContract> implements Pr
async count(args: any) {
// inject policy conditions
args = args ? this.utils.clone(args) : {};
this.utils.injectAuthGuard(this.prisma, args, this.model, 'read');
this.utils.injectAuthGuardAsWhere(this.prisma, args, this.model, 'read');

if (this.shouldLogQuery) {
this.logger.info(`[policy] \`count\` ${this.model}:\n${formatObject(args)}`);
Expand Down
Loading