Skip to content

fix: disallow undefined where clause #21062

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

Draft
wants to merge 11 commits into
base: main
Choose a base branch
from
Draft
21 changes: 16 additions & 5 deletions apps/web/playwright/fixtures/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -684,6 +684,8 @@ export const createUsersFixture = (
},
deleteAll: async () => {
const ids = store.users.map((u) => u.id);
const orgIds = store.teams.map((org) => org.id);
const trackedEmails = store.trackedEmails.map((e) => e.email);
if (emails) {
const emailMessageIds: string[] = [];
for (const user of store.trackedEmails.concat(store.users.map((u) => ({ email: u.email })))) {
Expand All @@ -699,11 +701,20 @@ export const createUsersFixture = (
}
}

await prisma.user.deleteMany({ where: { id: { in: ids } } });
// Delete all users that were tracked by email(if they were created)
await prisma.user.deleteMany({ where: { email: { in: store.trackedEmails.map((e) => e.email) } } });
await prisma.team.deleteMany({ where: { id: { in: store.teams.map((org) => org.id) } } });
await prisma.secondaryEmail.deleteMany({ where: { userId: { in: ids } } });
if (ids.length) {
await prisma.user.deleteMany({ where: { id: { in: ids } } });
await prisma.secondaryEmail.deleteMany({ where: { userId: { in: ids } } });
}

if (orgIds.length) {
await prisma.team.deleteMany({ where: { id: { in: orgIds } } });
}

if (trackedEmails.length) {
// Delete all users that were tracked by email(if they were created)
await prisma.user.deleteMany({ where: { email: { in: trackedEmails } } });
}

store.users = [];
store.teams = [];
store.trackedEmails = [];
Expand Down

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { describe, it, expect } from "vitest";

import { validateWhereClause } from "./disallow-undefined-where-clause";

describe("Disallow undefined where", () => {
it("validateWhereClause should throw exception when the 'in' field of where object is undefined", async () => {
const where = {
id: {
in: undefined,
},
};

expect(() => validateWhereClause(where)).toThrowError(
'The "in" value for the field "id" cannot be undefined.'
);
});

it("validateWhereClause should throw exception when a field of where object is undefined", async () => {
const where = {
from: undefined,
};

expect(() => validateWhereClause(where)).toThrowError(
'The value for the field "from" cannot be undefined.'
);
});

it("validateWhereClause should not throw exception when the where object does not contain undefined values", async () => {
const where = {
id: {
in: [1, 2, 3],
},
name: "test name",
};

validateWhereClause(where);
});

it("validateWhereClause should not throw exception when the where object contain null values", async () => {
const where = {
teamId: null,
parentId: null,
};

validateWhereClause(where);
});

it("validateWhereClause should throw exception when the where object contain null values and 'in' field is undefined", async () => {
const where = {
teamId: null,
parentId: null,
id: {
in: undefined,
},
};

expect(() => validateWhereClause(where)).toThrowError(
'The "in" value for the field "id" cannot be undefined.'
);
});

it("validateWhereClause should throw exception when the where object is undefined", async () => {
Copy link
Contributor

Choose a reason for hiding this comment

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

Unnecessary async keyword in test function that doesn't use await

const where = undefined;

expect(() => validateWhereClause(where)).toThrowError('The "where" clause cannot be undefined.');
});

it("validateWhereClause should throw exception when the where object is {}", async () => {
const where = {};

expect(() => validateWhereClause(where)).toThrowError('The "where" clause cannot be an empty object {}.');
});

it("validateWhereClause should throw exception when the where object is []", async () => {
const where = [];

expect(() => validateWhereClause(where)).toThrowError('The "where" clause cannot be an empty array [].');
});

it("validateWhereClause should throw exception when the 'in' field of where object is []", async () => {
const where = {
id: {
in: [],
},
};

expect(() => validateWhereClause(where)).toThrowError(
'The "in" value for the field "id" cannot be an empty array [].'
);
});
});
Comment on lines +62 to +91
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Added new test

66 changes: 66 additions & 0 deletions packages/prisma/extensions/disallow-undefined-where-clause.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { Prisma } from "@prisma/client";

export const validateWhereClause = (where: any) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

Using 'any' type reduces type safety and prevents TypeScript from providing helpful errors

// Check if where is undefined
if (where === undefined) {
throw new Error('The "where" clause cannot be undefined.');

Check failure on line 6 in packages/prisma/extensions/disallow-undefined-where-clause.ts

View workflow job for this annotation

GitHub Actions / Tests / Integration

apps/api/v1/test/lib/bookings/_get.integration-test.ts > GET /api/bookings > Returns bookings for all users when accessed by system-wide admin

Error: The "where" clause cannot be undefined. ❯ validateWhereClause packages/prisma/extensions/disallow-undefined-where-clause.ts:6:11 ❯ Array.findMany packages/prisma/extensions/disallow-undefined-where-clause.ts:60:11 ❯ node_modules/@prisma/client/runtime/library.js:34:4829 ❯ i node_modules/@prisma/client/runtime/library.js:123:987 ❯ PrismaPromise.then node_modules/@prisma/client/runtime/library.js:123:1063

Check failure on line 6 in packages/prisma/extensions/disallow-undefined-where-clause.ts

View workflow job for this annotation

GitHub Actions / Tests / Integration

packages/features/flags/features.repository.integration-test.ts > FeaturesRepository Integration Tests > checkIfFeatureIsEnabledGlobally > should return true when feature is enabled globally

Error: The "where" clause cannot be undefined. ❯ validateWhereClause packages/prisma/extensions/disallow-undefined-where-clause.ts:6:11 ❯ Array.findMany packages/prisma/extensions/disallow-undefined-where-clause.ts:60:11 ❯ node_modules/@prisma/client/runtime/library.js:34:4829 ❯ i node_modules/@prisma/client/runtime/library.js:123:987 ❯ PrismaPromise.then node_modules/@prisma/client/runtime/library.js:123:1063

Check failure on line 6 in packages/prisma/extensions/disallow-undefined-where-clause.ts

View workflow job for this annotation

GitHub Actions / Tests / Integration

packages/features/flags/features.repository.integration-test.ts > FeaturesRepository Integration Tests > checkIfFeatureIsEnabledGlobally > should return false when feature is not enabled globally

Error: The "where" clause cannot be undefined. ❯ validateWhereClause packages/prisma/extensions/disallow-undefined-where-clause.ts:6:11 ❯ Array.findMany packages/prisma/extensions/disallow-undefined-where-clause.ts:60:11 ❯ node_modules/@prisma/client/runtime/library.js:34:4829 ❯ i node_modules/@prisma/client/runtime/library.js:123:987 ❯ PrismaPromise.then node_modules/@prisma/client/runtime/library.js:123:1063
}

// Check if where is an empty object
if (typeof where === "object" && !Array.isArray(where) && Object.keys(where || {}).length === 0) {
throw new Error('The "where" clause cannot be an empty object {}.');
}

// Check if where is an empty array
if (Array.isArray(where) && where.length === 0) {
throw new Error('The "where" clause cannot be an empty array [].');
}

if (where) {
for (const key in where) {
// INFO: Since this is for $allModels, we don't have a way to get the correct
// where type
const whereInput = where[key as any] as any;
let message;
if (whereInput === undefined) {
message = `The value for the field "${key}" cannot be undefined.`;
throw new Error(message);
}

if (whereInput === null) {
continue;
}

if (whereInput.hasOwnProperty("in") && typeof whereInput.in === "undefined") {
message = `The "in" value for the field "${key}" cannot be undefined.`;
throw new Error(message);
}

if (whereInput.hasOwnProperty("in") && Array.isArray(whereInput.in) && whereInput.in.length === 0) {
message = `The "in" value for the field "${key}" cannot be an empty array [].`;
throw new Error(message);

Check failure on line 41 in packages/prisma/extensions/disallow-undefined-where-clause.ts

View workflow job for this annotation

GitHub Actions / Tests / Integration

packages/lib/server/getLuckyUser.integration-test.ts > getOrderedListOfLuckyUsers Integration tests > should sort as per availableUsers if no other criteria like weight/priority/calibration (TODO: make it independent of availableUsers order)

Error: The "in" value for the field "userId" cannot be an empty array []. ❯ validateWhereClause packages/prisma/extensions/disallow-undefined-where-clause.ts:41:15 ❯ Array.findMany packages/prisma/extensions/disallow-undefined-where-clause.ts:60:11 ❯ node_modules/@prisma/client/runtime/library.js:34:4829 ❯ i node_modules/@prisma/client/runtime/library.js:123:987 ❯ PrismaPromise.then node_modules/@prisma/client/runtime/library.js:123:1063

Check failure on line 41 in packages/prisma/extensions/disallow-undefined-where-clause.ts

View workflow job for this annotation

GitHub Actions / Tests / Integration

packages/lib/server/getLuckyUser.integration-test.ts > getLuckyUser Integration tests > should not consider no show bookings for round robin: > When a host is no show, that is chosen when competing with another host that showed up for the booking

Error: The "in" value for the field "userId" cannot be an empty array []. ❯ validateWhereClause packages/prisma/extensions/disallow-undefined-where-clause.ts:41:15 ❯ Array.findMany packages/prisma/extensions/disallow-undefined-where-clause.ts:60:11 ❯ node_modules/@prisma/client/runtime/library.js:34:4829 ❯ i node_modules/@prisma/client/runtime/library.js:123:987 ❯ PrismaPromise.then node_modules/@prisma/client/runtime/library.js:123:1063
}
}
}
};

export function disallowUndefinedWhereExtension() {
return Prisma.defineExtension({
query: {
$allModels: {
async deleteMany({ args, query }) {
validateWhereClause(args.where);
return query(args);
},
async updateMany({ args, query }) {
validateWhereClause(args.where);
return query(args);
},
async findMany({ args, query }) {
validateWhereClause(args.where);
return query(args);
},
},
},
});
}
6 changes: 3 additions & 3 deletions packages/prisma/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { PrismaClient as PrismaClientWithoutExtension } from "@prisma/client";
import { withAccelerate } from "@prisma/extension-accelerate";

import { bookingIdempotencyKeyExtension } from "./extensions/booking-idempotency-key";
import { disallowUndefinedDeleteUpdateManyExtension } from "./extensions/disallow-undefined-delete-update-many";
import { disallowUndefinedWhereExtension } from "./extensions/disallow-undefined-where-clause";
import { excludeLockedUsersExtension } from "./extensions/exclude-locked-users";
import { excludePendingPaymentsExtension } from "./extensions/exclude-pending-payment-teams";
import { usageTrackingExtention } from "./extensions/usage-tracking";
Expand Down Expand Up @@ -47,7 +47,7 @@ export const customPrisma = (options?: Prisma.PrismaClientOptions) =>
.$extends(excludeLockedUsersExtension())
.$extends(excludePendingPaymentsExtension())
.$extends(bookingIdempotencyKeyExtension())
.$extends(disallowUndefinedDeleteUpdateManyExtension())
.$extends(disallowUndefinedWhereExtension())
.$extends(withAccelerate());

// If any changed on middleware server restart is required
Expand All @@ -61,7 +61,7 @@ const prismaWithClientExtensions = prismaWithoutClientExtensions
.$extends(excludeLockedUsersExtension())
.$extends(excludePendingPaymentsExtension())
.$extends(bookingIdempotencyKeyExtension())
.$extends(disallowUndefinedDeleteUpdateManyExtension())
.$extends(disallowUndefinedWhereExtension())
.$extends(withAccelerate());

export const prisma = globalForPrisma.prismaWithClientExtensions || prismaWithClientExtensions;
Expand Down
Loading