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

module.exports.handle = function handle() {
  requireHook.resolve(
    { name: 'fastify-plugin', file: 'plugin' },
    (fastifyPlugin) => (patcher.patch(fastifyPlugin, {
      name: 'fastify-plugin',
      patchType: PATCH_TYPES.ASSESS_PROPAGATOR,
      alwaysRun: true,
      pre: ({ args }) => {
        if ((typeof args[0] == 'function') && args[1] && (args[1].name === 'fastify-static')) {
          const fastifyStatic = args[0];

          args[0] = patcher.patch(fastifyStatic, {
            name: 'fastify-static',
            patchType: PATCH_TYPES.ASSESS_PROPAGATOR,
            alwaysRun: true,
            pre: ({ args: preArgs }) => {
              if (preArgs[1] && preArgs[1].allowedPath) {
                const { allowedPath } = preArgs[1];

                preArgs[1].allowedPath = patcher.patch(allowedPath, {
                  name: 'allowed-path',
                  patchType: PATCH_TYPES.ASSESS_PROPAGATOR,
                  alwaysRun: true,
                  post: (data) => {
                    if (data.result && agent.config.assess.trust_custom_validators) {
                      const trackingData = tracker.getData(data.args[0]);

                      if (trackingData) {
                        logger.trace('hooking fastify-static/index');
                        tagRangeUtil.addInPlace(
                          trackingData.tagRanges,
                          new TagRange(0, data.args[0].length - 1, 'safe-path')
                        );
                        tagRangeUtil.removeInPlace(trackingData.tagRanges, ['untrusted']);

                        const context = CallContext.create(data);
                        const event = new PropagationEvent({
                          context,
                          signature: new Signature('fastify-static.allowedPath'),
                          tagRanges: trackingData.tagRanges,
                          source: 'O',
                          target: 'R'
                        });

                        event.parents.push(trackingData.event);
                        trackingData.event = event;
                      }
                    }
                  }
                });
              }
            }
          });
        }
      },
    }))

  );
};
