/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
'use strict';

const logger = require('../../../core/logger')('contrast:sequelize:propagator');
const tracker = require('../../../tracker');
const patcher = require('../../../hooks/patcher');
const { PATCH_TYPES } = require('../../../constants');
const moduleHook = require('../../../hooks/require');
const { CallContext, PropagationEvent, Signature } = require('../../models');
const TagRange = require('../../models/tag-range');
const tagRangeUtil = require('../../models/tag-range/util');
const { getSequelizeString } = require('./utils');

function getPositions(str) {
  const positions = [];
  for (let i = 0, len = str.length; i < len; i++) {
    if (str[i] === '?') positions.push(i);
  }
  return positions;
}

module.exports.handle = function() {
  moduleHook.resolve(
    { name: 'sequelize', file: 'lib/sql-string.js' },
    (sqlstring) => {
      logger.debug('hooking sql-string.js');

      patcher.patch(sqlstring, 'format', {
        name: 'sequelize/lib/sql-string',
        patchType: PATCH_TYPES.ASSESS_PROPAGATOR,
        post(data) {
          // else either the replacement value or a values in the array replacement is being tracked
          const trackingData = tracker.getData(data.result);
          if (!trackingData) {
            return;
          }

          const positions = getPositions(data.args[0]);
          if (!positions.length) {
            return;
          }

          const replacements = [].concat(data.args[1]);
          const timezone = data.args[2];
          const dialect = data.args[3];
          const len = positions.length; // micro optomized since used multiple times

          for (let i = 0; i < len; i++) {
            const props = tracker.getData(replacements[i]);
            // we don't need to run in a no instrumentation scope here since
            // patcher will do so automatically since we're in a post hook
            const escapedVal = getSequelizeString().escape(
              replacements[i],
              timezone,
              dialect,
              true // true is required to get format function behavior.
            );

            if (props && props.tracked) {
              tagRangeUtil.addInPlace(
                trackingData.tagRanges,
                new TagRange(
                  positions[i],
                  positions[i] + escapedVal.length - 1,
                  'sql-encoded'
                )
              );
            }
            //update the string replacement poisitions based on current val length - it's replacing a ? in the origional string
            if (i < len - 1) {
              for (let j = i + 1; j < len; j++) {
                positions[j] = positions[j] + escapedVal.length - 1;
              }
            }
          }

          const event = new PropagationEvent({
            context: CallContext.create(data),
            parents: [trackingData.event],
            signature: new Signature('sequelize/lib/sql-string.format'),
            source: 'P',
            tagRanges: trackingData.tagRanges,
            target: 'R'
          });

          trackingData.event = event;
        }
      });
    }
  );
};
