/**
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 {
  prototype: { decorateRequest }
} = require('../../hooks/frameworks/base');
const {
  INPUT_TYPES: { URL_PARAMETER }
} = require('../../constants');
const { emitSourceEvent } = require('../../hooks/frameworks/common');
const agentEmitter = require('../../agent-emitter');
const patcher = require('../../hooks/patcher');
const { PATCH_TYPES } = require('../../constants');
const {
  utils,
  constants: { EVENTS }
} = require('../../core/restify');
const { get } = require('lodash');

const id = 'restify';

class RestifyProtectSources {
  /**
   * @param {Boolean} [instrument=true] used for testing only
   */
  constructor(instrument = true) {
    if (instrument) {
      agentEmitter.on(
        EVENTS.CREATE_SERVER,
        this.registerUrlParamsHandler.bind(this)
      );
      agentEmitter.on(
        EVENTS.RESTIFY_EXPORT,
        this.registerQueryParamsHandler.bind(this)
      );
    }
  }

  /**
   * Patches query parser middleware to wrap the callback argument. Once this
   * wrapped callback is invoked w/out error we know we can proxy `req.query`.
   * @param {object} restify
   */
  registerQueryParamsHandler(restify) {
    const {
      plugins: { queryParser: origQueryParser }
    } = restify;

    if (origQueryParser) {
      patcher.patch(restify.plugins, 'queryParser', {
        name: 'restify.plugins',
        patchType: PATCH_TYPES.FRAMEWORK,
        alwaysRun: true,
        post(data) {
          patcher.patch(data, 'result', {
            name: 'restify.plugins.queryParser',
            patchType: PATCH_TYPES.PROTECT_SOURCE,
            alwaysRun: true,
            post(data) {
              decorateRequest({ query: get(data.args[0], 'query') });
            }
          });
        }
      });
    }
  }

  /**
   * Registers a middleware after `server.use` that emits the `protect.params`
   * using an event built from SourcesEvent
   *
   * For all input events /except/ for url params, we just use speedracer.
   * However, due to differences in how url params are handled, we need to handle
   * this specific case.
   * @param {restify.Server} server
   */
  registerUrlParamsHandler(server) {
    utils.registerSafeHandler(server, 'use', function(req, res, next) {
      if (Object.keys(req.params).length) {
        decorateRequest({ normalizedUri: get(req, 'route.path') });
        // restify decorates the IncomingMessage directly
        emitSourceEvent(req, req, res, 'params', URL_PARAMETER, id);
      }
    });
  }
}

module.exports = RestifyProtectSources;
