/**
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 { 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/fastify');
const { AsyncStorage, KEYS } = require('../../../core/async-storage');
const stackFactory = require('../../../core/stacktrace').singleton;

class FastifyXssSink {
  constructor(agent) {
    this.common = require('../../sinks/common')(agent);
    this.rules = get(policy, 'rules');
    this.moduleName = 'fastify.Reply';
    this.ruleId = 'reflected-xss';
    this.signature = new Signature({
      moduleName: this.moduleName,
      methodName: 'send',
      isModule: true
    });

    this.registerRouteWrapperHandler();
    this.instrumentHandleRequest();
  }

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

  /**
   * Implements a fastify `onRoute` hook to wrap the handler
   * if it is a promise
   */
  registerRouteWrapperHandler() {
    const self = this;
    agentEmitter.on(EVENTS.ON_ROUTE, (routeOptions) => {
      patcher.patch(routeOptions, 'handler', {
        name: 'fastify.route',
        patchType: PATCH_TYPES.ASYNC_CONTEXT,
        alwaysRun: true,
        post(data) {
          const result = get(data, 'result');
          if (result && typeof result.then === 'function') {
            data.result = self.wrapAsyncRouteHandler(data.result);
          }
        }
      });
    });
  }

  /**
   * If handler is async it will set a key in `AsyncStorage`
   * this is used in `Reply.send` to determine whether or not
   * to take a stack trace
   *
   * @param {Function} handler route handler
   * @return {Function} wrapped handler
   */
  wrapAsyncRouteHandler(handler) {
    return handler.then((payload) => {
      AsyncStorage.set(KEYS.FASTIFY_HANDLER_RESOLVED, true);
      return payload;
    });
  }

  /**
   * Sets up a hook for when `fastify/lib/handleRequest` is required
   */
  instrumentHandleRequest() {
    moduleHook.resolve(
      { name: 'fastify', file: 'lib/handleRequest.js' },
      this.registerXssHandler.bind(this)
    );
  }

  /**
   * wraps `handleRequest` to use a patched version of reply
   * to check for `reflected-xss`
   *
   * @param {Function} handleRequest
   * @return {Function} wrapped handleRequest
   */
  registerXssHandler(handleRequest) {
    const self = this;
    return patcher.patch(handleRequest, {
      name: 'fastify.handleRequest',
      patchType: PATCH_TYPES.ASYNC_CONTEXT,
      pre(data) {
        if (!self.enabled) {
          return;
        }

        const [, , reply] = data.args;

        self.registerSendHandler(reply);
        self.registerEndHandler(reply);
      }
    });
  }

  /**
   * adds a pre handler for `reply.send`
   * to check for `reflected-xss`
   *
   * @param {Fastify.reply} reply outgoing message
   */
  registerSendHandler(reply) {
    const {
      isVulnerable,
      xss: { disallowedTags },
      requiredTags
    } = this.common;
    const { ruleId } = this;

    patcher.patch(reply, 'send', {
      name: 'fastify.reply',
      patchType: PATCH_TYPES.ASYNC_CONTEXT,
      alwaysRun: true,
      pre(data) {
        const [input] = data.args;
        /*
         * If the handler has resolved then Fastify is calling
         * reply.send rather than the handler itself, just
         * call original
         */
        if (AsyncStorage.get(KEYS.FASTIFY_HANDLER_RESOLVED)) {
          return;
        }

        /*
         * Otherwise the handler is directly calling Reply.send
         * so get a nice stack trace if the input is vulnerable
         */
        if (
          isVulnerable({
            input,
            disallowedTags,
            requiredTags,
            ruleId
          })
        ) {
          AsyncStorage.set(KEYS.FASTIFY_REPLY_SEND_STATE, {
            stack: stackFactory.createSnapshot({
              constructorOpt: data.hooked
            }),
            payload: input,
            reply
          });
        }
      }
    });
  }

  /**
   * adds a pre handler for `reply.end`
   * to check for `reflected-xss`
   *
   * @param {Fastify.reply} reply outgoing message
   */
  registerEndHandler(reply) {
    const { ruleId, signature } = this;
    const {
      isVulnerable,
      xss: { disallowedTags },
      requiredTags,
      report
    } = this.common;

    const res = reply.raw || reply.res;

    patcher.patch(res, 'end', {
      name: 'fastify.reply.raw',
      patchType: PATCH_TYPES.ASSESS_SINK,
      alwaysRun: true,
      pre(data) {
        // Final check after handler and all hooks have ran
        const replyState = AsyncStorage.get(KEYS.FASTIFY_REPLY_SEND_STATE);
        const payload = data.args[0] || replyState && replyState.payload;

        if (!payload) return;

        if (
          isVulnerable({
            input: payload,
            disallowedTags,
            requiredTags,
            ruleId
          })
        ) {
          const ctxt = replyState
            ? CallContext.create({
                obj: replyState.reply,
                args: [replyState.payload],
                result: null,
                stacktrace: replyState.stack
              })
            : CallContext.create({
                obj: data.obj,
                args: [payload],
                result: null,
                stackOpts: {
                  constructorOpt: data.hooked
                }
              });

          report({
            ruleId,
            signature,
            input: payload,
            ctxt
          });
        }
      }
    });
  }
}

module.exports = FastifyXssSink;
