All files / src/tools/auth0/handlers rules.ts

92.53% Statements 62/67
96% Branches 24/25
85% Functions 17/20
92.98% Lines 53/57

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 2151x 1x 1x 1x 1x     1x         1x                                                                             1x       143x               26x 20x 20x       6x             15x   15x   15x     15x 9x 10x       15x               15x   15x 15x 15x     15x 15x 15x 2x 2x               13x     15x                   74x     74x   7x     7x     7x             7x 7x 2x 1x           6x 6x   6x     1x         1x   6x 1x         5x       6x     6x     6x     6x                                   6x                
import ValidationError from '../../validationError';
import { convertJsonToString, stripFields, duplicateItems } from '../../utils';
import DefaultHandler from './default';
import log from '../../../logger';
import { calculateChanges } from '../../calculateChanges';
import { Asset, Assets, CalculatedChanges } from '../../../types';
 
export const excludeSchema = {
  type: 'array',
  items: { type: 'string' },
};
 
export const schema = {
  type: 'array',
  items: {
    type: 'object',
    default: [],
    properties: {
      script: {
        type: 'string',
        description: "A script that contains the rule's code",
        default: '',
      },
      name: {
        type: 'string',
        description:
          "The name of the rule. Can only contain alphanumeric characters, spaces and '-'. Can neither start nor end with '-' or spaces",
        pattern: '^[^-\\s][a-zA-Z0-9-\\s]+[^-\\s]$',
      },
      order: {
        type: ['number', 'null'],
        description:
          "The rule's order in relation to other rules. A rule with a lower order than another rule executes first.",
        default: null,
      },
      enabled: {
        type: 'boolean',
        description: 'true if the rule is enabled, false otherwise',
        default: true,
      },
      stage: {
        type: 'string',
        description: "The rule's execution stage",
        default: 'login_success',
        enum: ['login_success', 'login_failure', 'pre_authorize'],
      },
    },
    required: ['name'],
  },
};
 
export default class RulesHandler extends DefaultHandler {
  existing: Asset[];
 
  constructor(options: DefaultHandler) {
    super({
      ...options,
      type: 'rules',
      stripUpdateFields: ['stage'], // Fields not allowed in updates
    });
  }
 
  async getType(): Promise<Asset[]> {
    if (this.existing) return this.existing;
    this.existing = await this.client.rules.getAll({ paginate: true, include_totals: true });
    return this.existing;
  }
 
  objString(rule): string {
    return super.objString({ name: rule.name, order: rule.order });
  }
 
  async calcChanges(
    assets,
    includeExcluded = false
  ): Promise<CalculatedChanges & { reOrder: Asset[] }> {
    let { rules } = assets;
 
    const excludedRules = (assets.exclude && assets.exclude.rules) || [];
 
    let existing = await this.getType();
 
    // Filter excluded rules
    if (!includeExcluded) {
      rules = rules.filter((r) => !excludedRules.includes(r.name));
      existing = existing.filter((r) => !excludedRules.includes(r.name));
    }
 
    // Figure out what needs to be updated vs created
    const { del, update, create, conflicts } = calculateChanges({
      handler: this,
      assets: rules,
      existing,
      identifiers: this.identifiers,
      allowDelete: !!this.config('AUTH0_ALLOW_DELETE'),
    });
    // Figure out the rules that need to be re-ordered
    const futureRules = [...create, ...update];
 
    const futureMaxOrder = Math.max(...futureRules.map((r) => r.order));
    const existingMaxOrder = Math.max(...existing.map((r) => r.order));
    let nextOrderNo = Math.max(futureMaxOrder, existingMaxOrder);
 
    //@ts-ignore because we know reOrder is Asset[]
    const reOrder: Asset[] = futureRules.reduce((accum: Asset[], r: Asset) => {
      const conflict = existing.find((f) => r.order === f.order && r.name !== f.name);
      if (conflict !== undefined) {
        nextOrderNo += 1;
        return [
          ...accum,
          {
            ...conflict,
            order: nextOrderNo,
          },
        ];
      }
      return accum;
    }, []);
 
    return {
      del,
      update,
      create,
      reOrder,
      conflicts,
    };
  }
 
  async validate(assets: Assets): Promise<void> {
    const { rules } = assets;
 
    // Do nothing if not set
    if (!rules) return;
 
    const excludedRules = (assets.exclude && assets.exclude.rules) || [];
 
    // Figure out what needs to be updated vs created
    const { update, create, del } = await this.calcChanges(assets, true);
    // Include del rules which are actually not going to be deleted but are excluded
    // they can still muck up the ordering so we must take it into consideration.
    const futureRules = [
      ...create,
      ...update,
      ...del.filter((r) => excludedRules.includes(r.name)),
    ];
 
    // Detect rules with the same order
    const rulesSameOrder = duplicateItems(futureRules, 'order');
    if (rulesSameOrder.length > 0) {
      const formatted = rulesSameOrder.map((dups) => dups.map((d) => `${d.name}`));
      throw new ValidationError(`There are multiple rules for the following stage-order combinations
      ${convertJsonToString(formatted)}.
       Only one rule must be defined for the same order number in a stage.`);
    }
 
    // Detect Rules that are changing stage as it's not allowed.
    const existing = await this.getType();
    const stateChanged = futureRules
      .reduce(
        (changed: Asset[], rule) => [
          ...changed,
          ...existing.filter(
            (r) => rule.name.toLowerCase() === r.name.toLowerCase() && r.stage !== rule.stage
          ),
        ],
        []
      )
      .map((r) => r.name);
 
    if (stateChanged.length > 0) {
      throw new ValidationError(`The following rules changed stage which is not allowed:
      ${convertJsonToString(stateChanged)}.
      Rename the rules to recreate them and avoid this error.`);
    }
 
    await super.validate(assets);
  }
 
  async processChanges(assets: Assets): Promise<void> {
    const { rules } = assets;
 
    // Do nothing if not set
    Iif (!rules) return;
 
    // Figure out what needs to be updated vs created
    const changes = await this.calcChanges(assets);
 
    // Temporally re-order rules with conflicting ordering
    await this.client.pool
      .addEachTask({
        data: changes.reOrder,
        generator: (rule) =>
          this.client.rules
            .update({ id: rule.id }, stripFields(rule, this.stripUpdateFields))
            .then(() => {
              const updated = {
                name: rule.name,
                stage: rule.stage,
                order: rule.order,
                id: rule.id,
              };
              log.info(`Temporally re-order Rule ${convertJsonToString(updated)}`);
            }),
      })
      .promise();
 
    await super.processChanges(assets, {
      del: changes.del,
      create: changes.create,
      update: changes.update,
      conflicts: changes.conflicts,
    });
  }
}