prisma: `where: { shop: undefined }`: The entire table data was accidentally deleted

Bug description

let shop = undefined; // shop is variable, and in some cases, it may be undefined

await prisma.theme.deleteMany({
  where: {
    shop,
  }
})

I left out the shop parameter check, causing the shop to be undefined in some cases, triggering the deletion of the entire table. This operation of Prisma is very risky, I hope to improve it.

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 15
  • Comments: 18 (6 by maintainers)

Commits related to this issue

Most upvoted comments

Hello everyone, in the past weeks we’ve came up with a different proposal for handling that issue, addressing some of the feedback.

TL;DR: we’ll introduce a preview feature flag for making explicitly undefined values invalid in Prisma 5, make it a default in Prisma 6, as well as introduce a safer shortcut for explicitly skipping part of the query.

Full proposal text below, we’d like to hear you comments on it:

Problem

Currently, we treat undefined values as absent. Meaning, that any field set to undefined explicitly is treated as if the query was not supplied at all.

This makes some usecases, listed in the doc pretty convenient, however, it also causes problems: JS language itself is very inconsistent on when it treats null vs undefined as the same values or as two different ones and our behaviour is not the default most people expect.

More importantly, for write queries, the feature can accidentally cause a data loss: https://github.com/prisma/prisma/issues/20169

For read queries, similar situation might cause a data leak.

Overall, there is strong opinion that that feature was a bad decision on our part for a long time. This proposal suggests we change that behaviour.

Proposal

In Prisma 5

Introduce new preview feature strictUndefinedChecks.

When preview feature is on, any value that is explicitly set to undefined will cause a runtime error. Omitting a field must still be allowed - only explicit values are disallowed.

