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 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 | 1x 1x 1x 1x 1x 10x 10x 10x 1x 3993x 3993x 3993x 3993x 3993x 3993x 3993x 3993x 3993x 3993x 3993x 3993x 3993x 3993x 57x 47x 47x 10x 24x 33x 64x 129x 123x 123x 123x 123x 123x 123x 123x 50x 50x 50x 50x 1810x 1810x 75x 75x 26x 13x 62x 62x 2x 1x 67x 8x 67x 67x 67x 67x 67x 67x 27x 27x 27x 27x 8x 9x 19x 19x 19x 19x 19x 67x 67x 26x 26x 26x 26x 26x 26x 26x 67x 20x 20x 20x 20x 20x 20x 20x 20x | import ValidationError from '../../validationError'; import { stripFields, convertJsonToString, duplicateItems, obfuscateSensitiveValues, stripObfuscatedFieldsFromPayload, detectInsufficientScopeError, } from '../../utils'; import log from '../../../logger'; import { calculateChanges } from '../../calculateChanges'; import { Asset, Assets, Auth0APIClient, CalculatedChanges } from '../../../types'; import { ConfigFunction } from '../../../configFactory'; export function order(value) { return function decorator(t, n, descriptor) { descriptor.value.order = value; // eslint-disable-line return descriptor; }; } type ApiMethodOverride = string | Function; export default class APIHandler { config: ConfigFunction; id: string; type: string; updated: number; created: number; deleted: number; existing: null | Asset | Asset[]; client: Auth0APIClient; // TODO: apply stronger types to Auth0 API client identifiers: string[]; objectFields: string[]; sensitiveFieldsToObfuscate: string[]; stripUpdateFields: string[]; //Fields to strip from payload when updating stripCreateFields: string[]; //Fields to strip from payload when creating name?: string; // TODO: understand if any handlers actually leverage `name` property functions: { getAll: ApiMethodOverride; update: ApiMethodOverride; create: ApiMethodOverride; delete: ApiMethodOverride; }; constructor(options: { id?: APIHandler['id']; config: ConfigFunction; type: APIHandler['type']; client: Auth0APIClient; objectFields?: APIHandler['objectFields']; identifiers?: APIHandler['identifiers']; stripUpdateFields?: APIHandler['stripUpdateFields']; sensitiveFieldsToObfuscate?: APIHandler['sensitiveFieldsToObfuscate']; stripCreateFields?: APIHandler['stripCreateFields']; functions: { getAll?: ApiMethodOverride; update?: ApiMethodOverride; create?: ApiMethodOverride; delete?: ApiMethodOverride; }; }) { this.config = options.config; this.type = options.type; this.id = options.id || 'id'; this.client = options.client; this.existing = null; this.identifiers = options.identifiers || ['id', 'name']; this.objectFields = options.objectFields || []; this.stripUpdateFields = [...(options.stripUpdateFields || []), this.id]; this.sensitiveFieldsToObfuscate = options.sensitiveFieldsToObfuscate || []; this.stripCreateFields = options.stripCreateFields || []; this.functions = { getAll: 'getAll', create: 'create', delete: 'delete', update: 'update', ...(options.functions || {}), }; this.updated = 0; this.created = 0; this.deleted = 0; } getClientFN(fn: ApiMethodOverride): Function { if (typeof fn === 'string') { const client = this.client[this.type]; return client[fn].bind(client); } return fn; } didDelete(item: Asset): void { log.info(`Deleted [${this.type}]: ${this.objString(item)}`); } didCreate(item: Asset): void { log.info(`Created [${this.type}]: ${this.objString(item)}`); } didUpdate(item: Asset): void { log.info(`Updated [${this.type}]: ${this.objString(item)}`); } objString(item: Asset): string { return convertJsonToString(item); } async getType(): Promise<Asset | Asset[] | null> { // Each type to impl how to get the existing as its not consistent across the mgnt api. throw new Error(`Must implement getType for type ${this.type}`); } async load(): Promise<{ [key: string]: Asset | Asset[] | null }> { // Load Asset from Tenant const data = await (async () => { const { data, hadSufficientScopes, requiredScopes } = await detectInsufficientScopeError< Asset | Asset[] >(this.getType.bind(this)); Iif (!hadSufficientScopes) { log.warn(`Cannot retrieve ${this.type} due to missing scopes: ${requiredScopes}`); return null; } log.info(`Retrieving ${this.type} data from Auth0`); return data; })(); this.existing = obfuscateSensitiveValues(data, this.sensitiveFieldsToObfuscate); return { [this.type]: this.existing }; } async calcChanges(assets: Assets): Promise<CalculatedChanges> { const typeAssets = assets[this.type]; // Do nothing if not set Iif (!typeAssets) { return { del: [], create: [], conflicts: [], update: [], }; } const existing = await this.getType(); // Figure out what needs to be updated vs created return calculateChanges({ handler: this, assets: typeAssets, allowDelete: !!this.config('AUTH0_ALLOW_DELETE'), //@ts-ignore TODO: investigate what happens when `existing` is null existing, identifiers: this.identifiers, }); } async validate(assets: Assets): Promise<void> { // Ensure no duplication in id and name const typeAssets = assets[this.type]; // Do nothing if not set if (!Array.isArray(typeAssets)) return; // Do not allow items with same name const duplicateNames = duplicateItems(typeAssets, 'name'); if (duplicateNames.length > 0) { const formatted = duplicateNames.map((dups) => dups.map((d) => `${d.name}`)); throw new ValidationError(`There are multiple ${this.type} with the same name combinations ${convertJsonToString(formatted)}. Names must be unique.`); } // Do not allow items with same id const duplicateIDs = duplicateItems(typeAssets, this.id); if (duplicateIDs.length > 0) { const formatted = duplicateIDs.map((dups) => dups.map((d) => `${d[this.id]}`)); throw new ValidationError(`There are multiple ${ this.type } for the following stage-order combinations ${convertJsonToString(formatted)}. Only one rule must be defined for the same order number in a stage.`); } } async processChanges(assets: Assets, changes: CalculatedChanges): Promise<void> { if (!changes) { changes = await this.calcChanges(assets); } const del = changes.del || []; const update = changes.update || []; const create = changes.create || []; const conflicts = changes.conflicts || []; log.debug( `Start processChanges for ${this.type} [delete:${del.length}] [update:${update.length}], [create:${create.length}], [conflicts:${conflicts.length}]` ); // Process Deleted if (del.length > 0) { const allowDelete = this.config('AUTH0_ALLOW_DELETE') === 'true' || this.config('AUTH0_ALLOW_DELETE') === true; const byExtension = this.config('EXTENSION_SECRET') && (this.type === 'rules' || this.type === 'resourceServers'); const shouldDelete = allowDelete || byExtension; if (!shouldDelete) { log.warn(`Detected the following ${ this.type } should be deleted. Doing so may be destructive.\nYou can enable deletes by setting 'AUTH0_ALLOW_DELETE' to true in the config \n${changes.del.map((i) => this.objString(i)).join('\n')} `); } else { await this.client.pool .addEachTask({ data: del || [], generator: (delItem) => { const delFunction = this.getClientFN(this.functions.delete); return delFunction({ [this.id]: delItem[this.id] }) .then(() => { this.didDelete(delItem); this.deleted += 1; }) .catch((err) => { throw new Error( `Problem deleting ${this.type} ${this.objString(delItem)}\n${err}` ); }); }, }) .promise(); } } // Process Renaming Entries Temp due to conflicts in names await this.client.pool .addEachTask({ data: conflicts || [], generator: (updateItem) => { const updateFN = this.getClientFN(this.functions.update); const params = { [this.id]: updateItem[this.id] }; const updatePayload = (() => { let data = stripFields({ ...updateItem }, this.stripUpdateFields); return stripObfuscatedFieldsFromPayload(data, this.sensitiveFieldsToObfuscate); })(); return updateFN(params, updatePayload) .then((data) => this.didUpdate(data)) .catch((err) => { throw new Error( `Problem updating ${this.type} ${this.objString(updateItem)}\n${err}` ); }); }, }) .promise(); // Process Creations await this.client.pool .addEachTask({ data: create || [], generator: (createItem) => { const createFunction = this.getClientFN(this.functions.create); const createPayload = (() => { const strippedPayload = stripFields(createItem, this.stripCreateFields); return stripObfuscatedFieldsFromPayload( strippedPayload, this.sensitiveFieldsToObfuscate ); })(); return createFunction(createPayload) .then((data) => { this.didCreate(data); this.created += 1; }) .catch((err) => { throw new Error( `Problem creating ${this.type} ${this.objString(createItem)}\n${err}` ); }); }, }) .promise(); // Process Updates and strip fields not allowed in updates await this.client.pool .addEachTask({ data: update || [], generator: (updateItem) => { const updateFN = this.getClientFN(this.functions.update); const params = { [this.id]: updateItem[this.id] }; const updatePayload = (() => { let data = stripFields({ ...updateItem }, this.stripUpdateFields); return stripObfuscatedFieldsFromPayload(data, this.sensitiveFieldsToObfuscate); })(); return updateFN(params, updatePayload) .then((data) => { this.didUpdate(data); this.updated += 1; }) .catch((err) => { throw new Error( `Problem updating ${this.type} ${this.objString(updateItem)}\n${err}` ); }); }, }) .promise(); } } |