Skip to content

Commit ea9d388

Browse files
Merge pull request #49 from rumsan/copilot/sub-pr-48
Add audit logging for service impersonation events
2 parents 7e5962c + cadd312 commit ea9d388

1 file changed

Lines changed: 24 additions & 0 deletions

File tree

libs/user/src/lib/auths/guard/hybrid-jwt.guard.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import {
22
CanActivate,
33
ExecutionContext,
44
Injectable,
5+
Logger,
56
UnauthorizedException,
67
} from '@nestjs/common';
78
import { JwtService } from '@nestjs/jwt';
@@ -23,6 +24,12 @@ import { getSecret } from '../../utils/config.utils';
2324
*/
2425
@Injectable()
2526
export class HybridJwtGuard implements CanActivate {
27+
/**
28+
* Logger for audit logging of service impersonation events.
29+
* Tracks both successful and failed impersonation attempts for security monitoring.
30+
*/
31+
private readonly logger = new Logger(HybridJwtGuard.name);
32+
2633
constructor(
2734
private jwtService: JwtService,
2835
private prisma: PrismaService,
@@ -78,13 +85,21 @@ export class HybridJwtGuard implements CanActivate {
7885

7986
if (impersonateId) {
8087
if (!serviceClient.canImpersonate) {
88+
// Log failed impersonation attempt
89+
this.logger.warn(
90+
`Service impersonation denied - ${payload.serviceName}: service not allowed to impersonate`,
91+
);
8192
throw new UnauthorizedException(
8293
'This service is not allowed to impersonate users',
8394
);
8495
}
8596

8697
const user = await this.loadUserById(impersonateId);
8798
if (!user) {
99+
// Log failed impersonation attempt
100+
this.logger.warn(
101+
`Service impersonation denied - ${payload.serviceName}: user not found`,
102+
);
88103
throw new UnauthorizedException('Impersonated user not found');
89104
}
90105

@@ -101,12 +116,21 @@ export class HybridJwtGuard implements CanActivate {
101116
);
102117

103118
if (!canImpersonate) {
119+
// Log failed impersonation attempt
120+
this.logger.warn(
121+
`Service impersonation denied - ${payload.serviceName}: user ${user.uuid} roles not allowed`,
122+
);
104123
throw new UnauthorizedException(
105124
'Service not allowed to impersonate users with these roles',
106125
);
107126
}
108127
}
109128

129+
// Log successful impersonation
130+
this.logger.log(
131+
`Service impersonation granted - ${payload.serviceName}: user ${user.uuid} with roles ${userRoleNames.join(',')}`,
132+
);
133+
110134
request.user = {
111135
id: user.id,
112136
userId: user.id,

0 commit comments

Comments
 (0)