Skip to content

HTTP Response Sent Before Encryption Completes Due to Async Cache Access in Exception Filter #15214

@kheyrem

Description

@kheyrem

Is there an existing issue for this?

  • I have searched the existing issues

Current behavior

import {
ExceptionFilter,
Catch,
ArgumentsHost,
HttpException,
HttpStatus,
Inject,
CACHE_MANAGER,
BadRequestException,
} from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
import { Cache } from 'cache-manager';
import { CacheKeys } from '../enums/tayopay.enum';
import * as CryptoJS from 'crypto-js';

@catch()
export class CatchEverythingFilter implements ExceptionFilter {
constructor(private readonly httpAdapterHost: HttpAdapterHost, @Inject(CACHE_MANAGER) private readonly cacheManager: Cache) { }

catch(exception: BadRequestException, host: ArgumentsHost){
const { httpAdapter } = this.httpAdapterHost;

const ctx = host.switchToHttp();
const request = ctx.getRequest();

const httpStatus =
  exception instanceof BadRequestException
    ? exception.getStatus()
    : HttpStatus.INTERNAL_SERVER_ERROR;

var encrypted;
const cacheKey = `${CacheKeys.JWT}#${request?.user?.id || request?.user?.userId}`;

(this.cacheManager.get<string>(cacheKey)).then((res => {
  const errorResponse =
    typeof exception.getResponse() === 'string'
      ? { message: exception.getResponse() }
      : exception.getResponse();

  encrypted = CryptoJS.AES.encrypt(
    JSON.stringify(errorResponse),
    res
  ).toString();


}));

const responseBody = {
  statusCode: httpStatus,
  payload: encrypted
};

httpAdapter.reply(ctx.getResponse(), responseBody, httpStatus);

}
}

Minimum reproduction code

https://github.com/kheyrem

Steps to reproduce

No response

Expected behavior

i wan to return encrypted repones

Package

  • I don't know. Or some 3rd-party package
  • @nestjs/common
  • @nestjs/core
  • @nestjs/microservices
  • @nestjs/platform-express
  • @nestjs/platform-fastify
  • @nestjs/platform-socket.io
  • @nestjs/platform-ws
  • @nestjs/testing
  • @nestjs/websockets
  • Other (see below)

Other package

No response

NestJS version

No response

Packages versions

Node.js version

No response

In which operating systems have you tested?

  • macOS
  • Windows
  • Linux

Other

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    needs triageThis issue has not been looked into

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions