|
| 1 | +import type { SanitizedCollectionConfig } from '../../collections/config/types.js' |
| 2 | +import type { FlattenedField } from '../../fields/config/types.js' |
| 3 | +import type { SanitizedGlobalConfig } from '../../globals/config/types.js' |
| 4 | +import type { PayloadRequest, Sort, Where } from '../../types/index.js' |
| 5 | + |
| 6 | +import { getLocalizedPaths } from '../getLocalizedPaths.js' |
| 7 | +import { validateQueryPaths } from './validateQueryPaths.js' |
| 8 | + |
| 9 | +type Args = { |
| 10 | + overrideAccess: boolean |
| 11 | + req: PayloadRequest |
| 12 | + sort?: Sort |
| 13 | + versionFields?: FlattenedField[] |
| 14 | +} & ( |
| 15 | + | { |
| 16 | + collectionConfig: SanitizedCollectionConfig |
| 17 | + globalConfig?: undefined |
| 18 | + } |
| 19 | + | { |
| 20 | + collectionConfig?: undefined |
| 21 | + globalConfig: SanitizedGlobalConfig |
| 22 | + } |
| 23 | +) |
| 24 | + |
| 25 | +/** |
| 26 | + * Ensures sort paths are subject to the same field-read access checks as query `where` paths, |
| 27 | + * since database sorting happens before response-time field redaction. |
| 28 | + */ |
| 29 | +export const validateSortQuery = async ({ |
| 30 | + collectionConfig, |
| 31 | + globalConfig, |
| 32 | + overrideAccess, |
| 33 | + req, |
| 34 | + sort, |
| 35 | + versionFields, |
| 36 | +}: Args): Promise<void> => { |
| 37 | + if (overrideAccess || !sort) { |
| 38 | + return |
| 39 | + } |
| 40 | + |
| 41 | + const fields = versionFields || (globalConfig || collectionConfig).flattenedFields |
| 42 | + const sortFields = Array.isArray(sort) ? sort : [sort] |
| 43 | + const where: Where = {} |
| 44 | + |
| 45 | + for (const sortField of sortFields) { |
| 46 | + const path = sortField.replace(/^-/, '').replace(/__/g, '.') |
| 47 | + const paths = getLocalizedPaths({ |
| 48 | + collectionSlug: collectionConfig?.slug, |
| 49 | + fields, |
| 50 | + globalSlug: globalConfig?.slug, |
| 51 | + incomingPath: path, |
| 52 | + locale: req.locale!, |
| 53 | + overrideAccess: true, |
| 54 | + payload: req.payload, |
| 55 | + }) |
| 56 | + |
| 57 | + if (path !== 'id' && path !== '_id' && paths.every(({ invalid }) => !invalid)) { |
| 58 | + where[path] = { exists: true } |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + if (Object.keys(where).length === 0) { |
| 63 | + return |
| 64 | + } |
| 65 | + |
| 66 | + if (collectionConfig) { |
| 67 | + await validateQueryPaths({ |
| 68 | + collectionConfig, |
| 69 | + overrideAccess, |
| 70 | + req, |
| 71 | + versionFields, |
| 72 | + where, |
| 73 | + }) |
| 74 | + } else { |
| 75 | + await validateQueryPaths({ |
| 76 | + globalConfig, |
| 77 | + overrideAccess, |
| 78 | + req, |
| 79 | + versionFields, |
| 80 | + where, |
| 81 | + }) |
| 82 | + } |
| 83 | +} |
0 commit comments