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

68.47% Statements 63/92
53.7% Branches 29/54
81.48% Functions 22/27
70.45% Lines 62/88

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 2791x 1x 1x 1x     1x                                                     1x                                                                                                             2x   2x     1x 6x     1x       142x       2x 1x               2x 2x 2x 2x     2x 2x       1x     1x       4x       4x       1x   1x                   1x 1x                                                                                             18x   18x         18x 18x 13x 13x   5x 2x     3x 1x         2x 1x 1x     1x         1x 4x     4x 4x     4x 4x   2x       4x   4x 4x 4x 4x       4x   2x     1x 1x     1x       1x   1x       4x      
import _ from 'lodash';
import DefaultAPIHandler, { order } from './default';
import log from '../../../logger';
import { areArraysEquals } from '../../utils';
import { Asset, Assets, CalculatedChanges } from '../../../types';
 
const MAX_ACTION_DEPLOY_RETRY_ATTEMPTS = 60; // 60 * 2s => 2 min timeout
 
export type Action = {
  id: string;
  name: string;
  created_at: string;
  updated_at: string;
  deployed?: boolean;
  supported_triggers: {
    id: string;
    version: string;
    status?: string;
  }[];
  code?: string;
  dependencies?: [];
  runtime?: string;
  status?: string;
  secrets?: {
    name: string;
    value: string;
  }[];
  all_changes_deployed?: boolean;
  installed_integration_id?: string;
  integration?: Object;
};
 
// With this schema, we can only validate property types but not valid properties on per type basis
export const schema = {
  type: 'array',
  items: {
    type: 'object',
    required: ['name', 'supported_triggers', 'code'],
    additionalProperties: false,
    properties: {
      code: { type: 'string', default: '' },
      runtime: { type: 'string' },
      dependencies: {
        type: 'array',
        items: {
          type: 'object',
          additionalProperties: false,
          properties: {
            name: { type: 'string' },
            version: { type: 'string' },
            registry_url: { type: 'string' },
          },
        },
      },
      secrets: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            name: { type: 'string' },
            value: { type: 'string' },
            updated_at: { type: 'string', format: 'date-time' },
          },
        },
      },
      name: { type: 'string', default: '' },
      supported_triggers: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            id: { type: 'string', default: '' },
            version: { type: 'string' },
            url: { type: 'string' },
          },
        },
      },
      deployed: { type: 'boolean' },
      status: { type: 'string' },
    },
  },
};
 
function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
 
function isActionsDisabled(err) {
  const errorBody = _.get(err, 'originalError.response.body') || {};
 
  return err.statusCode === 403 && errorBody.errorCode === 'feature_not_enabled';
}
 
export function isMarketplaceAction(action: Action): boolean {
  return !!action.integration;
}
 
export default class ActionHandler extends DefaultAPIHandler {
  existing: Action[] | null;
 
  constructor(options: DefaultAPIHandler) {
    super({
      ...options,
      type: 'actions',
      functions: {
        create: (action: Action) => this.createAction(action),
        delete: (action: Action) => this.deleteAction(action),
      },
      stripUpdateFields: ['deployed', 'status'],
    });
  }
 
  async createAction(action: Action) {
    // Strip the deployed flag
    const addAction = { ...action };
    delete addAction.deployed;
    delete addAction.status;
    const createdAction = await this.client.actions.create(addAction);
 
    // Add the action id so we can deploy it later
    action.id = createdAction.id;
    return createdAction;
  }
 
  async deleteAction(action: Action) {
    Iif (!this.client.actions || typeof this.client.actions.delete !== 'function') {
      return [];
    }
    return this.client.actions.delete({ id: action.id, force: true });
  }
 
  objString(action) {
    return super.objString({ id: action.id, name: action.name });
  }
 
  async deployActions(actions) {
    await this.client.pool
      .addEachTask({
        data: actions || [],
        generator: (action) =>
          this.deployAction(action)
            .then(() => {
              log.info(`Deployed [${this.type}]: ${this.objString(action)}`);
            })
            .catch((err) => {
              throw new Error(`Problem Deploying ${this.type} ${this.objString(action)}\n${err}`);
            }),
      })
      .promise();
  }
 