We adjust our doc to recommend setting exactOptionalPropertyTypes setting ([docs](https://www.typescriptlang.org/tsconfig/#exactOptionalPropertyTypes)) to get equivalent type error.

To simplify the migration, we also introduce Prisma.skip symbol which would act as “ignore this part of the query as if the field were not set” instead of undefined.

So these two calls are equivalent:

prisma.user.create({
   name: 'Steve the rat',
})

prisma.user.create({
   name: 'Steve the rat',
   profilePicture: Prisma.skip
})

In that case, migration from undefined to Prisma.skip is relatively simple:

let optionalProfilePicture: ProfilePicture | undefined

// before
prisma.user.create({
   name: 'Steve the rat',
   profilePicture: optionalProfilePicture
})

// after
prisma.user.create({
   name: 'Steve the rat',
   profilePicture: optionalProfilePicture ?? Prisma.skip
})

It is a safer option, because users are forced to be explicit about their intent.

In Prisma 6

We remove strictUndefinedChecks preview feature and make this behavior a default. Depending on feedback, we might introduce a generator option to revert back to old, unsafe, behaviour.

This is extremely dangerous, I do not think it’s being treated as such. You are offering an abstraction that does the opposite of what the SQL standard does (and the majority of your users understand SQL before they understand Prisma). When filtering by emptiness (where id in [], or undefined), no database will return records, but Prisma does. This is even worse in the case of deletes.

I fear this is one famous case of mass-deletion away from a PR disaster for Prisma. I am a happy user of the library, mind you, but I’d recommend more urgency to this issue. I spent 2 minutes googling, and I already found a case of someone who had to suffer from this issue: https://www.farmin.dev/posts/35ad668d-29ae-4d86-8b4a-126b6d561aaa.

From our point of view this is not surprising and a “bug we have to fix”, but how Prisma is currently designed to work: https://www.prisma.io/docs/concepts/components/prisma-client/null-and-undefined We know this can be dangerous, but it has been like this for quite some while and switching would also have other deficits.

So as soon as we find the proper issue that requests us to change this, we will close this issue here as a duplicate.

We unfortunately ran into this issue (luckily had snapshots we could restore), and I had to write some middleware because this was super dangerous. I hope this can help somebody!

import { isEmpty } from "lodash";
import { Prisma } from "prisma/generated";

/**
 * Middleware featured below
 */

// This naming convention specifically matches the
// safe word to the exported constant to support the
// middleware error handling
export const safeWordDelete = "FORCE_DELETE_ALL";
export const FORCE_DELETE_ALL = { id: safeWordDelete };

export const safeWordFind = "FIND_ALL";
export const FIND_ALL = { id: safeWordFind };

export const safeWordUpdate = "UPDATE_ALL";
export const UPDATE_ALL = { id: safeWordUpdate };

/**
 * If you have found yourself here after a hard lesson:
 *
 * These middleware specifically do NOT guard in the case of a nested find, update, delete.
 * These middleware also don't protect in the case of an undefined variable being passed in alongside a specific condition.
 *
 * Ex: {
 *    id, // undefined
 *    otherAttr: null
 * }
 *
 * The above where clause will delete/modify/find all regardless of undefined status of variable appId.
 *
 * The !! best !! guard here is proper type adherence - do not bang, do not coerce.
 */
const _guardEnMasse = ({
  params,
  actions,
  safeWord,
}: {
  params: Prisma.MiddlewareParams;
  actions: Prisma.MiddlewareParams["action"][];
  safeWord: string;
}) => {
  // Check if empty, if not and safeWord is provided, then set where = {} and proceed to execute
  if (actions.includes(params.action)) {
    // Don't allow delete all queries
    if (isEmpty(params.args.where)) {
      throw new Error(
        `It looks like you just tried to perform a ${params.action} on all of the ${params.model}s. If this was intentional, pass 'where: ${safeWord}'`,
      );
    }
  }

  if (params.args?.where?.id === safeWord) {
    params.args.where = {};
  }
};

export const guardEnMasse: PrismaMiddleware = async (params, next) => {
  /* DELETION PROTECTION MIDDLEWARE */
  _guardEnMasse({
    actions: ["delete", "deleteMany"],
    params,
    safeWord: safeWordDelete,
  });

  /* MASS FIND PROTECTION MIDDLEWARE */
  _guardEnMasse({
    actions: ["findMany"],
    params,
    safeWord: safeWordFind,
  });

  /* MASS UPDATE PROTECTION MIDDLEWARE */
  _guardEnMasse({
    actions: ["updateMany"],
    params,
    safeWord: safeWordUpdate,
  });

  return next(params);
};

and then

const dbClient = new PrismaClient();

dbClient.$use(guardEnMasse);

const whoops = undefined;

// Throws an error
dbClient.sensitiveData.deleteMany({ where: { id: whoops } });

// Deletes everything
dbClient.insensitiveData.deleteMany({ where: FORCE_DELETE_ALL });

Best guard here is strict type safety and attribute validation ahead of db writes. Also, always always always backup your production database!

I don’t care if breaking change were to be introduced, this evil shall be corrected.

The proposal is to change the behavior of undefined so it is exactly the same as null - it will filter for the null value in the database.

undefined and null aren’t the same though. While moving in this direction is theoretically safer, it’s not as safe as it should be. Honestly, I believe the correct answer here is that Prisma should just throw an error if an undefined value is passed.

Let’s say we have this method in Typescript.

fooQuery = (userId: string) => {
    return this.prisma.teamTask.findMany({
      where: {
        assigneeUserId: userId,
      }
    })
  }

In this case, if for some unchecked reason userId ends up being undefined. There query would just end up being

return this.prisma.teamTask.findMany({
      where: {
        assigneeUserId: null,
      },
    })

which ultimately has the same issue when you deal with DBs with significant scale. This could potentially query extreme amounts of data just in the same way the current behavior does.

To follow up: This feature is now live as the strictUndefinedChecks Preview feature in Prisma ORM 5.20.0. Please let us know what you think.

If you have any feedback, please leave it on the GitHub Discussion below

Docs: https://www.prisma.io/docs/orm/prisma-client/special-fields-and-types/null-and-undefined Feedback: https://github.com/prisma/prisma/discussions/25271

Hey, thanks for the report, we are aware of this issue and I fully agree with you that it can be dangerous. We should improve it.

The release notes say that this will be the default in the next major version. While not a blocker, that will require many changes with how my team currently uses prisma.

It’s quite common for us to use prisma to implement REST GET endpoints to list entities that can have many optional query params. For that sort of use case it’ll require us to make many changes to fallback to Prisma.skip.

Is it possible to make this behavior configurable in the future?