(query: Query)
| 258 | } |
| 259 | |
| 260 | function validateRelationalDepth(query: Query) { |
| 261 | const maxRelationalDepth = Number(env['MAX_RELATIONAL_DEPTH']) > 2 ? Number(env['MAX_RELATIONAL_DEPTH']) : 2; |
| 262 | |
| 263 | // Process the fields in the same way as api/src/utils/get-ast-from-query.ts |
| 264 | let fields = ['*']; |
| 265 | |
| 266 | if (query.fields) { |
| 267 | fields = query.fields; |
| 268 | } |
| 269 | |
| 270 | /** |
| 271 | * When using aggregate functions, you can't have any other regular fields |
| 272 | * selected. This makes sure you never end up in a non-aggregate fields selection error |
| 273 | */ |
| 274 | if (Object.keys(query.aggregate || {}).length > 0) { |
| 275 | fields = []; |
| 276 | } |
| 277 | |
| 278 | /** |
| 279 | * Similarly, when grouping on a specific field, you can't have other non-aggregated fields. |
| 280 | * The group query will override the fields query |
| 281 | */ |
| 282 | if (query.group) { |
| 283 | fields = query.group; |
| 284 | } |
| 285 | |
| 286 | fields = uniq(fields); |
| 287 | |
| 288 | for (const field of fields) { |
| 289 | // Resolve user-defined aliases before measuring depth so that |
| 290 | // alias={"myAlias":"json(category_id.metadata, color)"} is checked |
| 291 | // against the actual relational path, not just the alias key. |
| 292 | const resolved = query.alias?.[field] ?? field; |
| 293 | |
| 294 | if (getFieldRelationalDepth(resolved) > maxRelationalDepth) { |
| 295 | throw new InvalidQueryError({ reason: 'Max relational depth exceeded' }); |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | if (query.filter) { |
| 300 | const filterRelationalDepth = calculateFieldDepth(query.filter); |
| 301 | |
| 302 | if (filterRelationalDepth > maxRelationalDepth) { |
| 303 | throw new InvalidQueryError({ reason: 'Max relational depth exceeded' }); |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | if (query.sort) { |
| 308 | for (const sort of query.sort) { |
| 309 | const field = sort.startsWith('-') ? sort.slice(1) : sort; |
| 310 | const resolved = query.alias?.[field] ?? field; |
| 311 | |
| 312 | if (getFieldRelationalDepth(resolved) > maxRelationalDepth) { |
| 313 | throw new InvalidQueryError({ reason: 'Max relational depth exceeded' }); |
| 314 | } |
| 315 | } |
| 316 | } |
| 317 |
no test coverage detected