  async deployAction(action) {
    try {
      await this.client.actions.deploy({ id: action.id });
    } catch (err) {
      // Retry if pending build.
      if (err.message && err.message.includes("must be in the 'built' state")) {
        if (!action.retry_count) {
          log.info(`[${this.type}]: Waiting for build to complete ${this.objString(action)}`);
          action.retry_count = 1;
        }
        if (action.retry_count > MAX_ACTION_DEPLOY_RETRY_ATTEMPTS) {
          throw err;
        }
        await sleep(2000);
        action.retry_count += 1;
        await this.deployAction(action);
      } else {
        throw err;
      }
    }
  }
 
  async actionChanges(action, found) {
    const actionChanges: Asset = {};
 
    // if action is deployed, should compare against curren_version - calcDeployedVersionChanges method
    if (!action.deployed) {
      // name or secrets modifications are not supported yet
      if (action.code !== found.code) {
        actionChanges.code = action.code;
      }
 
      if (action.runtime !== found.runtime) {
        actionChanges.runtime = action.runtime;
      }
 
      if (!areArraysEquals(action.dependencies, found.dependencies)) {
        actionChanges.dependencies = action.dependencies;
      }
    }
 
    if (!areArraysEquals(action.supported_triggers, found.supported_triggers)) {
      actionChanges.supported_triggers = action.supported_triggers;
    }
 
    return actionChanges;
  }
 
  async getType(): Promise<Asset[] | null> {
    Iif (this.existing) return this.existing;
 
    Iif (!this.client.actions || typeof this.client.actions.getAll !== 'function') {
      return [];
    }
    // Actions API does not support include_totals param like the other paginate API's.
    // So we set it to false otherwise it will fail with "Additional properties not allowed: include_totals"
    try {
      const actions = await this.client.actions.getAll({ paginate: true });
      this.existing = actions;
      return actions;
    } catch (err) {
      if (err.statusCode === 404 || err.statusCode === 501) {
        return null;
      }
 
      if (err.statusCode === 500 && err.message === 'An internal server error occurred') {
        throw new Error(
          "Cannot process actions because the actions service is currently unavailable. Retrying may result in a successful operation. Alternatively, adding 'actions' to `AUTH0_EXCLUDED` configuration property will provide ability to skip until service is restored to actions service. This is not an issue with the Deploy CLI."
        );
      }
 
      if (isActionsDisabled(err)) {
        log.info('Skipping actions because it is not enabled.');
        return null;
      }
 
      throw err;
    }
  }
 
  @order('60')
  async processChanges(assets: Assets) {
    const { actions } = assets;
 
    // Do nothing if not set
    Iif (!actions) return;
    const changes = await this.calcChanges(assets);
 
    //Management of marketplace actions not currently supported, see ESD-23225.
    const changesWithMarketplaceActionsFiltered: CalculatedChanges = (() => {
      return {
        ...changes,
        del: changes.del.filter((action: Action) => !isMarketplaceAction(action)),
      };
    })();
 
    await super.processChanges(assets, changesWithMarketplaceActionsFiltered);
 
    const postProcessedActions = await (async () => {
      this.existing = null; //Clear the cache
      const actions = await this.getType();
      return actions;
    })();
 
    // Deploy actions
    const deployActions = [
      ...changes.create
        .filter((action) => action.deployed)
        .map((actionWithoutId) => {
          // Add IDs to just-created actions
          const actionId = postProcessedActions?.find((postProcessedAction) => {
            return postProcessedAction.name === actionWithoutId.name;
          })?.id;
 
          const actionWithId = {
            ...actionWithoutId,
            id: actionId,
          };
          return actionWithId;
        })
        .filter((action) => !!action.id),
      ...changes.update.filter((action) => action.deployed),
    ];
 
    await this.deployActions(deployActions);
  }
}