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

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

  get enabled() {
    return get(this.rules, `${this.ruleId}.enabled`);
  }

  /**
   * Patches `Response.prototype.redirect` for
   * `unvalidated-redirect` checking
   *
   */
  registerUnvalidatedRedirectHandler() {
    const { isVulnerable, requiredTags, report } = this.common;
    const { disallowedTags, ruleId, methodName, moduleName, signature } = this;
    if (!this.enabled) {
      return;
    }

    agentEmitter.on(EVENTS.RESPONSE, (Response) => {
      patcher.patch(Response.prototype, methodName, {
        name: moduleName,
        patchType: PATCH_TYPES.ASSESS_SINK,
        alwaysRun: true,
        post({ args, obj }) {
          let input;
          const [arg1, arg2] = args;
          if (typeof arg1 === 'string' || typeof arg1 === 'object') {
            input = arg1;
          } else if (typeof arg1 === 'number') {
            input = arg2;
          }

          const vulnerable = isVulnerable({
            searchDepth: 2, // when object, query params are nested, this will check those leaf nodes
            input,
            disallowedTags,
            requiredTags,
            ruleId
          });

          if (vulnerable) {
            report({
              signature,
              input: vulnerable,
              ctxt: CallContext.create({
                obj,
                args: [input],
                stackOpts: {
                  constructorOpt: agentEmitter.emit
                }
              }),
              ruleId
            });
          }
        }
      });
    });
  }
}

module.exports = RestifyRedirectSink;
