Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion apps/backend/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ import { ExportModule } from './export/export.module';
import { SignalsModule } from './signals/signals.module';
import { AppConfigModule } from './config/config.module';
import { CrowdfundModule } from './crowdfund/crowdfund.module';
import { AuditModule } from './audit/audit.module';
import { AuditLogInterceptor } from './audit/interceptors/audit-log.interceptor';

@Module({
imports: [
Expand Down Expand Up @@ -124,6 +126,7 @@ import { CrowdfundModule } from './crowdfund/crowdfund.module';
FeatureFlagsModule,
CrowdfundModule,
AppConfigModule,
AuditModule,
],
controllers: [AppController, TestController, TestExceptionController],
providers: [
Expand All @@ -136,6 +139,10 @@ import { CrowdfundModule } from './crowdfund/crowdfund.module';
provide: APP_INTERCEPTOR,
useClass: IdempotencyInterceptor,
},
{
provide: APP_INTERCEPTOR,
useClass: AuditLogInterceptor,
},
{
provide: APP_INTERCEPTOR,
useClass: DeprecationInterceptor,
Expand All @@ -146,4 +153,4 @@ export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(RequestIdMiddleware, LoggerMiddleware).forRoutes('*');
}
}
}
69 changes: 69 additions & 0 deletions apps/backend/src/audit/audit.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import {
Controller,
Get,
Query,
UseGuards,
ParseIntPipe,
DefaultValuePipe,
} from '@nestjs/common';
import {
ApiTags,
ApiOperation,
ApiResponse,
ApiBearerAuth,
ApiQuery,
} from '@nestjs/swagger';
import { AuditService } from './audit.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../auth/roles.guard';
import { Roles } from '../auth/decorators/auth.decorators';
import { UserRole } from '../users/entities/user.entity';

@ApiTags('admin-audit-logs')
@ApiBearerAuth('JWT-auth')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(UserRole.ADMIN)
@Controller('admin/audit-logs')
export class AuditController {
constructor(private readonly auditService: AuditService) {}

@Get()
@ApiOperation({
summary: 'Get all audit logs (admin only)',
description:
'Retrieves a paginated list of audit logs. Requires admin privileges.',
})
@ApiQuery({ name: 'limit', required: false, type: Number })
@ApiQuery({ name: 'offset', required: false, type: Number })
@ApiResponse({
status: 200,
description: 'Audit logs retrieved successfully',
schema: {
properties: {
logs: {
type: 'array',
items: {
properties: {
id: { type: 'string', format: 'uuid' },
userId: { type: 'string', format: 'uuid', nullable: true },
action: { type: 'string', example: 'login' },
ipAddress: { type: 'string', example: '127.0.0.1' },
metadata: { type: 'object', nullable: true },
createdAt: { type: 'string', format: 'date-time' },
},
},
},
count: { type: 'number', example: 1 },
},
},
})
@ApiResponse({ status: 401, description: 'Unauthorized' })
@ApiResponse({ status: 403, description: 'Forbidden (admin only)' })
async getAuditLogs(
@Query('limit', new DefaultValuePipe(100), ParseIntPipe) limit: number,
@Query('offset', new DefaultValuePipe(0), ParseIntPipe) offset: number,
) {
const [logs, count] = await this.auditService.findAll(limit, offset);
return { logs, count };
}
}
18 changes: 18 additions & 0 deletions apps/backend/src/audit/audit.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Module, forwardRef } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuditLog } from './entities/audit-log.entity';
import { AuditService } from './audit.service';
import { AuditController } from './audit.controller';
import { AuditLogInterceptor } from './interceptors/audit-log.interceptor';
import { UsersModule } from '../users/users.module';

@Module({
imports: [
TypeOrmModule.forFeature([AuditLog]),
forwardRef(() => UsersModule),
],
controllers: [AuditController],
providers: [AuditService, AuditLogInterceptor],
exports: [AuditService, AuditLogInterceptor],
})
export class AuditModule {}
35 changes: 35 additions & 0 deletions apps/backend/src/audit/audit.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { AuditLog } from './entities/audit-log.entity';

@Injectable()
export class AuditService {
constructor(
@InjectRepository(AuditLog)
private readonly auditLogRepo: Repository<AuditLog>,
) {}

async log(
action: string,
userId: string | null,
ipAddress: string | null,
metadata?: Record<string, any>,
): Promise<AuditLog> {
const auditLog = this.auditLogRepo.create({
action,
userId,
ipAddress,
metadata: metadata || null,
});
return this.auditLogRepo.save(auditLog);
}

async findAll(limit = 100, offset = 0): Promise<[AuditLog[], number]> {
return this.auditLogRepo.findAndCount({
order: { createdAt: 'DESC' },
take: limit,
skip: offset,
});
}
}
5 changes: 5 additions & 0 deletions apps/backend/src/audit/decorators/audit-log.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { SetMetadata } from '@nestjs/common';

