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

const enumPatcher = (SchemaString) => {
  patcher.patch(SchemaString.prototype, 'enum', {
    alwaysRun: true,
    name: 'mongoose.string.enum',
    patchType: ASSESS_PROPAGATOR,
    post(data) {
      if (!data.result) return;

      const enumValidator = data.result.validators.find(
        (validator) => validator.type === 'enum'
      );

      if (!enumValidator) return;

      patcher.patch(enumValidator, 'validator', {
        alwaysRun: true,
        name: 'mongoose.string.enumValidator',
        patchType: ASSESS_PROPAGATOR,
        post(data) {
          if (!data.result) return;

          tracker.untrack(data.args[0]);
        }
      });
    }
  });
};

const doValidateSyncPatcher = (SchemaString) => {
  patcher.patch(SchemaString.prototype, 'doValidateSync', {
    alwaysRun: true,
    name: 'mongoose.string.doValidateSync',
    patchType: ASSESS_PROPAGATOR,
    post(data) {
      if (data.result) return;

      if (!hasUserDefinedValidator(data)) return;

      const trackingData = tracker.track(data.args[0]);
      if (!trackingData) return;

      const { props } = trackingData;
      const incomingStringLength = data.args[0].length - 1;

      props.tagRanges = tagRangeUtil.add(
        props.tagRanges,
        new TagRange(
          0,
          incomingStringLength,
          'custom-validated-nosql-injection'
        )
      );

      props.tagRanges = tagRangeUtil.add(
        props.tagRanges,
        new TagRange(0, incomingStringLength, 'string-type-checked')
      );

      props.event = new PropagationEvent({
        context: CallContext.create(data),
        signature: new Signature('mongoose.string.doValidateSync'),
        tagRanges: props.tagRanges,
        source: 'P',
        target: 'A',
        parents: [props.event]
      });
    }
  });
};

requireHook.resolve(
  { name: 'mongoose', file: 'lib/schema/string.js', version: '>=5.0.0' },
  (SchemaString) => {
    if (
      !agent.config ||
      (agent.config && !agent.config.assess.trust_custom_validators)
    ) {
      return;
    }

    enumPatcher(SchemaString);
    doValidateSyncPatcher(SchemaString);
  }
);
