All files / src/databases/mongo/services maskService.ts

99.25% Statements 268/270
84.7% Branches 72/85
100% Functions 10/10
99.25% Lines 268/270

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 2701x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 9x 5x 5x 5x 1x 2x 2x 2x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 1x 1x 7x 7x 1x 1x 1x 1x 1x 1x 1x 20x 20x 20x 20x 20x 20x 20x 20x 12x 12x 20x 4x 4x 4x 4x 4x 4x 4x 4x 4x 28x 20x 20x 4x 4x 4x 4x 4x 20x 20x 20x 4x 4x 4x 4x 20x 20x 20x 3x 3x 3x 9x 47x 47x 9x 9x 20x 1x 1x 1x 3x 3x 1x 1x 1x 3x 1x 1x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 11x 11x 9x 7x 7x 7x 7x 7x 7x 11x 152x 152x 13x 13x     13x 152x 11x 7x 7x 7x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 9x 9x 12x 12x 12x 12x 6x 3x 3x 3x 3x 3x 3x 3x 3x 3x 4x 4x 3x 6x 6x 12x 12x 12x 12x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 4x 4x 4x 2x 2x 1x 1x 1x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 1x 12x 12x 2x 2x 2x 12x 12x 1x 50x 50x 50x 1x 1x 1x 1x 1x 1x 1x 1x 19x 19x 14x 14x 14x 14x 14x 19x
 
 
import { appliableHooksForUser } from '../../0_hooks/appliableHookForUser'
import { forEachPopulateFieldRecursive } from './populateService'
import { PopulateConfig, PopulateConfigWithoutStringSyntax } from '../types/mongoDbTypes'
import { DaoGenericMethods, MaskHook, DaoHookSharedParsed } from '../../../types/core.types'
import { getProjectDatabaseDaosForModel, getProjectDatabaseModels } from '../../../helpers/getProjectModelsAndDaos'
import { AllDbIds } from '../../../cache/dbs/index.generated'
 
import { getId, objForceWrite, escapeRegexp, flattenObject, unflattenObject } from 'topkat-utils'
 
export type Mask<T = any> = DaoHookSharedParsed & MaskHook<T>
 
//----------------------------------------
// MAIN
//----------------------------------------
export async function applyMaskIncludingOnPopulatedFieldsRecursive<ModelName extends string, T extends Record<string, any>>(
    ctx: Ctx,
    method: DaoGenericMethods,
    dbName: AllDbIds,
    modelName: ModelName,
    fields: T,
    recursive = true
): Promise<T> {
 
    const newFieldsParent = await applyMaskOnObjectForUser(ctx, dbName, modelName, method, fields)
 
    if (recursive) await forEachPopulateFieldRecursive(dbName, modelName, newFieldsParent, async (val, fieldAddr, parent, modelName) => {
        if (val && typeof val !== 'string') {
            const newFields = await applyMaskOnObjectForUser(ctx, dbName, modelName, method, val)
            parent[fieldAddr] = newFields
        }
    })
 
    return newFieldsParent
}
 
export async function applyMaskOnObjectForUser<T extends Record<string, any>>(
    ctx: Ctx,
    dbName: AllDbIds,
    modelName: string,
    method: DaoGenericMethods,
    obj: T
): Promise<T> {
    const dao = await getProjectDatabaseDaosForModel(dbName, modelName)
    const maskHooksForModel = dao.mask || []
    const maskFromCache = retrieveMaskFromCacheOrDelete(ctx, modelName, method)
    if (maskFromCache) return applyMaskFlatToModel(maskFromCache.mask, obj)
    const maskHooksForUser = await appliableHooksForUser(ctx, maskHooksForModel, method, 'alwaysReturnFalse', hook => hook.select ? 'alwaysReturnFalse' : 'alwaysReturnTrue')
    const { mask } = await combineMaskHooksAndReturnMaskOrSelectAddrArray(ctx, dbName, modelName, maskHooksForUser, method)
    return mask.length ? applyMaskFlatToModel(mask, obj) : obj
}
 
/** @returns array of field adresses like `organization.team[0].name` /!\ it will not return fields with mongo format, organization.team[0].name should be transformed to organization.team.name
 *
 * Note that _id field is never present in neither mask nor select
 * NOTE 2 /!\ IF THERE IS A SELECT, THE SELECT WINS OVER THE MASK
 */
