Objection.js:添加了所有where子句后是否可以将它们括在括号中?

问题描述

代码示例
// Creates an Objection query. 
// I have no control over the creation of the query. I can only modify the query after it has been created.
// Example: "select `todos`.* from `todos` where `text` = ?"
const objectionQuery = thirdPartyService.createQuery(userControlledInput);
// Adds an access check. Example "select `todos`.* from `todos` where `text` = ? and `userId` = ?"
objectionQuery.andWhere("userId",currentUser.id);

上面的示例有一个安全漏洞。如果thirdPartyService生成如下查询:

select `todos`.* from `todos` where `text` = ? or `id` = ?

然后添加访问检查后,我们将得到以下查询:

select `todos`.* from `todos` where `text` = ? or `id` = ? and `userId` = ?

此查询可以返回不属于当前用户的数据。 要解决此错误,我们需要将用户控制的条件括在括号中:

select `todos`.* from `todos` where (`text` = ? or `id` = ?) and `userId` = ?

但是我该如何使用Objection查询构建器来做到这一点?我想象这样的事情:

const objectionQuery = thirdPartyService.createQuery(userControlledInput);
wrapWhereClauses(objectionQuery);
objectionQuery.andWhere("userId",currentUser.id);

解决方法

一种方法可能是将原始查询包装为子查询/临时表:

MyModel.query().from(thirdPartyService.createQuery(userControlledInput)).where(...)

(请告诉我这是否可行,我还没有测试过)

,

来自docs:您可以通过将函数传递给任何where*方法来为查询添加括号:

await Todo.query()
  .where('userId',1)
  .where(builder => {
    builder.where('text',2).orWhere('id',3);
  });

将导致

select * from "todos" where "userId" = 1 and ("text" = 2 or "id" = 3)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...