# All files / modules/audit/interceptors audit.interceptor.ts

0% Statements 0/70
0% Branches 0/31
0% Functions 0/16
0% Lines 0/66

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180

     import {
      Injectable,
      NestInterceptor,
      ExecutionContext,
      CallHandler,
    } from '@nestjs/common';
    import { Observable, tap } from 'rxjs';
    import { Reflector } from '@nestjs/core';
    import { AuditService, CreateAuditLogParams } from '../services/audit.service';
    import { AuditAction as AuditActionEnum } from '../entities/audit-log.entity';

    export const AUDIT_ACTION_KEY = 'audit_action';
    export const AUDIT_ENTITY_KEY = 'audit_entity';
    export const SKIP_AUDIT_KEY = 'skip_audit';

    /**
     * Decorator to specify audit action for a route
     */
    export function AuditActionDecorator(action: AuditActionEnum) {
      return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
        Reflect.defineMetadata(AUDIT_ACTION_KEY, action, descriptor.value);
        return descriptor;
      };
    }

    /**
     * Decorator to specify entity type for audit logging
     */
    export function AuditEntity(entityType: string) {
      return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
        Reflect.defineMetadata(AUDIT_ENTITY_KEY, entityType, descriptor.value);
        return descriptor;
      };
    }

    /**
     * Decorator to skip audit logging for a route
     */
    export function SkipAudit() {
      return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
        Reflect.defineMetadata(SKIP_AUDIT_KEY, true, descriptor.value);
        return descriptor;
      };
    }

    @Injectable()
    export class AuditInterceptor implements NestInterceptor {
      constructor(
        private readonly auditService: AuditService,
        private readonly reflector: Reflector,
      ) {}

      intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
        const request = context.switchToHttp().getRequest();
        const handler = context.getHandler();
        const startTime = Date.now();

        // Check if audit should be skipped
        const skipAudit = this.reflector.get<boolean>(SKIP_AUDIT_KEY, handler);
        Iif (skipAudit) {
          return next.handle();
        }

        // Get audit metadata
        const auditAction = this.reflector.get<AuditActionEnum>(AUDIT_ACTION_KEY, handler);
        const entityType = this.reflector.get<string>(AUDIT_ENTITY_KEY, handler);

        // If no explicit audit action, try to infer from HTTP method
        const action = auditAction || this.inferActionFromMethod(request.method);
        Iif (!action) {
          return next.handle();
        }

        return next.handle().pipe(
          tap({
            next: async (response) => {
              const duration = Date.now() - startTime;
              await this.logAudit(request, action, entityType, response, 200, duration);
            },
            error: async (error) => {
              const duration = Date.now() - startTime;
              const statusCode = error.status || 500;
              await this.logAudit(request, action, entityType, null, statusCode, duration);
            },
          }),
        );
      }

      private inferActionFromMethod(method: string): AuditActionEnum | null {
        switch (method.toUpperCase()) {
          case 'POST':
            return AuditActionEnum.CREATE;
          case 'PUT':
          case 'PATCH':
            return AuditActionEnum.UPDATE;
          case 'DELETE':
            return AuditActionEnum.DELETE;
          case 'GET':
            return null; // Don't log reads by default
          default:
            return null;
        }
      }

      private async logAudit(
        request: any,
        action: AuditActionEnum,
        entityType: string | undefined,
        response: any,
        statusCode: number,
        duration: number,
      ): Promise<void> {
        try {
          const tenantId = request.user?.tenantId || request.headers['x-tenant-id'];
          Iif (!tenantId) {
            return; // Cannot log without tenant context
          }

          const params: CreateAuditLogParams = {
            tenant_id: tenantId,
            user_id: request.user?.sub || request.user?.id,
            action,
            entity_type: entityType || this.inferEntityFromPath(request.path),
            entity_id: request.params?.id,
            old_values: request.body?._oldValues, // If provided by controller
            new_values: this.sanitizeBody(request.body),
            ip_address: this.getClientIp(request),
            user_agent: request.headers['user-agent'],
            endpoint: request.path,
            http_method: request.method,
            response_status: statusCode,
            duration_ms: duration,
            metadata: {
              query: request.query,
              response_id: response?.id,
            },
          };

          await this.auditService.createAuditLog(params);
        } catch (error) {
          // Don't let audit logging failures affect the request
          console.error('Failed to create audit log:', error);
        }
      }

      private inferEntityFromPath(path: string): string {
        // Extract entity type from path like /api/v1/users/:id -> users
        const segments = path.split('/').filter(Boolean);
        const apiIndex = segments.findIndex((s) => s === 'api');
        Iif (apiIndex !== -1 && segments.length > apiIndex + 2) {
          return segments[apiIndex + 2]; // Skip 'api' and version
        }
        return segments[segments.length - 1] || 'unknown';
      }

      private sanitizeBody(body: any): Record<string, any> | undefined {
        Iif (!body) return undefined;

        const sanitized = { ...body };
        // Remove sensitive fields
        const sensitiveFields = ['password', 'token', 'secret', 'creditCard', 'cvv', '_oldValues'];
        for (const field of sensitiveFields) {
          Iif (field in sanitized) {
            sanitized[field] = '[REDACTED]';
          }
        }
        return sanitized;
      }

      private getClientIp(request: any): string {
        return (
          request.headers['x-forwarded-for']?.split(',')[0]?.trim() ||
          request.headers['x-real-ip'] ||
          request.connection?.remoteAddress ||
          request.ip ||
          'unknown'
        );
      }
    }