/**
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 _ = require('lodash');
const semver = require('semver');
const patcher = require('../../hooks/patcher');
const BaseSensor = require('../../hooks/frameworks/base');
const { PATCH_TYPES, SINK_TYPES } = require('../../constants');
const { emitSinkEvent } = require('../../hooks/frameworks/common');

const ID = 'mongodb';

function getCursorQueryData(args, version) {
  const query = semver.gte(version, '3.3.0')
    ? _.get(args, '0.cmd.query')
    : _.get(args, '1.query');

  if (!query) {
    return;
  }

  if (_.isString(query)) {
    return query.toString();
  }

  if (query['$where']) {
    return query['$where'].toString();
  }

  return query;
}

function getOpQueryData(op) {
  if (!op.q) {
    return;
  }
  if (op.q.$where) {
    return op.q.$where;
  }
  return op.q;
}

class MongoDBSensor extends BaseSensor {
  constructor(agent) {
    super({ id: ID, agent });
  }

  install({ ModuleHook }) {
    const v4MethodsWithFilter = [
      'updateOne',
      'replaceOne',
      'updateMany',
      'deleteOne',
      'deleteMany',
      'findOneAndDelete',
      'findOneAndReplace',
      'findOneAndUpdate',
      'countDocuments',
      'count',
      'distinct',
    ];

    ModuleHook.resolve({ name: ID, version: '<4.0.0' }, (mongodb, { version }) => {
      ['command', 'cursor'].forEach(method => {
        patcher.patch(mongodb.CoreServer.prototype, method, {
          alwaysRun: true,
          name: `mongodb.CoreServer.prototype.${method}`,
          patchType: PATCH_TYPES.PROTECT_SINK,
          pre: (wrapCtx) => {
            emitSinkEvent(
              getCursorQueryData(wrapCtx.args, version),
              SINK_TYPES.NOSQL_QUERY,
              ID
            );
          }
        });
      });

      ['remove', 'update'].forEach(method => {
        patcher.patch(mongodb.CoreServer.prototype, method, {
          alwaysRun: true,
          name: 'mongodb.CoreServer.prototype.remove',
          patchType: PATCH_TYPES.PROTECT_SINK,
          pre: (wrapCtx) => {
            const ops = Array.isArray(wrapCtx.args[1]) ? wrapCtx.args[1] : [wrapCtx.args[1]];

            for (const op of ops) {
              const eData = getOpQueryData(op);
              if (eData) {
                emitSinkEvent(eData, SINK_TYPES.NOSQL_QUERY, ID);
              }
            }
          }
        });
      });

      patcher.patch(mongodb.Db.prototype, 'eval', {
        alwaysRun: true,
        name: 'mongodb.Db.prototype.eval',
        patchType: PATCH_TYPES.PROTECT_SINK,
        pre: (wrapCtx) => {
          emitSinkEvent(wrapCtx.args[0], SINK_TYPES.NOSQL_QUERY, ID);
        }
      });
    });

    ModuleHook.resolve({ name: ID, version: '>=4.0.0' }, (mongodb) => {
      v4MethodsWithFilter.forEach((method) => {
        patcher.patch(mongodb.Collection.prototype, method, {
          alwaysRun: true,
          name: `mongodb.Collection.prototype.${method}`,
          patchType: PATCH_TYPES.PROTECT_SINK,
          pre: (wrapCtx) => {
            const value = typeof wrapCtx.args[0] == 'function' ? null : wrapCtx.args[0];
            emitSinkEvent(value, SINK_TYPES.NOSQL_QUERY, ID);
          },
        });
      });

      patcher.patch(mongodb.Db.prototype, 'command', {
        alwaysRun: true,
        name: 'mongodb.Db.prototype.command',
        patchType: PATCH_TYPES.PROTECT_SINK,
        pre: (wrapCtx) => {
          const value = wrapCtx.args[0] && wrapCtx.args[0].filter;
          emitSinkEvent(value, SINK_TYPES.NOSQL_QUERY, ID);
        }
      });
    });

    ModuleHook.resolve({ name: ID, file: 'lib/cursor/find_cursor', version: '>=4.0.0' }, (cursor) => patcher.patch(cursor, 'FindCursor', {
      alwaysRun: true,
      name: 'mongodb.FindCursor',
      patchType: PATCH_TYPES.PROTECT_SINK,
      pre: (wrapCtx) => {
        const value = wrapCtx.args[2];
        emitSinkEvent(value, SINK_TYPES.NOSQL_QUERY, ID);
      }
    }));

    return this;
  }
}

module.exports = MongoDBSensor;
