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

92.85% Statements 52/56
85.18% Branches 23/27
100% Functions 12/12
97.87% Lines 46/47

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 1721x 1x 1x 1x       1x                                       1x                 15x     8x 8x   3x 3x   5x     3x 9x 9x   12x   7x   7x 7x             9x                 3x           1x       143x               13x       10x 10x                   6x         16x 16x         16x 16x 16x       10x     10x                 10x 10x       10x         10x   10x           10x         1x 10x     10x   10x   10x   10x      
import dotProp from 'dot-prop';
import _ from 'lodash';
import DefaultAPIHandler, { order } from './default';
import { filterExcluded, convertClientNameToId, getEnabledClients } from '../../utils';
import { CalculatedChanges, Asset, Assets } from '../../../types';
import { ConfigFunction } from '../../../configFactory';
 
export const schema = {
  type: 'array',
  items: {
    type: 'object',
    properties: {
      name: { type: 'string' },
      strategy: { type: 'string' },
      options: { type: 'object' },
      enabled_clients: { type: 'array', items: { type: 'string' } },
      realms: { type: 'array', items: { type: 'string' } },
      metadata: { type: 'object' },
    },
    required: ['name', 'strategy'],
  },
};
 
// addExcludedConnectionPropertiesToChanges superimposes excluded properties on the `options` object. The Auth0 API
// will overwrite the options property when updating connections, so it is necessary to add excluded properties back in to prevent those excluded properties from being deleted.
// This use case is common because organizations may not want to expose sensitive connection details, but want to preserve them in the tenant.
// exported only for unit testing purposes
export const addExcludedConnectionPropertiesToChanges = ({
  proposedChanges,
  existingConnections,
  config,
}: {
  proposedChanges: CalculatedChanges;
  existingConnections: Asset[];
  config: ConfigFunction;
}) => {
  if (proposedChanges.update.length === 0) return proposedChanges;
 
  //@ts-ignore because this expects a parameter to be passed
  const excludedFields = config()?.EXCLUDED_PROPS?.connections || [];
  if (excludedFields.length === 0) return proposedChanges;
 
  const existingConnectionsMap = _.keyBy(existingConnections, 'id');
  const excludedOptions = excludedFields.filter(
    // Only include fields that pertain to options
    (excludedField) => excludedField.startsWith('options')
  );
 
  const newProposedUpdates = proposedChanges.update.map((proposedConnection) => {
    const currConnection = existingConnectionsMap[proposedConnection.id];
    const currentExcludedPropertyValues = excludedOptions.reduce(
      (agg, excludedField) => {
        if (!dotProp.has(currConnection, excludedField)) return agg;
 
        const currentExcludedFieldValue = dotProp.get(currConnection, excludedField);
 
        dotProp.set(agg, excludedField, currentExcludedFieldValue);
        return agg;
      },
      {
        options: {},
      }
    );
 
    return {
      ...proposedConnection,
      options: {
        ...proposedConnection.options,
        ...currentExcludedPropertyValues.options,
      },
    };
  });
 
  return {
    ...proposedChanges,
    update: newProposedUpdates,
  };
};
 
export default class ConnectionsHandler extends DefaultAPIHandler {
  existing: Asset[] | null;
 
  constructor(config: DefaultAPIHandler) {
    super({
      ...config,
      type: 'connections',
      stripUpdateFields: ['strategy', 'name'],
    });
  }
 
  objString(connection): string {
    return super.objString({ name: connection.name, id: connection.id });
  }
 
  getFormattedOptions(connection, clients) {
    try {
      return {
        options: {
          ...connection.options,
          idpinitiated: {
            ...connection.options.idpinitiated,
            client_id: convertClientNameToId(connection.options.idpinitiated.client_id, clients),
          },
        },
      };
    } catch (e) {
      return {};
    }
  }
 
  async getType(): Promise<Asset[] | null> {
    Iif (this.existing) return this.existing;
    const connections: Asset[] = await this.client.connections.getAll({
      paginate: true,
      include_totals: true,
    });
    // Filter out database connections
    this.existing = connections.filter((c) => c.strategy !== 'auth0');
    Iif (this.existing === null) return [];
    return this.existing;
  }
 
  async calcChanges(assets: Assets): Promise<CalculatedChanges> {
    const { connections } = assets;
 
    // Do nothing if not set
    Iif (!connections)
      return {
        del: [],
        create: [],
        update: [],
        conflicts: [],
      };
 
    // Convert enabled_clients by name to the id
    const clients = await this.client.clients.getAll({ paginate: true, include_totals: true });
    const existingConnections = await this.client.connections.getAll({
      paginate: true,
      include_totals: true,
    });
    const formatted = connections.map((connection) => ({
      ...connection,
      ...this.getFormattedOptions(connection, clients),
      enabled_clients: getEnabledClients(assets, connection, existingConnections, clients),
    }));
    const proposedChanges = await super.calcChanges({ ...assets, connections: formatted });
 
    const proposedChangesWithExcludedProperties = addExcludedConnectionPropertiesToChanges({
      proposedChanges,
      existingConnections,
      config: this.config,
    });
 
    return proposedChangesWithExcludedProperties;
  }
 
  // Run after clients are updated so we can convert all the enabled_clients names to id's
  @order('60')
  async processChanges(assets: Assets): Promise<void> {
    const { connections } = assets;
 
    // Do nothing if not set
    Iif (!connections) return;
 
    const excludedConnections = (assets.exclude && assets.exclude.connections) || [];
 
    const changes = await this.calcChanges(assets);
 
    await super.processChanges(assets, filterExcluded(changes, excludedConnections));
  }
}