/**
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 { PropagationEvent, Signature, CallContext } = require('../../models');
const TagRange = require('../../models/tag-range');
const tagRangeUtil = require('../../models/tag-range/util');
const tracker = require('../../../tracker');
const { setProxyTaggedString, getContrastData } = require('../utils');

const VALIDATORS = {
  base64: 'alphanum-space-hyphen',
  guid: 'alphanum-space-hyphen',
  alphanum: 'alphanum-space-hyphen',
  hex: 'alphanum-space-hyphen',
  isoDate: 'alphanum-space-hyphen',
  isoDuration: 'alphanum-space-hyphen',
  token: 'alphanum-space-hyphen',
  creditCard: 'limited-chars',
  ip: 'limited-chars',
  hostname: 'alphanum-space-hyphen',
  domain: 'alphanum-space-hyphen',
};

requireHook.resolve(
  { name: 'joi', file: 'lib/types/string.js', version: '>=17.0.0' },
  (stringType, meta) => {
    const rules = _.get(Object.getPrototypeOf(stringType), '_definition.rules');

    if (!rules || rules.length === 0) {
      return;
    }

    for (const rule in VALIDATORS) {
      if (rules[rule]) {
        wrapRuleAsValidator(rules[rule], rule, VALIDATORS[rule]);
      }
    }

    const coerce = _.get(
      Object.getPrototypeOf(stringType),
      '_definition.coerce'
    );

    if (coerce && rules['isoDate']) {
      reTrackCoercedValue(coerce, 'isoDate');
    }
  }
);

function reTrackCoercedValue(coerce, rule) {
  patcher.patch(coerce, {
    name: 'joi.string._definition.coerce',
    patchType: ASSESS_PROPAGATOR,
    alwaysRun: true,
    post(data) {
      const { args, result } = data;

      // currently, we are losing track of coerced isoDate only
      if (!args[1].schema.$_getRule('isoDate')) {
        return;
      }

      const argContrastProperties = tracker.getData(args[0]);
      if (!argContrastProperties) {
        return;
      }

      const tracked = tracker.track(result.value);

      if (tracked) {
        tracked.props.tagRanges = tagRangeUtil.add(
          tracked.props.tagRanges,
          new TagRange(0, tracked.str.length - 1, 'untrusted')
        );

        tracked.props.event = createPropagationEvent({
          data,
          trackedArgsData: argContrastProperties,
          tagRanges: tracked.props.tagRanges,
          target: 'R',
          joiMethod: rule,
        });

        data.result = { value: tracked.str };
      }
    },
  });
}

function wrapRuleAsValidator(rules, rule, tagName) {
  patcher.patch(rules, 'validate', {
    name: 'joi.string._definition.rules',
    patchType: ASSESS_PROPAGATOR,
    alwaysRun: true,
    post(data) {
      const { args, result } = data;

      // if the validation failed, result is an object
      if (typeof result !== 'string') {
        return;
      }

      const argContrastProperties = tracker.getData(args[0]);

      const contrastData = getContrastData(data);
      const doesSchemaHaveReferences = !!contrastData;

      if (!argContrastProperties && !doesSchemaHaveReferences) {
        return;
      }

      let trackingData = tracker.getData(result);

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

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

      if (trackingData) {
        trackingData.tagRanges = tagRangeUtil.add(
          trackingData.tagRanges,
          new TagRange(0, result.length - 1, tagName)
        );

        trackingData.event = createPropagationEvent({
          data,
          trackedArgsData: trackingData,
          tagRanges: trackingData.tagRanges,
          target: 'A',
          joiMethod: rule,
        });
      }
    },
  });
}

function createPropagationEvent({
  data,
  trackedArgsData,
  tagRanges,
  target,
  joiMethod,
}) {
  const { event: lastEvent } = trackedArgsData;

  const context = CallContext.create(data);
  const signature = new Signature(`joi.string.${joiMethod}`);

  const event = new PropagationEvent({
    context,
    signature,
    tagRanges,
    source: 'P',
    target,
  });

  event.parents.push(lastEvent);

  return event;
}

module.exports.wrapRuleAsValidator = wrapRuleAsValidator;
module.exports.reTrackCoercedValue = reTrackCoercedValue;
