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

class KoaRedirectSink {
  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: 'ctx',
      methodName,
      isModule: true
    });

    this.instrumentResponse();
  }

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

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

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

    logger.info('loading ctx.redirect hooks');
    patcher.patch(Response, methodName, {
      name: 'koa.Response.prototype',
      patchType: PATCH_TYPES.ASSESS_SINK,
      alwaysRun: true,
      post(data) {
        if (!self.enabled) {
          return;
        }
        const [url] = data.args;
        if (isVulnerable({ input: url, disallowedTags, requiredTags })) {
          const ctxt = CallContext.create({
            obj: data.obj,
            args: [url],
            result: url,
            stackOpts: {
              constructorOpt: data.hooked
            }
          });
          report({ ruleId, signature, input: url, ctxt });
        }
      }
    });
  }
}

module.exports = KoaRedirectSink;
