/**
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 moduleHook = require('../../hooks/require');
const { CallContext, Signature } = require('../models');
const {
  RULES: { NOSQL_INJECTION }
} = require('../../constants');

const filterSignature = new Signature({
  moduleName: 'rethinkdb.RDBVal',
  methodName: 'filter',
  isModule: true
});
const matchSignature = new Signature({
  moduleName: 'rethinkdb.RDBVal',
  methodName: 'match',
  isModule: true
});
const moduleName = 'rethinkdb';

class Handler {
  constructor({ report, isVulnerable, requiredTags }) {
    this._isVulnerable = isVulnerable;
    this.report = report;
    this.requiredTags = requiredTags;
    this.disallowedTags = [
      'alphanum-space-hyphen',
      'limited-chars',
      'custom-validated',
      'custom-encoded-nosql-injection',
      'custom-validated-nosql-injection'
    ];
  }

  isVulnerable(input) {
    const { requiredTags, disallowedTags } = this;
    return this._isVulnerable({
      input,
      ruleId: NOSQL_INJECTION,
      disallowedTags,
      requiredTags,
      searchDepth: 5
    });
  }

  handle() {
    moduleHook.resolve({ name: moduleName }, (rethinkdb) =>
      this.handleRequire(rethinkdb)
    );
  }

  patchRethinkDb(rethinkdb) {
    const self = this;
    patcher.patch(rethinkdb, 'db', {
      name: moduleName,
      patchType: PATCH_TYPES.ASSESS_SINK,
      alwaysRun: true,
      post(data) {
        self.patchTableMethod(data.result);
      }
    });
  }

  /**
   * Patch the table method and through it gain access to the object
   * prototype that holds the vulnerable `match` and `filter` methods
   */
  patchTableMethod(tableObject) {
    const RDBValObject = Object.getPrototypeOf(tableObject.args[0]);
    const TermBaseObject = Object.getPrototypeOf(RDBValObject);
    const self = this;

    patcher.patch(TermBaseObject, 'match', {
      name: 'TermBase.prototype',
      patchType: PATCH_TYPES.ASSESS_SINK,
      alwaysRun: true,
      post({ args: [str], hooked, obj }) {
        if (self.isVulnerable(str)) {
          self.report({
            ruleId: NOSQL_INJECTION,
            signature: matchSignature,
            input: str,
            ctxt: CallContext.create({
              obj,
              args: [str],
              result: str,
              stackOpts: {
                constructorOpt: hooked
              }
            })
          });
        }
      }
    });
    patcher.patch(TermBaseObject, 'filter', {
      name: 'TermBase.prototype',
      patchType: PATCH_TYPES.ASSESS_SINK,
      alwaysRun: true,
      post({ args: [str], hooked, obj }) {
        if (self.isVulnerable(str)) {
          self.report({
            ruleId: NOSQL_INJECTION,
            signature: filterSignature,
            input: str,
            ctxt: CallContext.create({
              obj,
              args: [str],
              result: str,
              stackOpts: {
                constructorOpt: hooked
              }
            })
          });
        }
      }
    });
  }

  handleRequire(rethinkdb) {
    this.patchRethinkDb(rethinkdb);
    return rethinkdb;
  }
}

module.exports = ({ common }) => new Handler(common);
module.exports.Handler = Handler;
