diff --git a/x-pack/plugins/security/server/audit/audit_service.test.ts b/x-pack/plugins/security/server/audit/audit_service.test.ts index a03e5047a10a2..cf90c7222e5a4 100644 --- a/x-pack/plugins/security/server/audit/audit_service.test.ts +++ b/x-pack/plugins/security/server/audit/audit_service.test.ts @@ -52,6 +52,7 @@ const recordAuditLoggingUsage = jest.fn(); beforeEach(() => { logger.info.mockClear(); logging.configure.mockClear(); + logger.isLevelEnabled.mockClear().mockReturnValue(true); recordAuditLoggingUsage.mockClear(); http.registerOnPostAuth.mockClear(); }); @@ -321,6 +322,41 @@ describe('#asScoped', () => { expect(logger.info).not.toHaveBeenCalled(); audit.stop(); }); + + it('does not log to audit logger if info logging level is disabled', async () => { + logger.isLevelEnabled.mockReturnValue(false); + + const audit = new AuditService(logger); + const auditSetup = audit.setup({ + license, + config, + logging, + http, + getCurrentUser, + getSpaceId, + getSID, + recordAuditLoggingUsage, + }); + const request = httpServerMock.createKibanaRequest({ + socket: { remoteAddress: '3.3.3.3' } as Socket, + headers: { + 'x-forwarded-for': '1.1.1.1, 2.2.2.2', + }, + kibanaRequestState: { requestId: 'REQUEST_ID', requestUuid: 'REQUEST_UUID' }, + }); + + await auditSetup.asScoped(request).log({ + message: 'MESSAGE', + event: { action: 'ACTION' }, + http: { request: { method: 'GET' } }, + }); + + expect(logger.info).not.toHaveBeenCalled(); + expect(logger.isLevelEnabled).toHaveBeenCalledTimes(1); + expect(logger.isLevelEnabled).toHaveBeenCalledWith('info'); + + audit.stop(); + }); }); describe('#withoutRequest', () => { diff --git a/x-pack/plugins/security/server/audit/audit_service.ts b/x-pack/plugins/security/server/audit/audit_service.ts index dddb24d47fdaf..12180808ae477 100644 --- a/x-pack/plugins/security/server/audit/audit_service.ts +++ b/x-pack/plugins/security/server/audit/audit_service.ts @@ -93,13 +93,17 @@ interface AuditServiceSetupParams { config: ConfigType['audit']; logging: Pick; http: Pick; + getCurrentUser( request: KibanaRequest ): ReturnType | undefined; + getSID(request: KibanaRequest): Promise; + getSpaceId( request: KibanaRequest ): ReturnType | undefined; + recordAuditLoggingUsage(): void; } @@ -154,9 +158,13 @@ export class AuditService { } }; + const isLoggingEnabled = () => { + return this.logger.isLevelEnabled('info'); + }; + const asScoped = (request: KibanaRequest): AuditLogger => ({ log: async (event) => { - if (!event) { + if (!event || !isLoggingEnabled()) { return; } const spaceId = getSpaceId(request); @@ -197,7 +205,7 @@ export class AuditService { }); http.registerOnPostAuth((request, response, t) => { - if (request.auth.isAuthenticated) { + if (request.auth.isAuthenticated && isLoggingEnabled()) { asScoped(request).log(httpRequestEvent({ request })); } return t.next();