export const AUDIT_LOG_ACTION_KEY = 'audit_log_action';
export const AuditLogAction = (action: string) =>
SetMetadata(AUDIT_LOG_ACTION_KEY, action);
38 changes: 38 additions & 0 deletions apps/backend/src/audit/entities/audit-log.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
ManyToOne,
JoinColumn,
Index,
} from 'typeorm';
import { User } from '../../users/entities/user.entity';

@Entity('audit_logs')
export class AuditLog {
@PrimaryGeneratedColumn('uuid')
id: string;

@Column({ name: 'userId', type: 'uuid', nullable: true })
@Index()
userId: string | null;

@Column({ type: 'varchar', length: 100 })
@Index()
action: string;

@Column({ type: 'varchar', length: 45, nullable: true })
ipAddress: string | null;

@Column({ type: 'jsonb', nullable: true })
metadata: Record<string, any> | null;

@CreateDateColumn({ type: 'timestamp with time zone' })
@Index()
createdAt: Date;

@ManyToOne(() => User, { onDelete: 'SET NULL', nullable: true })
@JoinColumn({ name: 'userId' })
user: User | null;
}
110 changes: 110 additions & 0 deletions apps/backend/src/audit/interceptors/audit-log.interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import {
Injectable,
NestInterceptor,
ExecutionContext,
CallHandler,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { AuditService } from '../audit.service';
import { AUDIT_LOG_ACTION_KEY } from '../decorators/audit-log.decorator';
import { UsersService } from '../../users/users.service';

interface RequestWithUser {
headers: Record<string, string | string[] | undefined>;
ip?: string;
connection?: { remoteAddress?: string };
body?: Record<string, unknown>;
user?: { id?: string; sub?: string };
}

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

intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const action = this.reflector.get<string>(
AUDIT_LOG_ACTION_KEY,
context.getHandler(),
);

if (!action) {
return next.handle();
}

const request = context.switchToHttp().getRequest<RequestWithUser>();

let ipAddress: string | null = null;
const xForwardedFor = request.headers['x-forwarded-for'];
if (typeof xForwardedFor === 'string') {
ipAddress = xForwardedFor.split(',')[0].trim();
} else if (Array.isArray(xForwardedFor) && xForwardedFor.length > 0) {
ipAddress = xForwardedFor[0].split(',')[0].trim();
} else {
ipAddress = request.ip || request.connection?.remoteAddress || null;
}

// Filter out sensitive data from request body metadata
const metadata = request.body ? { ...request.body } : {};
const sensitiveKeys = [
'password',
'newPassword',
'token',
'signedChallenge',
];
for (const key of sensitiveKeys) {
if (key in metadata) {
metadata[key] = '[REDACTED]';
}
}

return next.handle().pipe(
tap((response: unknown) => {
// Execute logging asynchronously as fire-and-forget
void (async () => {
let userId: string | null = null;

// 1. Check if user is already authenticated
if (request.user?.id) {
userId = request.user.id;
} else if (request.user?.sub) {
userId = request.user.sub;
}

// 2. If login or password reset, resolve user by email from request body
if (
!userId &&
request.body &&
typeof request.body.email === 'string'
) {
try {
const user = await this.usersService.findByEmail(
request.body.email,
);
if (user) {
userId = user.id;
}
} catch {
// Ignore error
}
}

// 3. If response contains user object
if (!userId && response && typeof response === 'object') {
const resObj = response as { user?: { id?: string } };
if (resObj.user?.id) {
userId = resObj.user.id;
}
}

await this.auditService.log(action, userId, ipAddress, metadata);
})();
}),
);
}
}
4 changes: 4 additions & 0 deletions apps/backend/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ import {
} from '@nestjs/swagger';
import { ProfileResponseDto } from '../users/dto/profile-response.dto';
import { getAuthThrottleOverride } from '../common/rate-limit/rate-limit.config';
import { AuditLogAction } from '../audit/decorators/audit-log.decorator';

import {
ActiveSessionsResponseDto,
RevokeSessionResponseDto,
Expand Down Expand Up @@ -90,6 +92,7 @@ export class AuthController {
},
},
})
@AuditLogAction('login')
async login(@Body() body: LoginDto) {
const user = await this.authService.validateUser(body.email, body.password);
if (!user) {
Expand Down Expand Up @@ -172,6 +175,7 @@ export class AuthController {
status: 400,
description: 'Invalid, expired, or already-used token',
})
@AuditLogAction('password_change')
async resetPassword(@Body() body: ResetPasswordDto) {
return this.authService.resetPassword(body.token, body.newPassword);
}
Expand Down
2 changes: 1 addition & 1 deletion apps/backend/src/common/decorators/deprecated.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,4 @@ export function Deprecated(options: DeprecationOptions) {
required: false,
}),
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,10 @@ export class DeprecationInterceptor implements NestInterceptor {
}

if (meta.replacement) {
response.setHeader('Link', `<${meta.replacement}>; rel="successor-version"`);
response.setHeader(
'Link',
`<${meta.replacement}>; rel="successor-version"`,
);
}

this.logger.warn(
Expand All @@ -58,4 +61,4 @@ export class DeprecationInterceptor implements NestInterceptor {

return next.handle().pipe(tap(() => {}));
}
}
}
Loading
Loading