export async function combineMaskHooksAndReturnMaskOrSelectAddrArray(
    ctx: Ctx,
    dbName: AllDbIds,
    modelName: string,
    maskHooks: Mask[],
    method: DaoGenericMethods
): Promise<{ mask: string[] }> {
 
    if (!maskHooks?.length) return { mask: [] }
 
    const maskFromCache = retrieveMaskFromCacheOrDelete(ctx, modelName, method)
    if (maskFromCache) return maskFromCache
 
    const allAdresses: string[] = []
    let maskedAdresses: string[] = []
 
    const models = await getProjectDatabaseModels()
 
    const modelFlat = models[dbName][modelName]._getDefinitionObjFlat()
 
    Object.entries(modelFlat).forEach(([addr, def]) => {
        if (!def.getDefinitionValue('isParent') && addr !== '_id') {
            allAdresses.push(addr)
        }
    })
 
    const regexps: (string | RegExp)[] = []
    const selectHooks = maskHooks.filter(h => typeof h.select === 'function')
    const isSelect = selectHooks.length
    const hooks = isSelect ? selectHooks : maskHooks
 
    hooks.forEach(mh => {
        const fn = mh.mask || mh.select
        const addresses = Object.keys(flattenObject(fn(ctx)))
        const addrRegexpes = addresses.map(m => convertAddrToRegexpIfWildCard(m))
        regexps.push(...addrRegexpes)
    })
 
    if (isSelect) {
        // SELECT
        maskedAdresses = allAdresses
        for (const selectReg of regexps) {
            maskedAdresses = maskedAdresses.filter(addr => {
                // FILTER ALL ADDR THAT DOESN'T MATCH SELECT
                return typeof selectReg === 'string' ? !matchAddress(selectReg, addr) : !selectReg.test(addr)
            })
        }
    } else {
        // MASK
        for (const maskReg of regexps) {
            for (const addr of allAdresses) {
                const doMatch = typeof maskReg === 'string' ? matchAddress(maskReg, addr) : maskReg.test(addr)
                if (doMatch) {
                    const addrToMask = typeof maskReg === 'string' ? maskReg : addr // allow shortcut when nested object root masked
                    if (!maskedAdresses.includes(addrToMask)) maskedAdresses.push(addrToMask)
                }
            }
        }
    }
 
    // CACHE
    objForceWrite(maskCache, `${getId(ctx)}.${modelName}.${method}`, { mask: maskedAdresses, validUntil: Date.now() + cacheMinutes })
 
    return { mask: maskedAdresses }
}
 
 
 
/** Simply apply maskFlat to a set of fields. MaskFlat is generated by combineAndParseMaskHooks() */
function applyMaskFlatToModel<T extends Record<string, any>>(
    adresses: string[],
    fields: T
): T {
    const isMask = true
    const shouldMatchRegexp = adresses.map(addr => {
        // transform organization.teams[0] TO organization.teams[*]
        if (addr.includes('[')) return convertAddrToRegexpIfWildCard(addr.replace(/\[\d\]/g, '[*]'))
        else return addr
    })
 
    const objFlat = flattenObject(fields)
    const responseFlat = isMask ? objFlat : { _id: getId(objFlat) }
 
    for (const addrRegexp of shouldMatchRegexp) {
        for (const address in objFlat) {
            const doMatch = typeof addrRegexp === 'string' ? (addrRegexp === address || address.startsWith(addrRegexp + '.') || address.startsWith(addrRegexp + '[')) : addrRegexp.test(address)
            if (doMatch) {
                // should be deleted
                if (isMask) delete responseFlat[address]
                // should be added
                else responseFlat[address] = objFlat[address]
            }
        }
    }
 
    return unflattenObject(responseFlat) as T
}
 
