/**
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.
*/
/**
 * PostgreSQL protect-mode inFilter hooks.
 * @module lib/rules/protect/in-filters/postgres
 */

'use strict';

const _ = require('lodash');

const constants = require('../../constants');
const BaseSensor = require('../../hooks/frameworks/base');
const patcher = require('../../hooks/patcher');
const { PATCH_TYPES } = require('../../constants');
const { emitSinkEvent } = require('../../hooks/frameworks/common');

const { SINK_TYPES } = constants;
const ID = 'postgres';

/**
 * @param {any} optsOrStr
 * @returns {string | null}
 */
const extractQueryText = (optsOrStr) => {
  if (_.isEmpty(optsOrStr)) return null;
  return _.isString(optsOrStr) ? optsOrStr : optsOrStr.text;
};

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

  install({ ModuleHook }) {
    /* Hook the client's query method: */
    ModuleHook.resolve({ name: 'pg', file: 'lib/client.js' }, (client) => {
      patcher.patch(client.prototype, 'query', {
        name: 'pg.Client.prototype',
        patchType: PATCH_TYPES.PROTECT_SINK,
        alwaysRun: true,
        /* We have to pull the text value out of the 1st argument. */
        pre: (wrapCtx) => {
          const opts = _.get(wrapCtx, 'args.0');
          const query = extractQueryText(opts);
          emitSinkEvent(query, SINK_TYPES.SQL_QUERY, ID);
        }
      });
    });

    /* Hook the pool's query method: */
    ModuleHook.resolve({ name: 'pg-pool' }, (pool) => {
      patcher.patch(pool.prototype, 'query', {
        name: 'pg-pool.prototype',
        patchType: PATCH_TYPES.PROTECT_SINK,
        alwaysRun: true,
        /* The 1st arg is always a query String. */
        pre: (wrapCtx) => {
          const query = _.get(wrapCtx, 'args.0');
          emitSinkEvent(query, SINK_TYPES.SQL_QUERY, ID);
        }
      });
    });

    return this;
  }
}

module.exports = PostgreSQLSensor;
