/**
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 moduleHook = require('../../../hooks/require');
const patcher = require('../../../hooks/patcher');
const { PATCH_TYPES } = require('../../../constants');
const logger = require('../../../core/logger')('hooks:restify');
const { Signature, CallContext } = require('../../models');
const policy = require('../../policy');
const { get } = require('lodash');

class FastifyRedirectSink {
  constructor(agent) {
    this.common = require('../../sinks/common')(agent);
    this.rules = get(policy, 'rules');
    this.ruleId = 'unvalidated-redirect';
    this.disallowedTags = ['url-encoded'];
    const methodName = 'redirect';
    this.methodName = methodName;
    this.signature = new Signature({
      moduleName: 'redirect',
      methodName,
      isModule: true
    });

    this.instrumentReply();
  }

  /**
   * checks if an assess rule is enabled in policy
   */
  get enabled() {
    return get(this.rules, `${this.ruleId}.enabled`);
  }

  /**
   * Adds a hook for when fastify/lib/reply is required
   */
  instrumentReply() {
    moduleHook.resolve(
      { name: 'fastify', file: 'lib/reply' },
      this.registerUnvalidatedRedirectHandler.bind(this)
    );
  }

  /**
   * Patches `Reply.prototype.redirect` for
   * `unvalidated-redirect` checking
   *
   * @param {Fastify.Reply} Reply outgoing response
   */
  registerUnvalidatedRedirectHandler(Reply) {
    const { isVulnerable, requiredTags, report } = this.common;
    const { ruleId, disallowedTags, methodName, signature } = this;
    const self = this;

    logger.info('loading fastify reply hooks');
    patcher.patch(Reply.prototype, methodName, {
      name: 'fastify.Reply',
      patchType: PATCH_TYPES.ASSESS_SINK,
      alwaysRun: true,
      post(data) {
        if (!self.enabled) {
          return;
        }
        const [code] = data.args;
        // url can be first or second argument
        const url = typeof code === 'string' ? code : data.args[1];

        if (isVulnerable({ input: url, disallowedTags, requiredTags })) {
          const ctxt = CallContext.create({
            obj: Reply,
            args: [url],
            result: url
          });
          report({ ruleId, signature, input: url, ctxt });
        }
      }
    });
  }
}

module.exports = FastifyRedirectSink;