//----------------------------------------
// FOR POPULATE
//----------------------------------------
export async function applyMaskToPopulateConfig(
    ctx: Ctx,
    conf: PopulateConfig<any>[],
    dbName: AllDbIds,
    baseModelName: string,
    method: DaoGenericMethods
) {
    const newPopArr = [] as PopulateConfigWithoutStringSyntax<any>[]
    const models = await getProjectDatabaseModels()
    const modelFlat = models[dbName][baseModelName]._getDefinitionObjFlat(true)
 
    for (const popConf of conf) {
 
        const populateConfObj = (typeof popConf === 'string' ? { path: popConf } : popConf) as PopulateConfigWithoutStringSyntax<any>
 
        const fieldName = populateConfObj.path
        const modelNameForField = modelFlat?.[fieldName]?._refValue
 
        if (populateConfObj.select && typeof populateConfObj.select !== 'string') throw ctx.error.wrongValueForParam({ message: `onlyStringTypeIsAllowedInPopulateSelect`, fieldName, popConf })
        if (!modelNameForField) throw ctx.error.wrongValueForParam({ message: `modelDoNotExistForFieldNameInPopulate`, fieldName, popConf, fnName: 'applyMaskToPopulateConfig' })
 
        if ('populate' in populateConfObj) {
            populateConfObj.populate = await applyMaskToPopulateConfig(ctx, populateConfObj.populate, dbName, modelNameForField, method)
        }
 
        const maskArrFromhook = await getMongoMaskForUser(ctx, method, dbName, modelNameForField)
 
        if (maskArrFromhook.length) {
            if (populateConfObj.select) {
                // The difficulty here is to combine select OR mask defined by the user
                // with select OR mask outputed by path match hooks
                // so everything will be converted to MASK so it can be concatenated
                const selectOrMaskFromUser = populateConfObj.select.split(' ')
                const isExclude = selectOrMaskFromUser[0].startsWith('-')
 
                const maskFromUser = isExclude ? selectOrMaskFromUser.filter(f => f.startsWith('-')) : (await getMaskFromSelect(selectOrMaskFromUser, dbName, modelNameForField)).map(v => '-' + v)
 
                for (const field of maskFromUser) {
                    if (!maskArrFromhook.includes(field)) maskArrFromhook.push(field)
                }
            }
            populateConfObj.select = maskArrFromhook.join(' ')
        }
        newPopArr.push(populateConfObj)
    }
    return newPopArr
}
 
//----------------------------------------
// HELPERS
//----------------------------------------
 
export async function getMaskFromSelect(selectArr: string[], dbName: string, modelName: string) {
    const models = await getProjectDatabaseModels()
    const fields = models[dbName][modelName]._getDefinitionObjFlat(true)
    let allFieldsAddr = Object.keys(fields)
    for (const fieldName of selectArr) {
        // const fieldName = fieldName.replace('-', '')
        allFieldsAddr = allFieldsAddr.filter(f => !f.startsWith(fieldName))
    }
    return allFieldsAddr.filter(f => f !== '_id')
}
 
/** @returns mongo select array to put in .select() (Eg. ['name', 'phone']) no negative ('-feldName') will be returned */
export async function getMongoMaskForUser(
    ctx: Ctx,
    method: DaoGenericMethods,
    dbName: AllDbIds,
    modelName: string
) {
 
    const dao = await getProjectDatabaseDaosForModel(dbName, modelName)
 
    const maskHooksForUser = await appliableHooksForUser(
        ctx,
        dao.mask || [],
        method,
        'alwaysReturnFalse',
        hook => hook.select ? 'alwaysReturnFalse' : 'alwaysReturnTrue',
    )
    const { mask } = await combineMaskHooksAndReturnMaskOrSelectAddrArray(ctx, dbName, modelName, maskHooksForUser, method)
    return mask.map(e => '-' + e.replace(/\[\d+\]/g, '')) // replace array syntax user[0].name => user.name
}
 
function convertAddrToRegexpIfWildCard(shouldMatchAddr: string): string | RegExp {
    if (shouldMatchAddr.includes('*')) {
        const regexp = escapeRegexp(shouldMatchAddr, { parseWildcard: true })
        const regStr = '^' + regexp
        return new RegExp(regStr)
    } else return shouldMatchAddr
}
 
function matchAddress(strMatch: string, addr: string) {
    return addr === strMatch || addr.startsWith(strMatch + '.') || addr.startsWith(strMatch + '[')
}
 
//----------------------------------------
// CACHING
//----------------------------------------
const cacheMinutes = 1000 * 60 * 2
type CacheEndpoint = { validUntil: number, mask: string[] }
const maskCache = {} as { [userId: string]: { [modelName: string]: { [method: string]: CacheEndpoint } } }
const retrieveMaskFromCacheOrDelete = (ctx: Ctx, modelName: string, method: string): CacheEndpoint | void => {
    const userId = ctx.isSystem ? 'system' : getId(ctx)
    if (maskCache[userId]?.[modelName]?.[method]) {
        // combineAndParseMaskHooks are trigged multiple times by request, so better caching it
        const { validUntil } = maskCache[userId][modelName][method]
        if (validUntil < Date.now()) delete maskCache[userId][modelName][method]
        else return maskCache[userId][modelName][method]
    }
}