/**
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 _ = require('lodash');
const requireHook = require('../../../hooks/require');
const patcher = require('../../../hooks/patcher');
const {
  PATCH_TYPES: { ASSESS_PROPAGATOR },
} = require('../../../constants');
const tracker = require('../../../tracker');
const { PropagationEvent, Signature, CallContext } = require('../../models');
const TagRange = require('../../models/tag-range');
const tagRangeUtil = require('../../models/tag-range/util');
const agent = require('../../../agent');
const { setProxyTaggedString, getContrastData } = require('../utils');

const areThereRules = (obj) =>
  obj &&
  obj.schema &&
  Array.isArray(obj.schema._rules) &&
  obj.schema._rules.length > 0;

/**
 * Patch joi.string.validate so that it tags input with string-type-checked if validated
 * @param {Object} string
 */
function instrumentJoiString(string) {
  const def = _.get(Object.getPrototypeOf(string), '_definition');
  def &&
    patcher.patch(def, 'validate', {
      name: 'joi.string.validate',
      patchType: ASSESS_PROPAGATOR,
      post(data) {
        const input = data.args[0];
        const contrastData = getContrastData(data);
        const doesSchemaHaveReferences = !!contrastData;

        let trackingData = tracker.getData(input);

        if (!trackingData && !data.result && doesSchemaHaveReferences) {
          const proxyTaggedString = setProxyTaggedString(
            contrastData,
            input,
            tracker
          );

          trackingData = tracker.getData(proxyTaggedString);

          Object.values(contrastData.refInstances).forEach(
            (referenceInstance) => {
              Object.defineProperty(referenceInstance, '__CONTRAST__', {
                enumerable: false,
                configurable: true,
                value: {
                  proxyTaggedString,
                },
                writable: true,
              });
            }
          );
        }

        if (
          areThereRules(data.args[1]) &&
          data.args[1].schema._rules.find((rule) => rule.name === 'pattern') &&
          !agent.config.assess.trust_custom_validators
        )
          return;

        if (!data.result && trackingData) {
          const { event } = trackingData;
          trackingData.tagRanges = tagRangeUtil.add(
            trackingData.tagRanges,
            new TagRange(0, input.length - 1, 'string-type-checked')
          );
          trackingData.event = new PropagationEvent({
            context: CallContext.create(data),
            signature: new Signature('joi.string.validate'),
            tagRanges: trackingData.tagRanges,
            source: 'P',
            target: 'A',
            parents: [event],
          });
        }
      },
    });

  patcher.patch(string.__proto__, 'validateAsync', {
    name: 'joi.string.validateAsync',
    patchType: ASSESS_PROPAGATOR,
    alwaysRun: true,
    post(data) {
      if (
        !data.obj.$_terms.externals.length ||
        !agent.config.assess.trust_custom_validators
      )
        return;

      data.result.then((result) => {
        tracker.untrack(data.args[0]);
        tracker.untrack(result);
      });
    },
  });
}

requireHook.resolve(
  { name: 'joi', file: 'lib/types/string.js', version: '>=17.0.0' },
  instrumentJoiString
);
