From 701b9aac2fcd23e1c062bf123da0e37920e9efee Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Antonio=20David=20Guti=C3=A9rrez?=
Date: Tue, 21 Nov 2023 09:32:51 +0100
Subject: [PATCH 001/138] feat(logging): remove plugin logger from start tasks
of main plugin
- Enhance the logging messages
- Minor enhancements
---
plugins/main/server/controllers/wazuh-api.ts | 2 +-
.../start/cron-scheduler/error-handler.ts | 20 +-
.../start/cron-scheduler/save-document.ts | 134 ++++--
.../start/cron-scheduler/scheduler-handler.ts | 120 +++--
plugins/main/server/start/initialize/index.ts | 193 +++-----
.../server/start/migration-tasks/index.ts | 9 +-
.../migration-tasks/reports_directory_name.ts | 76 ++--
plugins/main/server/start/monitoring/index.ts | 419 ++++++++++--------
plugins/main/server/start/queue/index.ts | 48 +-
9 files changed, 526 insertions(+), 495 deletions(-)
diff --git a/plugins/main/server/controllers/wazuh-api.ts b/plugins/main/server/controllers/wazuh-api.ts
index cc7bf6cf69..f9ec4464d4 100644
--- a/plugins/main/server/controllers/wazuh-api.ts
+++ b/plugins/main/server/controllers/wazuh-api.ts
@@ -723,7 +723,7 @@ export class WazuhApiCtrl {
if (delay) {
addJobToQueue({
startAt: new Date(Date.now() + delay),
- run: async () => {
+ run: async contextJob => {
try {
await context.wazuh.api.client.asCurrentUser.request(
method,
diff --git a/plugins/main/server/start/cron-scheduler/error-handler.ts b/plugins/main/server/start/cron-scheduler/error-handler.ts
index e1ad63be95..bcf465f836 100644
--- a/plugins/main/server/start/cron-scheduler/error-handler.ts
+++ b/plugins/main/server/start/cron-scheduler/error-handler.ts
@@ -1,23 +1,17 @@
-import { log } from '../../lib/logger';
-import { getConfiguration } from '../../lib/get-configuration';
-
const DEBUG = 'debug';
const INFO = 'info';
const ERROR = 'error';
-function logLevel(level: string){
- return level === DEBUG ? INFO : level;
-};
-
export function ErrorHandler(error, serverLogger) {
- const { ['logs.level']: logsLevel } = getConfiguration();
const errorLevel = ErrorLevels[error.error] || ERROR;
- log('Cron-scheduler', error, errorLevel === ERROR ? INFO : errorLevel);
try {
- if (errorLevel === DEBUG && logsLevel !== DEBUG) return;
- serverLogger[logLevel(errorLevel)](`${error instanceof Error ? error.toString() : JSON.stringify(error)}`);
+ serverLogger[errorLevel](
+ `${error instanceof Error ? error.toString() : JSON.stringify(error)}`,
+ );
} catch (error) {
- serverLogger[logLevel(errorLevel)](`Message too long to show in console output, check the log file`)
+ serverLogger.error(
+ `Message too long to show in console output, check the log file`,
+ );
}
}
@@ -34,4 +28,4 @@ const ErrorLevels = {
10005: DEBUG,
10006: DEBUG,
10007: DEBUG,
-}
\ No newline at end of file
+};
diff --git a/plugins/main/server/start/cron-scheduler/save-document.ts b/plugins/main/server/start/cron-scheduler/save-document.ts
index 87b2203a37..f8abf8e19d 100644
--- a/plugins/main/server/start/cron-scheduler/save-document.ts
+++ b/plugins/main/server/start/cron-scheduler/save-document.ts
@@ -1,22 +1,24 @@
import { BulkIndexDocumentsParams } from 'elasticsearch';
import { getConfiguration } from '../../lib/get-configuration';
-import { log } from '../../lib/logger';
import { indexDate } from '../../lib/index-date';
-import { WAZUH_STATISTICS_DEFAULT_INDICES_SHARDS, WAZUH_STATISTICS_DEFAULT_INDICES_REPLICAS } from '../../../common/constants';
+import {
+ WAZUH_STATISTICS_DEFAULT_INDICES_SHARDS,
+ WAZUH_STATISTICS_DEFAULT_INDICES_REPLICAS,
+} from '../../../common/constants';
import { tryCatchForIndexPermissionError } from '../tryCatchForIndexPermissionError';
+import { getSettingDefaultValue } from '../../../common/services/settings';
export interface IIndexConfiguration {
- name: string
- creation: 'h' | 'd' | 'w' | 'm'
- mapping?: string
- shards?: number
- replicas?: number
+ name: string;
+ creation: 'h' | 'd' | 'w' | 'm';
+ mapping?: string;
+ shards?: number;
+ replicas?: number;
}
export class SaveDocument {
context: any;
esClientInternalUser: any;
- logPath = 'cron-scheduler|SaveDocument';
constructor(context) {
this.context = context;
@@ -28,38 +30,67 @@ export class SaveDocument {
const index = this.addIndexPrefix(name);
const indexCreation = `${index}-${indexDate(creation)}`;
try {
- await this.checkIndexAndCreateIfNotExists(indexCreation, shards, replicas);
- const createDocumentObject = this.createDocument(doc, indexCreation, mapping);
- const response = await this.esClientInternalUser.bulk(createDocumentObject);
- log(this.logPath, `Response of create new document ${JSON.stringify(response)}`, 'debug');
- // await this.checkIndexPatternAndCreateIfNotExists(index);
+ await this.checkIndexAndCreateIfNotExists(
+ indexCreation,
+ shards,
+ replicas,
+ );
+ const createDocumentObject = this.createDocument(
+ doc,
+ indexCreation,
+ mapping,
+ );
+ this.context.wazuh.logger.debug('Bulk data');
+ const response = await this.esClientInternalUser.bulk(
+ createDocumentObject,
+ );
+ this.context.wazuh.logger.debug(
+ `Bulked data. Response of creating the new document ${JSON.stringify(
+ response,
+ )}`,
+ );
} catch (error) {
- if (error.status === 403)
- throw { error: 403, message: `Authorization Exception in the index "${index}"` }
- if (error.status === 409)
- throw { error: 409, message: `Duplicate index-pattern: ${index}` }
+ if (error.status === 403) {
+ throw {
+ error: 403,
+ message: `Authorization Exception in the index "${index}"`,
+ };
+ }
+ if (error.status === 409) {
+ throw { error: 409, message: `Duplicate index-pattern: ${index}` };
+ }
throw error;
}
}
private async checkIndexAndCreateIfNotExists(index, shards, replicas) {
try {
- await tryCatchForIndexPermissionError(index) (async() => {
- const exists = await this.esClientInternalUser.indices.exists({ index });
- log(this.logPath, `Index '${index}' exists? ${exists.body}`, 'debug');
+ await tryCatchForIndexPermissionError(index)(async () => {
+ this.context.wazuh.logger.debug(
+ `Checking the existence of ${index} index`,
+ );
+ const exists = await this.esClientInternalUser.indices.exists({
+ index,
+ });
+ this.context.wazuh.logger.debug(
+ `Index '${index}' exists? ${exists.body}`,
+ );
if (!exists.body) {
- const response = await this.esClientInternalUser.indices.create({
+ this.context.wazuh.logger.debug(`Creating ${index} index`);
+ await this.esClientInternalUser.indices.create({
index,
body: {
settings: {
index: {
- number_of_shards: shards ?? WAZUH_STATISTICS_DEFAULT_INDICES_SHARDS,
- number_of_replicas: replicas ?? WAZUH_STATISTICS_DEFAULT_INDICES_REPLICAS
- }
- }
- }
+ number_of_shards:
+ shards ?? WAZUH_STATISTICS_DEFAULT_INDICES_SHARDS,
+ number_of_replicas:
+ replicas ?? WAZUH_STATISTICS_DEFAULT_INDICES_REPLICAS,
+ },
+ },
+ },
});
- log(this.logPath, `Status of create a new index: ${JSON.stringify(response)}`, 'debug');
+ this.context.wazuh.logger.info(`${index} index created`);
}
})();
} catch (error) {
@@ -68,21 +99,33 @@ export class SaveDocument {
}
private checkDuplicateIndexError(error: any) {
- const { type } = ((error || {}).body || {}).error || {};
- if (!['resource_already_exists_exception'].includes(type))
+ if (
+ !['resource_already_exists_exception'].includes(error?.body?.error?.type)
+ ) {
throw error;
+ }
}
- private createDocument(doc, index, mapping: string): BulkIndexDocumentsParams {
+ private createDocument(
+ doc,
+ index,
+ mapping: string,
+ ): BulkIndexDocumentsParams {
const createDocumentObject: BulkIndexDocumentsParams = {
index,
- body: doc.map(item => `{"index": { "_index": "${index}" }}\n${JSON.stringify({
- ...this.buildData(item, mapping),
- timestamp: new Date(Date.now()).toISOString()
- })}\n`)
- .join('')
+ body: doc
+ .map(
+ item =>
+ `{"index": { "_index": "${index}" }}\n${JSON.stringify({
+ ...this.buildData(item, mapping),
+ timestamp: new Date(Date.now()).toISOString(),
+ })}\n`,
+ )
+ .join(''),
};
- log(this.logPath, `Document object: ${JSON.stringify(createDocumentObject)}`, 'debug');
+ this.context.wazuh.logger.debug(
+ `Document object: ${JSON.stringify(createDocumentObject)}`,
+ );
return createDocumentObject;
}
@@ -93,22 +136,21 @@ export class SaveDocument {
const getValue = (key: string, item) => {
const keys = key.split('.');
if (keys.length === 1) {
- if(key.match(/\[.*\]/)){
+ if (key.match(/\[.*\]/)) {
return getItemArray(
item[key.replace(/\[.*\]/, '')],
- key.match(/\[(.*)\]/)[1]
+ key.match(/\[(.*)\]/)[1],
);
}
return JSON.stringify(item[key]);
}
- return getValue(keys.slice(1).join('.'), item[keys[0]])
- }
+ return getValue(keys.slice(1).join('.'), item[keys[0]]);
+ };
if (mapping) {
let data;
- data = mapping.replace(
- /\${([a-z|A-Z|0-9|\.\-\_\[.*\]]+)}/gi,
- (...key) => getValue(key[1], item)
- )
+ data = mapping.replace(/\${([a-z|A-Z|0-9|\.\-\_\[.*\]]+)}/gi, (...key) =>
+ getValue(key[1], item),
+ );
return JSON.parse(data);
}
@@ -120,8 +162,8 @@ export class SaveDocument {
private addIndexPrefix(index): string {
const configFile = getConfiguration();
- const prefix = configFile['cron.prefix'] || 'wazuh';
+ const prefix =
+ configFile['cron.prefix'] || getSettingDefaultValue('cron.prefix');
return `${prefix}-${index}`;
}
-
}
diff --git a/plugins/main/server/start/cron-scheduler/scheduler-handler.ts b/plugins/main/server/start/cron-scheduler/scheduler-handler.ts
index 4da8234bca..3f7679dc68 100644
--- a/plugins/main/server/start/cron-scheduler/scheduler-handler.ts
+++ b/plugins/main/server/start/cron-scheduler/scheduler-handler.ts
@@ -1,6 +1,5 @@
import { jobs, SchedulerJob } from './index';
import { configuredJobs } from './configured-jobs';
-import { log } from '../../lib/logger';
import { getConfiguration } from '../../lib/get-configuration';
import cron from 'node-cron';
import { WAZUH_STATISTICS_TEMPLATE_NAME } from '../../../common/constants';
@@ -8,78 +7,70 @@ import { statisticsTemplate } from '../../integration-files/statistics-template'
import { delayAsPromise } from '../../../common/utils';
import { getSettingDefaultValue } from '../../../common/services/settings';
-const blueWazuh = '\u001b[34mwazuh\u001b[39m';
-const schedulerErrorLogColors = [blueWazuh, 'scheduler', 'error'];
const schedulerJobs = [];
/**
-* Wait until Kibana server is ready
-*/
+ * Wait until Kibana server is ready
+ */
const checkPluginPlatformStatus = async function (context) {
try {
- log(
- 'scheduler-handler:checkPluginPlatformStatus',
- 'Waiting for Kibana and Elasticsearch servers to be ready...',
- 'debug'
- );
+ context.wazuh.logger.debug('Waiting for servers to be ready...');
await checkElasticsearchServer(context);
await checkTemplate(context);
return;
} catch (error) {
- log(
- 'scheduler-handler:checkPluginPlatformStatus',
- error.mesage ||error
- );
- try{
- await delayAsPromise(3000);
- await checkPluginPlatformStatus(context);
- }catch(error){};
+ context.wazuh.logger.warn(error.message || error);
+ try {
+ await delayAsPromise(3000);
+ await checkPluginPlatformStatus(context);
+ } catch (error) {}
}
- }
-
-
- /**
- * Check Elasticsearch Server status and Kibana index presence
- */
- const checkElasticsearchServer = async function (context) {
- try {
- const data = await context.core.opensearch.client.asInternalUser.indices.exists({
- index: context.server.config.opensearchDashboards.index
- });
+};
- return data.body;
- } catch (error) {
- log('scheduler-handler:checkElasticsearchServer', error.message || error);
- return Promise.reject(error);
- }
- }
+/**
+ * Check Elasticsearch Server status and Kibana index presence
+ */
+const checkElasticsearchServer = async function (context) {
+ context.wazuh.logger.debug(
+ `Checking the existence of ${context.server.config.opensearchDashboards.index} index`,
+ );
+ const data =
+ await context.core.opensearch.client.asInternalUser.indices.exists({
+ index: context.server.config.opensearchDashboards.index,
+ });
+ return data.body;
+};
- /**
+/**
* Verify wazuh-statistics template
*/
const checkTemplate = async function (context) {
try {
- log(
- 'scheduler-handler:checkTemplate',
- 'Updating the statistics template',
- 'debug'
- );
-
const appConfig = await getConfiguration();
- const prefixTemplateName = appConfig['cron.prefix'] || getSettingDefaultValue('cron.prefix');
- const statisticsIndicesTemplateName = appConfig['cron.statistics.index.name'] || getSettingDefaultValue('cron.statistics.index.name');
+ const prefixTemplateName =
+ appConfig['cron.prefix'] || getSettingDefaultValue('cron.prefix');
+ const statisticsIndicesTemplateName =
+ appConfig['cron.statistics.index.name'] ||
+ getSettingDefaultValue('cron.statistics.index.name');
const pattern = `${prefixTemplateName}-${statisticsIndicesTemplateName}-*`;
try {
// Check if the template already exists
- const currentTemplate = await context.core.opensearch.client.asInternalUser.indices.getTemplate({
- name: WAZUH_STATISTICS_TEMPLATE_NAME
- });
+ context.wazuh.logger.debug(
+ `Getting the ${WAZUH_STATISTICS_TEMPLATE_NAME} template`,
+ );
+ const currentTemplate =
+ await context.core.opensearch.client.asInternalUser.indices.getTemplate(
+ {
+ name: WAZUH_STATISTICS_TEMPLATE_NAME,
+ },
+ );
// Copy already created index patterns
- statisticsTemplate.index_patterns = currentTemplate.body[WAZUH_STATISTICS_TEMPLATE_NAME].index_patterns;
- }catch (error) {
+ statisticsTemplate.index_patterns =
+ currentTemplate.body[WAZUH_STATISTICS_TEMPLATE_NAME].index_patterns;
+ } catch (error) {
// Init with the default index pattern
statisticsTemplate.index_patterns = [pattern];
}
@@ -87,38 +78,35 @@ const checkTemplate = async function (context) {
// Check if the user is using a custom pattern and add it to the template if it does
if (!statisticsTemplate.index_patterns.includes(pattern)) {
statisticsTemplate.index_patterns.push(pattern);
- };
+ }
// Update the statistics template
+ context.wazuh.logger.debug(
+ `Updating the ${WAZUH_STATISTICS_TEMPLATE_NAME} template`,
+ );
await context.core.opensearch.client.asInternalUser.indices.putTemplate({
name: WAZUH_STATISTICS_TEMPLATE_NAME,
- body: statisticsTemplate
+ body: statisticsTemplate,
});
- log(
- 'scheduler-handler:checkTemplate',
- 'Updated the statistics template',
- 'debug'
+ context.wazuh.logger.info(
+ `Updated the ${WAZUH_STATISTICS_TEMPLATE_NAME} template`,
);
} catch (error) {
- const errorMessage = `Something went wrong updating the statistics template ${error.message || error}`;
- log(
- 'scheduler-handler:checkTemplate',
- errorMessage
+ context.wazuh.logger.error(
+ `Something went wrong updating the ${WAZUH_STATISTICS_TEMPLATE_NAME} template ${
+ error.message || error
+ }`,
);
- context.wazuh.logger.error(schedulerErrorLogColors, errorMessage);
throw error;
}
-}
+};
-export async function jobSchedulerRun(context){
+export async function jobSchedulerRun(context) {
// Check Kibana index and if it is prepared, start the initialization of Wazuh App.
await checkPluginPlatformStatus(context);
for (const job in configuredJobs({})) {
const schedulerJob: SchedulerJob = new SchedulerJob(job, context);
schedulerJobs.push(schedulerJob);
- const task = cron.schedule(
- jobs[job].interval,
- () => schedulerJob.run(),
- );
+ const task = cron.schedule(jobs[job].interval, () => schedulerJob.run());
}
}
diff --git a/plugins/main/server/start/initialize/index.ts b/plugins/main/server/start/initialize/index.ts
index e4514b0ab1..a90df44dc5 100644
--- a/plugins/main/server/start/initialize/index.ts
+++ b/plugins/main/server/start/initialize/index.ts
@@ -9,10 +9,8 @@
*
* Find more information about this on the LICENSE file.
*/
-import { log } from '../../lib/logger';
import packageJSON from '../../../package.json';
import { pluginPlatformTemplate } from '../../integration-files/kibana-template';
-import { getConfiguration } from '../../lib/get-configuration';
import { totalmem } from 'os';
import fs from 'fs';
import {
@@ -22,52 +20,27 @@ import {
PLUGIN_PLATFORM_NAME,
PLUGIN_PLATFORM_INSTALLATION_USER_GROUP,
PLUGIN_PLATFORM_INSTALLATION_USER,
- WAZUH_DEFAULT_APP_CONFIG,
PLUGIN_APP_NAME,
} from '../../../common/constants';
import { createDataDirectoryIfNotExists } from '../../lib/filesystem';
import _ from 'lodash';
-import {
- getSettingDefaultValue,
- getSettingsDefault,
-} from '../../../common/services/settings';
export function jobInitializeRun(context) {
const PLUGIN_PLATFORM_INDEX =
context.server.config.opensearchDashboards.index;
- log(
- 'initialize',
+ context.wazuh.logger.info(
`${PLUGIN_PLATFORM_NAME} index: ${PLUGIN_PLATFORM_INDEX}`,
- 'info',
);
- log('initialize', `App revision: ${packageJSON.revision}`, 'info');
-
- let configurationFile = {};
- let pattern = null;
- // Read config from package.json and wazuh.yml
- try {
- configurationFile = getConfiguration();
-
- pattern =
- configurationFile && typeof configurationFile.pattern !== 'undefined'
- ? configurationFile.pattern
- : getSettingDefaultValue('pattern');
- } catch (error) {
- log('initialize', error.message || error);
- context.wazuh.logger.error(
- 'Something went wrong while reading the configuration.' +
- (error.message || error),
- );
- }
+ context.wazuh.logger.info(`App revision: ${packageJSON.revision}`);
try {
// RAM in MB
+ context.wazuh.logger.debug('Getting the total RAM memory');
const ram = Math.ceil(totalmem() / 1024 / 1024);
- log('initialize', `Total RAM: ${ram}MB`, 'info');
+ context.wazuh.logger.info(`Total RAM: ${ram}MB`);
} catch (error) {
- log(
- 'initialize',
- `Could not check total RAM due to: ${error.message || error}`,
+ context.wazuh.logger.error(
+ `Could not check total RAM due to: ${error.message}`,
);
}
@@ -75,7 +48,6 @@ export function jobInitializeRun(context) {
const saveConfiguration = async (hosts = {}) => {
try {
const commonDate = new Date().toISOString();
-
const configuration = {
name: PLUGIN_APP_NAME,
'app-version': packageJSON.version,
@@ -84,35 +56,24 @@ export function jobInitializeRun(context) {
lastRestart: commonDate,
hosts,
};
- try {
- createDataDirectoryIfNotExists();
- createDataDirectoryIfNotExists('config');
- log(
- 'initialize:saveConfiguration',
- `Saving configuration in registry file: ${JSON.stringify(
- configuration,
- )}`,
- 'debug',
- );
- await fs.writeFileSync(
- WAZUH_DATA_CONFIG_REGISTRY_PATH,
- JSON.stringify(configuration),
- 'utf8',
- );
- log(
- 'initialize:saveConfiguration',
- 'Wazuh configuration registry saved.',
- 'debug',
- );
- } catch (error) {
- log('initialize:saveConfiguration', error.message || error);
- context.wazuh.logger.error(
- 'Could not create Wazuh configuration registry',
- );
- }
+ context.wazuh.logger.debug('Saving the configuration');
+ createDataDirectoryIfNotExists();
+ createDataDirectoryIfNotExists('config');
+ context.wazuh.logger.debug(
+ `Saving configuration in registry file: ${JSON.stringify(
+ configuration,
+ )}`,
+ );
+ await fs.writeFileSync(
+ WAZUH_DATA_CONFIG_REGISTRY_PATH,
+ JSON.stringify(configuration),
+ 'utf8',
+ );
+ context.wazuh.logger.info('Configuration registry saved.');
} catch (error) {
- log('initialize:saveConfiguration', error.message || error);
- context.wazuh.logger.error('Error creating wazuh-registry.json file.');
+ context.wazuh.logger.error(
+ `Error creating the registry file: ${error.message}`,
+ );
}
};
@@ -123,11 +84,7 @@ export function jobInitializeRun(context) {
* - no: create the file with empty hosts
*/
const checkWazuhRegistry = async () => {
- log(
- 'initialize:checkwazuhRegistry',
- 'Checking wazuh-registry.json file.',
- 'debug',
- );
+ context.wazuh.logger.debug('Checking the existence app data directory.');
if (!fs.existsSync(WAZUH_DATA_PLUGIN_PLATFORM_BASE_ABSOLUTE_PATH)) {
throw new Error(
@@ -135,20 +92,22 @@ export function jobInitializeRun(context) {
);
}
+ context.wazuh.logger.debug('Checking the existence of registry file.');
+
if (!fs.existsSync(WAZUH_DATA_CONFIG_REGISTRY_PATH)) {
- log(
- 'initialize:checkwazuhRegistry',
- 'wazuh-registry.json file does not exist. Initializing configuration.',
- 'debug',
+ context.wazuh.logger.debug(
+ 'Registry file does not exist. Initializing configuration.',
);
// Create the app registry file for the very first time
await saveConfiguration();
} else {
+ context.wazuh.logger.debug('Reading the registry file');
// If this function fails, it throws an exception
const source = JSON.parse(
fs.readFileSync(WAZUH_DATA_CONFIG_REGISTRY_PATH, 'utf8'),
);
+ context.wazuh.logger.debug('The registry file was read');
// Check if the stored revision differs from the package.json revision
const isUpgradedApp =
@@ -157,11 +116,13 @@ export function jobInitializeRun(context) {
// Rebuild the registry file if revision or version fields are differents
if (isUpgradedApp) {
- // Generate the hosts data
+ context.wazuh.logger.info(
+ 'App revision or version changed, regenerating registry file',
+ );
+ // Generate the hosts data.
const registryHostsData = Object.entries(source.hosts).reduce(
(accum, [hostID, hostData]) => {
- // We have removed the 'extensions' property from the host as module
- // logic has been eliminated, so this is a migration process.
+ // Migration: Remove the extensions property of the hosts data.
if (hostData.extensions) {
delete hostData.extensions;
}
@@ -171,21 +132,10 @@ export function jobInitializeRun(context) {
{},
);
- log(
- 'initialize:checkwazuhRegistry',
- 'Wazuh app revision or version changed, regenerating wazuh-registry.json.',
- 'info',
- );
-
- // Rebuild the registry file with the migrated host data (extensions are
- // migrated to these supported by the installed plugin).
+ // Rebuild the registry file with the migrated host data
await saveConfiguration(registryHostsData);
- log(
- 'initialize:checkwazuhRegistry',
- 'Migrated the registry file.',
- 'info',
- );
+ context.wazuh.logger.info('Migrated the registry file.');
}
}
};
@@ -196,17 +146,14 @@ export function jobInitializeRun(context) {
};
const createKibanaTemplate = () => {
- log(
- 'initialize:createKibanaTemplate',
+ context.wazuh.logger.debug(
`Creating template for ${PLUGIN_PLATFORM_INDEX}`,
- 'debug',
);
try {
pluginPlatformTemplate.template = PLUGIN_PLATFORM_INDEX + '*';
} catch (error) {
- log('initialize:createKibanaTemplate', error.message || error);
- context.wazuh.logger.error('Exception: ' + error.message || error);
+ context.wazuh.logger.error('Exception: ' + error.message);
}
return context.core.opensearch.client.asInternalUser.indices.putTemplate({
@@ -219,64 +166,46 @@ export function jobInitializeRun(context) {
const createEmptyKibanaIndex = async () => {
try {
- log(
- 'initialize:createEmptyKibanaIndex',
- `Creating ${PLUGIN_PLATFORM_INDEX} index.`,
- 'info',
- );
+ context.wazuh.logger.debug(`Creating ${PLUGIN_PLATFORM_INDEX} index.`);
await context.core.opensearch.client.asInternalUser.indices.create({
index: PLUGIN_PLATFORM_INDEX,
});
- log(
- 'initialize:createEmptyKibanaIndex',
- `Successfully created ${PLUGIN_PLATFORM_INDEX} index.`,
- 'debug',
- );
+ context.wazuh.logger.info(`${PLUGIN_PLATFORM_INDEX} index created`);
await init();
} catch (error) {
- return Promise.reject(
- new Error(
- `Error creating ${PLUGIN_PLATFORM_INDEX} index due to ${
- error.message || error
- }`,
- ),
+ throw new Error(
+ `Error creating ${PLUGIN_PLATFORM_INDEX} index: ${error.message}`,
);
}
};
const fixKibanaTemplate = async () => {
try {
+ context.wazuh.logger.debug(`Fixing ${PLUGIN_PLATFORM_INDEX} template`);
await createKibanaTemplate();
- log(
- 'initialize:fixKibanaTemplate',
- `Successfully created ${PLUGIN_PLATFORM_INDEX} template.`,
- 'debug',
- );
+ context.wazuh.logger.info(`${PLUGIN_PLATFORM_INDEX} template created`);
await createEmptyKibanaIndex();
} catch (error) {
- return Promise.reject(
- new Error(
- `Error creating template for ${PLUGIN_PLATFORM_INDEX} due to ${
- error.message || error
- }`,
- ),
+ throw new Error(
+ `Error creating template for ${PLUGIN_PLATFORM_INDEX}: ${error.message}`,
);
}
};
const getTemplateByName = async () => {
try {
+ context.wazuh.logger.debug(
+ `Getting ${WAZUH_PLUGIN_PLATFORM_TEMPLATE_NAME} template`,
+ );
await context.core.opensearch.client.asInternalUser.indices.getTemplate({
name: WAZUH_PLUGIN_PLATFORM_TEMPLATE_NAME,
});
- log(
- 'initialize:getTemplateByName',
+ context.wazuh.logger.debug(
`No need to create the ${PLUGIN_PLATFORM_INDEX} template, already exists.`,
- 'debug',
);
await createEmptyKibanaIndex();
} catch (error) {
- log('initialize:getTemplateByName', error.message || error);
+ context.wazuh.logger.warn(error.message || error);
return fixKibanaTemplate();
}
};
@@ -284,24 +213,26 @@ export function jobInitializeRun(context) {
// Does Kibana index exist?
const checkKibanaStatus = async () => {
try {
+ context.wazuh.logger.debug(
+ `Checking the existence of ${PLUGIN_PLATFORM_INDEX} index`,
+ );
const response =
await context.core.opensearch.client.asInternalUser.indices.exists({
index: PLUGIN_PLATFORM_INDEX,
});
if (response.body) {
+ context.wazuh.logger.debug(`${PLUGIN_PLATFORM_INDEX} index exist`);
// It exists, initialize!
await init();
} else {
- // No Kibana index created...
- log(
- 'initialize:checkKibanaStatus',
- `Not found ${PLUGIN_PLATFORM_INDEX} index`,
- 'info',
+ context.wazuh.logger.debug(
+ `${PLUGIN_PLATFORM_INDEX} index does not exist`,
);
+ // No Kibana index created...
+ context.wazuh.logger.info(`${PLUGIN_PLATFORM_INDEX} index not found`);
await getTemplateByName();
}
} catch (error) {
- log('initialize:checkKibanaStatus', error.message || error);
context.wazuh.logger.error(error.message || error);
}
};
@@ -313,10 +244,8 @@ export function jobInitializeRun(context) {
// await server.plugins.opensearch.waitUntilReady();
return await checkKibanaStatus();
} catch (error) {
- log(
- 'initialize:checkStatus',
+ context.wazuh.logger.debug(
'Waiting for opensearch plugin to be ready...',
- 'debug',
);
setTimeout(() => checkStatus(), 3000);
}
diff --git a/plugins/main/server/start/migration-tasks/index.ts b/plugins/main/server/start/migration-tasks/index.ts
index 025751c0cc..82ecf2f19c 100644
--- a/plugins/main/server/start/migration-tasks/index.ts
+++ b/plugins/main/server/start/migration-tasks/index.ts
@@ -1,9 +1,8 @@
-import migrateReportsDirectoryName from "./reports_directory_name";
+import migrateReportsDirectoryName from './reports_directory_name';
export function jobMigrationTasksRun(context) {
- const migrationTasks = [
- migrateReportsDirectoryName
- ];
+ context.wazuh.logger.debug('Migration tasks started');
+ const migrationTasks = [migrateReportsDirectoryName];
migrationTasks.forEach(task => task(context));
-}
\ No newline at end of file
+}
diff --git a/plugins/main/server/start/migration-tasks/reports_directory_name.ts b/plugins/main/server/start/migration-tasks/reports_directory_name.ts
index df81b8851e..288f8524f2 100644
--- a/plugins/main/server/start/migration-tasks/reports_directory_name.ts
+++ b/plugins/main/server/start/migration-tasks/reports_directory_name.ts
@@ -2,18 +2,15 @@ import fs from 'fs';
import md5 from 'md5';
import path from 'path';
import { WAZUH_DATA_DOWNLOADS_REPORTS_DIRECTORY_PATH } from '../../../common/constants';
-import { log } from '../../lib/logger';
/**
* This task renames the report user folder from username to hashed username.
- * @param context
- * @returns
+ * @param context
+ * @returns
*/
export default function migrateReportsDirectoryName(context) {
-
// Create a wrapper function that logs to plugin files and platform logging system
- const createLog = (level: string) => (message) => {
- log('migration:reportsDirectoryName', message, level);
+ const createLog = (level: string) => message => {
context.wazuh.logger[level](`migration:reportsDirectoryName: ${message}`);
};
@@ -26,38 +23,55 @@ export default function migrateReportsDirectoryName(context) {
};
try {
- logger.debug('Task started');
+ logger.debug('Task started: Migrate reports directory name');
// Skip the task if the directory that stores the reports files doesn't exist in the file system
if (!fs.existsSync(WAZUH_DATA_DOWNLOADS_REPORTS_DIRECTORY_PATH)) {
- logger.debug("Reports directory doesn't exist. The task is not required. Skip.");
+ logger.debug(
+ "Reports directory doesn't exist. The task is not required. Skip.",
+ );
return;
- };
+ }
// Read the directories/files in the reports path
- logger.debug(`Reading reports directory: ${WAZUH_DATA_DOWNLOADS_REPORTS_DIRECTORY_PATH}`);
- fs.readdirSync(WAZUH_DATA_DOWNLOADS_REPORTS_DIRECTORY_PATH, { withFileTypes: true })
- .forEach((fileDirent) => {
- // If it is a directory and has not a valid MD5 hash, continue the task.
- if (fileDirent.isDirectory() && !isMD5(fileDirent.name)) {
- // Generate the origin and target path and hash the name
- const originDirectoryPath = path.join(WAZUH_DATA_DOWNLOADS_REPORTS_DIRECTORY_PATH, fileDirent.name);
- const targetDirectoryName = md5(fileDirent.name);
- const targetDirectoryPath = path.join(WAZUH_DATA_DOWNLOADS_REPORTS_DIRECTORY_PATH, targetDirectoryName);
- try {
- logger.info(`Found reports directory to migrate: [${fileDirent.name}]`);
- // Rename the directory from origin to target path
- fs.renameSync(originDirectoryPath, targetDirectoryPath);
- logger.info(`Renamed directory [${fileDirent.name} (${originDirectoryPath})] to [${targetDirectoryName} (${targetDirectoryPath})]`);
- } catch (error) {
- logger.error(`Error renaming directory [${fileDirent.name} (${originDirectoryPath})] to [${targetDirectoryName} (${targetDirectoryPath})]: ${error.message}`);
- }
- };
- });
- logger.debug('Task finished');
+ logger.debug(
+ `Reading reports directory: ${WAZUH_DATA_DOWNLOADS_REPORTS_DIRECTORY_PATH}`,
+ );
+ fs.readdirSync(WAZUH_DATA_DOWNLOADS_REPORTS_DIRECTORY_PATH, {
+ withFileTypes: true,
+ }).forEach(fileDirent => {
+ // If it is a directory and has not a valid MD5 hash, continue the task.
+ if (fileDirent.isDirectory() && !isMD5(fileDirent.name)) {
+ // Generate the origin and target path and hash the name
+ const originDirectoryPath = path.join(
+ WAZUH_DATA_DOWNLOADS_REPORTS_DIRECTORY_PATH,
+ fileDirent.name,
+ );
+ const targetDirectoryName = md5(fileDirent.name);
+ const targetDirectoryPath = path.join(
+ WAZUH_DATA_DOWNLOADS_REPORTS_DIRECTORY_PATH,
+ targetDirectoryName,
+ );
+ try {
+ logger.info(
+ `Found reports directory to migrate: [${fileDirent.name}]`,
+ );
+ // Rename the directory from origin to target path
+ fs.renameSync(originDirectoryPath, targetDirectoryPath);
+ logger.info(
+ `Renamed directory [${fileDirent.name} (${originDirectoryPath})] to [${targetDirectoryName} (${targetDirectoryPath})]`,
+ );
+ } catch (error) {
+ logger.error(
+ `Error renaming directory [${fileDirent.name} (${originDirectoryPath})] to [${targetDirectoryName} (${targetDirectoryPath})]: ${error.message}`,
+ );
+ }
+ }
+ });
+ logger.debug('Task finished: Migrate reports directory name');
} catch (error) {
logger.error(`Error: ${error.message}`);
- };
+ }
}
// Check that the text is a valid MD5 hash
@@ -65,4 +79,4 @@ export default function migrateReportsDirectoryName(context) {
export function isMD5(text: string) {
const regexMD5 = /^[a-f0-9]{32}$/gi;
return regexMD5.test(text);
-}
\ No newline at end of file
+}
diff --git a/plugins/main/server/start/monitoring/index.ts b/plugins/main/server/start/monitoring/index.ts
index c17e844897..f6593f418c 100644
--- a/plugins/main/server/start/monitoring/index.ts
+++ b/plugins/main/server/start/monitoring/index.ts
@@ -10,7 +10,6 @@
* Find more information about this on the LICENSE file.
*/
import cron from 'node-cron';
-import { log } from '../../lib/logger';
import { monitoringTemplate } from '../../integration-files/monitoring-template';
import { getConfiguration } from '../../lib/get-configuration';
import { parseCron } from '../../lib/parse-cron';
@@ -18,17 +17,21 @@ import { indexDate } from '../../lib/index-date';
import { buildIndexSettings } from '../../lib/build-index-settings';
import { WazuhHostsCtrl } from '../../controllers/wazuh-hosts';
import {
+ PLUGIN_PLATFORM_NAME,
WAZUH_MONITORING_TEMPLATE_NAME,
} from '../../../common/constants';
import { tryCatchForIndexPermissionError } from '../tryCatchForIndexPermissionError';
import { delayAsPromise } from '../../../common/utils';
import { getSettingDefaultValue } from '../../../common/services/settings';
-const blueWazuh = '\u001b[34mwazuh\u001b[39m';
-const monitoringErrorLogColors = [blueWazuh, 'monitoring', 'error'];
const wazuhHostController = new WazuhHostsCtrl();
-let MONITORING_ENABLED, MONITORING_FREQUENCY, MONITORING_CRON_FREQ, MONITORING_CREATION, MONITORING_INDEX_PATTERN, MONITORING_INDEX_PREFIX;
+let MONITORING_ENABLED,
+ MONITORING_FREQUENCY,
+ MONITORING_CRON_FREQ,
+ MONITORING_CREATION,
+ MONITORING_INDEX_PATTERN,
+ MONITORING_INDEX_PREFIX;
// Utils functions
/**
@@ -37,9 +40,15 @@ let MONITORING_ENABLED, MONITORING_FREQUENCY, MONITORING_CRON_FREQ, MONITORING_C
* @param configuration
* @param defaultValue
*/
-function getAppConfigurationSetting(setting: string, configuration: any, defaultValue: any) {
- return typeof configuration[setting] !== 'undefined' ? configuration[setting] : defaultValue;
-};
+function getAppConfigurationSetting(
+ setting: string,
+ configuration: any,
+ defaultValue: any,
+) {
+ return typeof configuration[setting] !== 'undefined'
+ ? configuration[setting]
+ : defaultValue;
+}
/**
* Set the monitoring variables
@@ -47,48 +56,59 @@ function getAppConfigurationSetting(setting: string, configuration: any, default
*/
function initMonitoringConfiguration(context) {
try {
+ context.wazuh.logger.debug('Reading configuration');
const appConfig = getConfiguration();
- MONITORING_ENABLED = appConfig && typeof appConfig['wazuh.monitoring.enabled'] !== 'undefined'
- ? appConfig['wazuh.monitoring.enabled'] &&
- appConfig['wazuh.monitoring.enabled'] !== 'worker'
- : getSettingDefaultValue('wazuh.monitoring.enabled');
- MONITORING_FREQUENCY = getAppConfigurationSetting('wazuh.monitoring.frequency', appConfig, getSettingDefaultValue('wazuh.monitoring.frequency'));
+ MONITORING_ENABLED =
+ appConfig && typeof appConfig['wazuh.monitoring.enabled'] !== 'undefined'
+ ? appConfig['wazuh.monitoring.enabled'] &&
+ appConfig['wazuh.monitoring.enabled'] !== 'worker'
+ : getSettingDefaultValue('wazuh.monitoring.enabled');
+ MONITORING_FREQUENCY = getAppConfigurationSetting(
+ 'wazuh.monitoring.frequency',
+ appConfig,
+ getSettingDefaultValue('wazuh.monitoring.frequency'),
+ );
MONITORING_CRON_FREQ = parseCron(MONITORING_FREQUENCY);
- MONITORING_CREATION = getAppConfigurationSetting('wazuh.monitoring.creation', appConfig, getSettingDefaultValue('wazuh.monitoring.creation'));
+ MONITORING_CREATION = getAppConfigurationSetting(
+ 'wazuh.monitoring.creation',
+ appConfig,
+ getSettingDefaultValue('wazuh.monitoring.creation'),
+ );
- MONITORING_INDEX_PATTERN = getAppConfigurationSetting('wazuh.monitoring.pattern', appConfig, getSettingDefaultValue('wazuh.monitoring.pattern'));
- const lastCharIndexPattern = MONITORING_INDEX_PATTERN[MONITORING_INDEX_PATTERN.length - 1];
+ MONITORING_INDEX_PATTERN = getAppConfigurationSetting(
+ 'wazuh.monitoring.pattern',
+ appConfig,
+ getSettingDefaultValue('wazuh.monitoring.pattern'),
+ );
+ const lastCharIndexPattern =
+ MONITORING_INDEX_PATTERN[MONITORING_INDEX_PATTERN.length - 1];
if (lastCharIndexPattern !== '*') {
MONITORING_INDEX_PATTERN += '*';
- };
- MONITORING_INDEX_PREFIX = MONITORING_INDEX_PATTERN.slice(0, MONITORING_INDEX_PATTERN.length - 1);
+ }
+ MONITORING_INDEX_PREFIX = MONITORING_INDEX_PATTERN.slice(
+ 0,
+ MONITORING_INDEX_PATTERN.length - 1,
+ );
- log(
- 'monitoring:initMonitoringConfiguration',
+ context.wazuh.logger.debug(
`wazuh.monitoring.enabled: ${MONITORING_ENABLED}`,
- 'debug'
);
- log(
- 'monitoring:initMonitoringConfiguration',
+ context.wazuh.logger.debug(
`wazuh.monitoring.frequency: ${MONITORING_FREQUENCY} (${MONITORING_CRON_FREQ})`,
- 'debug'
);
- log(
- 'monitoring:initMonitoringConfiguration',
+ context.wazuh.logger.debug(
+ `wazuh.monitoring.creation: ${MONITORING_CREATION}`,
+ );
+
+ context.wazuh.logger.debug(
`wazuh.monitoring.pattern: ${MONITORING_INDEX_PATTERN} (index prefix: ${MONITORING_INDEX_PREFIX})`,
- 'debug'
);
} catch (error) {
- const errorMessage = error.message || error;
- log(
- 'monitoring:initMonitoringConfiguration',
- errorMessage
- );
- context.wazuh.logger.error(errorMessage)
+ context.wazuh.logger.error(error.message);
}
-};
+}
/**
* Main. First execution when installing / loading App.
@@ -98,10 +118,9 @@ async function init(context) {
try {
if (MONITORING_ENABLED) {
await checkTemplate(context);
- };
+ }
} catch (error) {
const errorMessage = error.message || error;
- log('monitoring:init', error.message || error);
context.wazuh.logger.error(errorMessage);
}
}
@@ -111,46 +130,48 @@ async function init(context) {
*/
async function checkTemplate(context) {
try {
- log(
- 'monitoring:checkTemplate',
- 'Updating the monitoring template',
- 'debug'
- );
-
try {
+ context.wazuh.logger.debug(
+ `Getting the ${WAZUH_MONITORING_TEMPLATE_NAME} template`,
+ );
// Check if the template already exists
- const currentTemplate = await context.core.opensearch.client.asInternalUser.indices.getTemplate({
- name: WAZUH_MONITORING_TEMPLATE_NAME
- });
+ const currentTemplate =
+ await context.core.opensearch.client.asInternalUser.indices.getTemplate(
+ {
+ name: WAZUH_MONITORING_TEMPLATE_NAME,
+ },
+ );
// Copy already created index patterns
- monitoringTemplate.index_patterns = currentTemplate.body[WAZUH_MONITORING_TEMPLATE_NAME].index_patterns;
+ monitoringTemplate.index_patterns =
+ currentTemplate.body[WAZUH_MONITORING_TEMPLATE_NAME].index_patterns;
} catch (error) {
// Init with the default index pattern
- monitoringTemplate.index_patterns = [getSettingDefaultValue('wazuh.monitoring.pattern')];
+ monitoringTemplate.index_patterns = [
+ getSettingDefaultValue('wazuh.monitoring.pattern'),
+ ];
}
// Check if the user is using a custom pattern and add it to the template if it does
if (!monitoringTemplate.index_patterns.includes(MONITORING_INDEX_PATTERN)) {
monitoringTemplate.index_patterns.push(MONITORING_INDEX_PATTERN);
- };
+ }
// Update the monitoring template
+ context.wazuh.logger.debug(
+ `Updating the ${WAZUH_MONITORING_TEMPLATE_NAME} template`,
+ );
await context.core.opensearch.client.asInternalUser.indices.putTemplate({
name: WAZUH_MONITORING_TEMPLATE_NAME,
- body: monitoringTemplate
+ body: monitoringTemplate,
});
- log(
- 'monitoring:checkTemplate',
- 'Updated the monitoring template',
- 'debug'
+ context.wazuh.logger.info(
+ `Updated the ${WAZUH_MONITORING_TEMPLATE_NAME} template`,
);
} catch (error) {
- const errorMessage = `Something went wrong updating the monitoring template ${error.message || error}`;
- log(
- 'monitoring:checkTemplate',
- errorMessage
- );
- context.wazuh.logger.error(monitoringErrorLogColors, errorMessage);
+ const errorMessage = `Something went wrong updating the ${WAZUH_MONITORING_TEMPLATE_NAME} template ${
+ error.message || error
+ }`;
+ context.wazuh.logger.error(errorMessage);
throw error;
}
}
@@ -161,39 +182,57 @@ async function checkTemplate(context) {
* @param {*} data
*/
async function insertMonitoringDataElasticsearch(context, data) {
- const monitoringIndexName = MONITORING_INDEX_PREFIX + indexDate(MONITORING_CREATION);
+ const monitoringIndexName =
+ MONITORING_INDEX_PREFIX + indexDate(MONITORING_CREATION);
if (!MONITORING_ENABLED) {
return;
- };
+ }
try {
await tryCatchForIndexPermissionError(monitoringIndexName)(async () => {
- const exists = await context.core.opensearch.client.asInternalUser.indices.exists({ index: monitoringIndexName });
+ context.wazuh.logger.debug(
+ `Checking the existence of ${monitoringIndexName} index`,
+ );
+ const exists =
+ await context.core.opensearch.client.asInternalUser.indices.exists({
+ index: monitoringIndexName,
+ });
if (!exists.body) {
+ context.wazuh.logger.debug(
+ `The ${monitoringIndexName} index does not exist`,
+ );
await createIndex(context, monitoringIndexName);
- };
+ } else {
+ context.wazuh.logger.debug(`The ${monitoringIndexName} index exists`);
+ }
// Update the index configuration
const appConfig = getConfiguration();
const indexConfiguration = buildIndexSettings(
appConfig,
'wazuh.monitoring',
- getSettingDefaultValue('wazuh.monitoring.shards')
+ getSettingDefaultValue('wazuh.monitoring.shards'),
);
// To update the index settings with this client is required close the index, update the settings and open it
// Number of shards is not dynamic so delete that setting if it's given
delete indexConfiguration.settings.index.number_of_shards;
+ context.wazuh.logger.debug(
+ `Adding settings to ${monitoringIndexName} index`,
+ );
await context.core.opensearch.client.asInternalUser.indices.putSettings({
index: monitoringIndexName,
- body: indexConfiguration
+ body: indexConfiguration,
});
+ context.wazuh.logger.info(
+ `Settings added to ${monitoringIndexName} index`,
+ );
+
// Insert data to the monitoring index
await insertDataToIndex(context, monitoringIndexName, data);
})();
} catch (error) {
- log('monitoring:insertMonitoringDataElasticsearch', error.message || error);
- context.wazuh.logger.error(error.message);
+ context.wazuh.logger.error(error.message || error);
}
}
@@ -203,39 +242,45 @@ async function insertMonitoringDataElasticsearch(context, data) {
* @param {String} indexName The name for the index (e.g. daily: wazuh-monitoring-YYYY.MM.DD)
* @param {*} data
*/
-async function insertDataToIndex(context, indexName: string, data: { agents: any[], apiHost }) {
+async function insertDataToIndex(
+ context,
+ indexName: string,
+ data: { agents: any[]; apiHost },
+) {
const { agents, apiHost } = data;
try {
if (agents.length > 0) {
- log(
- 'monitoring:insertDataToIndex',
+ context.wazuh.logger.debug(
`Bulk data to index ${indexName} for ${agents.length} agents`,
- 'debug'
);
- const bodyBulk = agents.map(agent => {
- const agentInfo = { ...agent };
- agentInfo['timestamp'] = new Date(Date.now()).toISOString();
- agentInfo.host = agent.manager;
- agentInfo.cluster = { name: apiHost.clusterName ? apiHost.clusterName : 'disabled' };
- return `{ "index": { "_index": "${indexName}" } }\n${JSON.stringify(agentInfo)}\n`;
- }).join('');
+ const bodyBulk = agents
+ .map(agent => {
+ const agentInfo = { ...agent };
+ agentInfo['timestamp'] = new Date(Date.now()).toISOString();
+ agentInfo.host = agent.manager;
+ agentInfo.cluster = {
+ name: apiHost.clusterName ? apiHost.clusterName : 'disabled',
+ };
+ return `{ "index": { "_index": "${indexName}" } }\n${JSON.stringify(
+ agentInfo,
+ )}\n`;
+ })
+ .join('');
await context.core.opensearch.client.asInternalUser.bulk({
index: indexName,
- body: bodyBulk
+ body: bodyBulk,
});
- log(
- 'monitoring:insertDataToIndex',
+ context.wazuh.logger.info(
`Bulk data to index ${indexName} for ${agents.length} agents completed`,
- 'debug'
);
}
} catch (error) {
- log(
- 'monitoring:insertDataToIndex',
- `Error inserting agent data into elasticsearch. Bulk request failed due to ${error.message ||
- error}`
+ context.wazuh.logger.error(
+ `Error inserting agent data into elasticsearch. Bulk request failed due to ${
+ error.message || error
+ }`,
);
}
}
@@ -253,67 +298,67 @@ async function createIndex(context, indexName: string) {
const IndexConfiguration = {
settings: {
index: {
- number_of_shards: getAppConfigurationSetting('wazuh.monitoring.shards', appConfig, getSettingDefaultValue('wazuh.monitoring.shards')),
- number_of_replicas: getAppConfigurationSetting('wazuh.monitoring.replicas', appConfig, getSettingDefaultValue('wazuh.monitoring.replicas'))
- }
- }
+ number_of_shards: getAppConfigurationSetting(
+ 'wazuh.monitoring.shards',
+ appConfig,
+ getSettingDefaultValue('wazuh.monitoring.shards'),
+ ),
+ number_of_replicas: getAppConfigurationSetting(
+ 'wazuh.monitoring.replicas',
+ appConfig,
+ getSettingDefaultValue('wazuh.monitoring.replicas'),
+ ),
+ },
+ },
};
+ context.wazuh.logger.debug(`Creating ${indexName} index`);
+
await context.core.opensearch.client.asInternalUser.indices.create({
index: indexName,
- body: IndexConfiguration
+ body: IndexConfiguration,
});
- log(
- 'monitoring:createIndex',
- `Successfully created new index: ${indexName}`,
- 'debug'
- );
+ context.wazuh.logger.info(`${indexName} index created`);
} catch (error) {
- const errorMessage = `Could not create ${indexName} index on elasticsearch due to ${error.message || error}`;
- log(
- 'monitoring:createIndex',
- errorMessage
+ context.wazuh.logger.error(
+ `Could not create ${indexName} index: ${error.message || error}`,
);
- context.wazuh.logger.error(errorMessage);
}
}
/**
-* Wait until Kibana server is ready
-*/
+ * Wait until Kibana server is ready
+ */
async function checkPluginPlatformStatus(context) {
try {
- log(
- 'monitoring:checkPluginPlatformStatus',
- 'Waiting for Kibana and Elasticsearch servers to be ready...',
- 'debug'
+ context.wazuh.logger.debug(
+ `Waiting for ${PLUGIN_PLATFORM_NAME} and Elasticsearch servers to be ready...`, //TODO: rename Elasticsearch (use constant)
);
await checkElasticsearchServer(context);
await init(context);
- return;
} catch (error) {
- log(
- 'monitoring:checkPluginPlatformStatus',
- error.mesage || error
- );
+ context.wazuh.logger.error(error.message || error);
try {
await delayAsPromise(3000);
await checkPluginPlatformStatus(context);
- } catch (error) { };
+ } catch (error) {}
}
}
-
/**
* Check Elasticsearch Server status and Kibana index presence
*/
async function checkElasticsearchServer(context) {
try {
- const data = await context.core.opensearch.client.asInternalUser.indices.exists({
- index: context.server.config.opensearchDashboards.index
- });
+ context.wazuh.logger.debug(
+ `Checking the existence of ${context.server.config.opensearchDashboards.index} index`,
+ );
+ const data =
+ await context.core.opensearch.client.asInternalUser.indices.exists({
+ index: context.server.config.opensearchDashboards.index,
+ });
return data.body;
// TODO: check if Elasticsearch can receive requests
@@ -323,7 +368,7 @@ async function checkElasticsearchServer(context) {
// }
return Promise.reject(data);
} catch (error) {
- log('monitoring:checkElasticsearchServer', error.message || error);
+ context.wazuh.logger.error(error.message || error);
return Promise.reject(error);
}
}
@@ -331,43 +376,46 @@ async function checkElasticsearchServer(context) {
const fakeResponseEndpoint = {
ok: (body: any) => body,
custom: (body: any) => body,
-}
+};
/**
* Get API configuration from elastic and callback to loadCredentials
*/
-async function getHostsConfiguration() {
+async function getHostsConfiguration(context) {
try {
- const hosts = await wazuhHostController.getHostsEntries(false, false, fakeResponseEndpoint);
+ const hosts = await wazuhHostController.getHostsEntries(
+ context, // TODO: research if this needs the context
+ false,
+ fakeResponseEndpoint,
+ );
if (hosts.body.length) {
return hosts.body;
- };
+ }
- log(
- 'monitoring:getConfig',
- 'There are no Wazuh API entries yet',
- 'debug'
- );
+ context.wazuh.logger.debug('There are no API host entries yet');
return Promise.reject({
error: 'no credentials',
- error_code: 1
+ error_code: 1,
});
} catch (error) {
- log('monitoring:getHostsConfiguration', error.message || error);
+ context.wazuh.logger.error(error.message || error);
return Promise.reject({
- error: 'no wazuh hosts',
- error_code: 2
+ error: 'no API hosts',
+ error_code: 2,
});
}
}
/**
- * Task used by the cron job.
- */
+ * Task used by the cron job.
+ */
async function cronTask(context) {
try {
- const templateMonitoring = await context.core.opensearch.client.asInternalUser.indices.getTemplate({ name: WAZUH_MONITORING_TEMPLATE_NAME });
+ const templateMonitoring =
+ await context.core.opensearch.client.asInternalUser.indices.getTemplate({
+ name: WAZUH_MONITORING_TEMPLATE_NAME,
+ });
- const apiHosts = await getHostsConfiguration();
+ const apiHosts = await getHostsConfiguration(context);
const apiHostsUnique = (apiHosts || []).filter(
(apiHost, index, self) =>
index ===
@@ -376,16 +424,17 @@ async function cronTask(context) {
t.user === apiHost.user &&
t.password === apiHost.password &&
t.url === apiHost.url &&
- t.port === apiHost.port
- )
+ t.port === apiHost.port,
+ ),
);
for (let apiHost of apiHostsUnique) {
try {
const { agents, apiHost: host } = await getApiInfo(context, apiHost);
- await insertMonitoringDataElasticsearch(context, { agents, apiHost: host });
- } catch (error) {
-
- };
+ await insertMonitoringDataElasticsearch(context, {
+ agents,
+ apiHost: host,
+ });
+ } catch (error) {}
}
} catch (error) {
// Retry to call itself again if Kibana index is not ready yet
@@ -399,8 +448,6 @@ async function cronTask(context) {
// return cronTask(context);
// }
// } catch (error) {} //eslint-disable-line
-
- log('monitoring:cronTask', error.message || error);
context.wazuh.logger.error(error.message || error);
}
}
@@ -412,20 +459,34 @@ async function cronTask(context) {
*/
async function getApiInfo(context, apiHost) {
try {
- log('monitoring:getApiInfo', `Getting API info for ${apiHost.id}`, 'debug');
- const responseIsCluster = await context.wazuh.api.client.asInternalUser.request('GET', '/cluster/status', {}, { apiHostID: apiHost.id });
- const isCluster = (((responseIsCluster || {}).data || {}).data || {}).enabled === 'yes';
+ context.wazuh.logger.debug(`Getting API info for ${apiHost.id}`);
+ const responseIsCluster =
+ await context.wazuh.api.client.asInternalUser.request(
+ 'GET',
+ '/cluster/status',
+ {},
+ { apiHostID: apiHost.id },
+ );
+ const isCluster =
+ (((responseIsCluster || {}).data || {}).data || {}).enabled === 'yes';
if (isCluster) {
- const responseClusterInfo = await context.wazuh.api.client.asInternalUser.request('GET', `/cluster/local/info`, {}, { apiHostID: apiHost.id });
- apiHost.clusterName = responseClusterInfo.data.data.affected_items[0].cluster;
- };
+ const responseClusterInfo =
+ await context.wazuh.api.client.asInternalUser.request(
+ 'GET',
+ `/cluster/local/info`,
+ {},
+ { apiHostID: apiHost.id },
+ );
+ apiHost.clusterName =
+ responseClusterInfo.data.data.affected_items[0].cluster;
+ }
const agents = await fetchAllAgentsFromApiHost(context, apiHost);
return { agents, apiHost };
} catch (error) {
- log('monitoring:getApiInfo', error.message || error);
+ context.wazuh.logger.error(error.message || error);
throw error;
}
-};
+}
/**
* Fetch all agents for the API provided
@@ -435,25 +496,30 @@ async function getApiInfo(context, apiHost) {
async function fetchAllAgentsFromApiHost(context, apiHost) {
let agents = [];
try {
- log('monitoring:fetchAllAgentsFromApiHost', `Getting all agents from ApiID: ${apiHost.id}`, 'debug');
- const responseAgentsCount = await context.wazuh.api.client.asInternalUser.request(
- 'GET',
- '/agents',
- {
- params: {
- offset: 0,
- limit: 1,
- q: 'id!=000'
- }
- }, { apiHostID: apiHost.id });
+ context.wazuh.logger.debug(`Getting all agents from ApiID: ${apiHost.id}`);
+ const responseAgentsCount =
+ await context.wazuh.api.client.asInternalUser.request(
+ 'GET',
+ '/agents',
+ {
+ params: {
+ offset: 0,
+ limit: 1,
+ q: 'id!=000',
+ },
+ },
+ { apiHostID: apiHost.id },
+ );
const agentsCount = responseAgentsCount.data.data.total_affected_items;
- log('monitoring:fetchAllAgentsFromApiHost', `ApiID: ${apiHost.id}, Agent count: ${agentsCount}`, 'debug');
+ context.wazuh.logger.debug(
+ `ApiID: ${apiHost.id}, Agent count: ${agentsCount}`,
+ );
let payload = {
offset: 0,
limit: 500,
- q: 'id!=000'
+ q: 'id!=000',
};
while (agents.length < agentsCount && payload.offset < agentsCount) {
@@ -472,29 +538,37 @@ async function fetchAllAgentsFromApiHost(context, apiHost) {
- increase the limit of results to retrieve (currently, the requests use the recommended value: 500).
See the allowed values. This depends on the selected data because the response could fail if contains a lot of data
*/
- const responseAgents = await context.wazuh.api.client.asInternalUser.request(
- 'GET',
- `/agents`,
- { params: payload },
- { apiHostID: apiHost.id }
- );
+ const responseAgents =
+ await context.wazuh.api.client.asInternalUser.request(
+ 'GET',
+ `/agents`,
+ { params: payload },
+ { apiHostID: apiHost.id },
+ );
agents = [...agents, ...responseAgents.data.data.affected_items];
payload.offset += payload.limit;
} catch (error) {
- log('monitoring:fetchAllAgentsFromApiHost', `ApiID: ${apiHost.id}, Error request with offset/limit ${payload.offset}/${payload.limit}: ${error.message || error}`);
+ context.wazuh.logger.error(
+ `ApiID: ${apiHost.id}, Error request with offset/limit ${
+ payload.offset
+ }/${payload.limit}: ${error.message || error}`,
+ );
}
}
return agents;
} catch (error) {
- log('monitoring:fetchAllAgentsFromApiHost', `ApiID: ${apiHost.id}. Error: ${error.message || error}`);
+ context.wazuh.logger.error(
+ `ApiID: ${apiHost.id}. Error: ${error.message || error}`,
+ );
throw error;
}
-};
+}
/**
* Start the cron job
*/
export async function jobMonitoringRun(context) {
+ context.wazuh.logger.debug('Task:Monitoring initializing');
// Init the monitoring variables
initMonitoringConfiguration(context);
// Check Kibana index and if it is prepared, start the initialization of Wazuh App.
@@ -505,4 +579,3 @@ export async function jobMonitoringRun(context) {
cron.schedule(MONITORING_CRON_FREQ, () => cronTask(context));
}
}
-
diff --git a/plugins/main/server/start/queue/index.ts b/plugins/main/server/start/queue/index.ts
index 36228872c5..5b1cea949e 100644
--- a/plugins/main/server/start/queue/index.ts
+++ b/plugins/main/server/start/queue/index.ts
@@ -15,64 +15,56 @@ import { WAZUH_QUEUE_CRON_FREQ } from '../../../common/constants';
export let queue = [];
-export interface IQueueJob{
+export interface IQueueJob {
/** Date object to start the job */
- startAt: Date
+ startAt: Date;
/** Function to execute */
- run: () => void
-};
+ run: () => void;
+}
/**
* Add a job to the queue.
* @param job Job to add to queue
*/
-export function addJobToQueue(job: IQueueJob) {
- log('queue:addJob', `New job added`, 'debug');
+export function addJobToQueue(context: any, job: IQueueJob) {
+ context.wazuh.logger.info('New job added');
queue.push(job);
-};
+}
-async function executePendingJobs() {
+async function executePendingJobs(context: any) {
try {
if (!queue || !queue.length) return;
const now: Date = new Date();
const pendingJobs: IQueueJob[] = queue.filter(item => item.startAt <= now);
- log(
- 'queue:executePendingJobs',
- `Pending jobs: ${pendingJobs.length}`,
- 'debug'
- );
- if (!pendingJobs || !pendingJobs.length){
+ context.wazuh.logger.debug(`Pending jobs: ${pendingJobs.length}`);
+ if (!pendingJobs || !pendingJobs.length) {
return;
- };
+ }
queue = queue.filter((item: IQueueJob) => item.startAt > now);
for (const job of pendingJobs) {
try {
- await job.run();
+ await job.run(context);
} catch (error) {
continue;
- };
+ }
}
} catch (error) {
queue = [];
- log('queue:executePendingJobs', error.message || error);
return Promise.reject(error);
}
}
/**
* Run the job queue it plugin start.
- * @param context
+ * @param context
*/
export function jobQueueRun(context) {
- cron.schedule(
- WAZUH_QUEUE_CRON_FREQ,
- async () => {
- try {
- await executePendingJobs();
- } catch (error) {
- log('queue:launchCronJob', error.message || error);
- }
+ cron.schedule(WAZUH_QUEUE_CRON_FREQ, async () => {
+ try {
+ await executePendingJobs(context);
+ } catch (error) {
+ context.wazuh.logger.error(error.message || error);
}
- );
+ });
}
From 70f02f414bfa33bf458f6ec75a9486d1dbca343f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Antonio=20David=20Guti=C3=A9rrez?=
Date: Tue, 21 Nov 2023 12:57:27 +0100
Subject: [PATCH 002/138] feat(logging): minor fixes to logging messages in the
main plugin
---
plugins/main/server/start/cron-scheduler/scheduler-handler.ts | 2 +-
plugins/main/server/start/monitoring/index.ts | 4 +---
2 files changed, 2 insertions(+), 4 deletions(-)
diff --git a/plugins/main/server/start/cron-scheduler/scheduler-handler.ts b/plugins/main/server/start/cron-scheduler/scheduler-handler.ts
index 3f7679dc68..a7f6134a02 100644
--- a/plugins/main/server/start/cron-scheduler/scheduler-handler.ts
+++ b/plugins/main/server/start/cron-scheduler/scheduler-handler.ts
@@ -14,7 +14,7 @@ const schedulerJobs = [];
*/
const checkPluginPlatformStatus = async function (context) {
try {
- context.wazuh.logger.debug('Waiting for servers to be ready...');
+ context.wazuh.logger.debug('Waiting for platform servers to be ready...');
await checkElasticsearchServer(context);
await checkTemplate(context);
diff --git a/plugins/main/server/start/monitoring/index.ts b/plugins/main/server/start/monitoring/index.ts
index f6593f418c..276ea9496e 100644
--- a/plugins/main/server/start/monitoring/index.ts
+++ b/plugins/main/server/start/monitoring/index.ts
@@ -332,9 +332,7 @@ async function createIndex(context, indexName: string) {
*/
async function checkPluginPlatformStatus(context) {
try {
- context.wazuh.logger.debug(
- `Waiting for ${PLUGIN_PLATFORM_NAME} and Elasticsearch servers to be ready...`, //TODO: rename Elasticsearch (use constant)
- );
+ context.wazuh.logger.debug('Waiting for platform servers to be ready...');
await checkElasticsearchServer(context);
await init(context);
From c3ba9d10f46c532ce370d5559941116edbfa2bc3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Antonio=20David=20Guti=C3=A9rrez?=
Date: Tue, 21 Nov 2023 13:12:13 +0100
Subject: [PATCH 003/138] feat(logging): remove custom logger from endpoints of
main plugin
---
plugins/main/server/controllers/wazuh-api.ts | 96 ++++-----
.../main/server/controllers/wazuh-elastic.ts | 185 +++++++----------
.../main/server/controllers/wazuh-hosts.ts | 104 ++++++----
.../server/controllers/wazuh-reporting.ts | 191 +++++++-----------
plugins/main/server/plugin.ts | 127 ++++++++----
5 files changed, 350 insertions(+), 353 deletions(-)
diff --git a/plugins/main/server/controllers/wazuh-api.ts b/plugins/main/server/controllers/wazuh-api.ts
index f9ec4464d4..87153db486 100644
--- a/plugins/main/server/controllers/wazuh-api.ts
+++ b/plugins/main/server/controllers/wazuh-api.ts
@@ -13,7 +13,6 @@
// Require some libraries
import { ErrorResponse } from '../lib/error-response';
import { Parser } from 'json2csv';
-import { log } from '../lib/logger';
import { KeyEquivalence } from '../../common/csv-key-equivalence';
import { ApiErrorEquivalence } from '../lib/api-errors-equivalence';
import apiRequestList from '../../common/api-info/endpoints';
@@ -35,7 +34,6 @@ import {
API_USER_STATUS_RUN_AS,
} from '../lib/cache-api-user-has-run-as';
import { getCookieValueByName } from '../lib/cookie';
-import { SecurityObj } from '../lib/security-factory';
import { getConfiguration } from '../lib/get-configuration';
export class WazuhApiCtrl {
@@ -82,7 +80,9 @@ export class WazuhApiCtrl {
});
}
} catch (error) {
- log('wazuh-api:getToken', error.message || error);
+ context.wazuh.logger.error(
+ `Error decoding the API host entry token: ${error.message}`,
+ );
}
}
}
@@ -116,11 +116,12 @@ export class WazuhApiCtrl {
body: { token },
});
} catch (error) {
- const errorMessage =
- ((error.response || {}).data || {}).detail || error.message || error;
- log('wazuh-api:getToken', errorMessage);
+ const errorMessage = `Error getting the authorization token: ${
+ ((error.response || {}).data || {}).detail || error.message || error
+ }`;
+ context.wazuh.logger.error(errorMessage);
return ErrorResponse(
- `Error getting the authorization token: ${errorMessage}`,
+ errorMessage,
3000,
error?.response?.status || HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,
response,
@@ -143,13 +144,17 @@ export class WazuhApiCtrl {
try {
// Get config from wazuh.yml
const id = request.body.id;
+ context.wazuh.logger.debug(`Getting server API host by ID: ${id}`);
const api = await this.manageHosts.getHostById(id);
+ context.wazuh.logger.debug(
+ `Server API host data: ${JSON.stringify(api)}`,
+ );
// Check Manage Hosts
if (!Object.keys(api).length) {
- throw new Error('Could not find Wazuh API entry on wazuh.yml');
+ throw new Error('Could not find server API entry in the configuration');
}
- log('wazuh-api:checkStoredAPI', `${id} exists`, 'debug');
+ context.wazuh.logger.debug(`${id} exists`);
// Fetch needed information about the cluster and the manager itself
const responseManagerInfo =
@@ -161,7 +166,7 @@ export class WazuhApiCtrl {
);
// Look for socket-related errors
- if (this.checkResponseIsDown(responseManagerInfo)) {
+ if (this.checkResponseIsDown(context, responseManagerInfo)) {
return ErrorResponse(
`ERROR3099 - ${
responseManagerInfo.data.detail || 'Wazuh not ready yet'
@@ -293,7 +298,7 @@ export class WazuhApiCtrl {
{ apiHostID: id },
);
- if (this.checkResponseIsDown(responseManagerInfo)) {
+ if (this.checkResponseIsDown(context, responseManagerInfo)) {
return ErrorResponse(
`ERROR3099 - ${
response.data.detail || 'Wazuh not ready yet'
@@ -311,7 +316,7 @@ export class WazuhApiCtrl {
} catch (error) {} // eslint-disable-line
}
} catch (error) {
- log('wazuh-api:checkStoredAPI', error.message || error);
+ context.wazuh.logger.error(error.message || error);
return ErrorResponse(
error.message || error,
3020,
@@ -319,7 +324,7 @@ export class WazuhApiCtrl {
response,
);
}
- log('wazuh-api:checkStoredAPI', error.message || error);
+ context.wazuh.logger.error(error.message || error);
return ErrorResponse(
error.message || error,
3002,
@@ -374,15 +379,16 @@ export class WazuhApiCtrl {
let apiAvailable = null;
// const notValid = this.validateCheckApiParams(request.body);
// if (notValid) return ErrorResponse(notValid, 3003, HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR, response);
- log('wazuh-api:checkAPI', `${request.body.id} is valid`, 'debug');
+ context.wazuh.logger.debug(`${request.body.id} is valid`);
// Check if a Wazuh API id is given (already stored API)
const data = await this.manageHosts.getHostById(request.body.id);
if (data) {
apiAvailable = data;
} else {
- log('wazuh-api:checkAPI', `API ${request.body.id} not found`);
+ const errorMessage = `The server API host entry with ID ${request.body.id} was not found`;
+ context.wazuh.logger.debug(errorMessage);
return ErrorResponse(
- `The API ${request.body.id} was not found`,
+ errorMessage,
3029,
HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,
response,
@@ -411,12 +417,7 @@ export class WazuhApiCtrl {
response,
);
}
-
- log(
- 'wazuh-api:checkAPI',
- `${request.body.id} credentials are valid`,
- 'debug',
- );
+ context.wazuh.logger.debug(`${request.body.id} credentials are valid`);
if (
responseManagerInfo.status === HTTP_STATUS_CODES.OK &&
responseManagerInfo.data
@@ -475,11 +476,7 @@ export class WazuhApiCtrl {
);
if (responseCluster.status === HTTP_STATUS_CODES.OK) {
- log(
- 'wazuh-api:checkStoredAPI',
- `Wazuh API response is valid`,
- 'debug',
- );
+ context.wazuh.logger.debug('Wazuh API response is valid');
if (responseCluster.data.data.enabled === 'yes') {
// If cluster mode is active
let responseClusterLocal =
@@ -517,7 +514,7 @@ export class WazuhApiCtrl {
}
}
} catch (error) {
- log('wazuh-api:checkAPI', error.message || error);
+ context.wazuh.logger.warn(error.message || error);
if (
error &&
@@ -561,7 +558,7 @@ export class WazuhApiCtrl {
}
}
- checkResponseIsDown(response) {
+ checkResponseIsDown(context, response) {
if (response.status !== HTTP_STATUS_CODES.OK) {
// Avoid "Error communicating with socket" like errors
const socketErrorCodes = [1013, 1014, 1017, 1018, 1019];
@@ -569,8 +566,7 @@ export class WazuhApiCtrl {
const isDown = socketErrorCodes.includes(status);
isDown &&
- log(
- 'wazuh-api:makeRequest',
+ context.wazuh.logger.error(
'Wazuh API is online but Wazuh is not ready yet',
);
@@ -612,7 +608,7 @@ export class WazuhApiCtrl {
const isValid = execd && modulesd && wazuhdb && clusterd;
- isValid && log('wazuh-api:checkDaemons', `Wazuh is ready`, 'debug');
+ isValid && context.wazuh.logger.debug('Wazuh is ready');
if (path === '/ping') {
return { isValid };
@@ -622,7 +618,7 @@ export class WazuhApiCtrl {
throw new Error('Wazuh not ready yet');
}
} catch (error) {
- log('wazuh-api:checkDaemons', error.message || error);
+ context.wazuh.logger.error(error.message || error);
return Promise.reject(error);
}
}
@@ -673,7 +669,7 @@ export class WazuhApiCtrl {
}
if (!Object.keys(api).length) {
- log('wazuh-api:makeRequest', 'Could not get host credentials');
+ context.wazuh.logger.error('Could not get host credentials');
//Can not get credentials from wazuh-hosts
return ErrorResponse(
'Could not get host credentials',
@@ -732,8 +728,7 @@ export class WazuhApiCtrl {
options,
);
} catch (error) {
- log(
- 'queue:delayApiRequest',
+ contextJob.wazuh.logger.error(
`An error ocurred in the delayed request: "${method} ${path}": ${
error.message || error
}`,
@@ -753,8 +748,7 @@ export class WazuhApiCtrl {
} catch (error) {
const isDown = (error || {}).code === 'ECONNREFUSED';
if (!isDown) {
- log(
- 'wazuh-api:makeRequest',
+ context.wazuh.logger.error(
'Wazuh API is online but Wazuh is not ready yet',
);
return ErrorResponse(
@@ -767,7 +761,7 @@ export class WazuhApiCtrl {
}
}
- log('wazuh-api:makeRequest', `${method} ${path}`, 'debug');
+ context.wazuh.logger.debug(`${method} ${path}`);
// Extract keys from parameters
const dataProperties = Object.keys(data);
@@ -790,7 +784,7 @@ export class WazuhApiCtrl {
data,
options,
);
- const responseIsDown = this.checkResponseIsDown(responseToken);
+ const responseIsDown = this.checkResponseIsDown(context, responseToken);
if (responseIsDown) {
return ErrorResponse(
`ERROR3099 - ${response.body.message || 'Wazuh not ready yet'}`,
@@ -841,7 +835,7 @@ export class WazuhApiCtrl {
);
}
const errorMsg = (error.response || {}).data || error.message;
- log('wazuh-api:makeRequest', errorMsg || error);
+ context.wazuh.logger.error(errorMsg || error);
if (devTools) {
return response.ok({
body: { error: '3013', message: errorMsg || error },
@@ -890,7 +884,7 @@ export class WazuhApiCtrl {
response,
);
} else if (!request.body.method.match(/^(?:GET|PUT|POST|DELETE)$/)) {
- log('wazuh-api:makeRequest', 'Request method is not valid.');
+ context.wazuh.logger.error('Request method is not valid.');
//Method is not a valid HTTP request method
return ErrorResponse(
'Request method is not valid.',
@@ -906,7 +900,7 @@ export class WazuhApiCtrl {
response,
);
} else if (!request.body.path.startsWith('/')) {
- log('wazuh-api:makeRequest', 'Request path is not valid.');
+ context.wazuh.logger.error('Request path is not valid.');
//Path doesn't start with '/'
return ErrorResponse(
'Request path is not valid.',
@@ -955,7 +949,7 @@ export class WazuhApiCtrl {
if (!tmpPath) throw new Error('An error occurred parsing path field');
- log('wazuh-api:csv', `Report ${tmpPath}`, 'debug');
+ context.wazuh.logger.debug(`Report ${tmpPath}`);
// Real limit, regardless the user query
const params = { limit: 500 };
@@ -1088,7 +1082,7 @@ export class WazuhApiCtrl {
);
}
} catch (error) {
- log('wazuh-api:csv', error.message || error);
+ context.wazuh.logger.error(error.message || error);
return ErrorResponse(
error.message || error,
3034,
@@ -1127,10 +1121,8 @@ export class WazuhApiCtrl {
fs.readFileSync(this.updateRegistry.file, 'utf8'),
);
if (source.installationDate && source.lastRestart) {
- log(
- 'wazuh-api:getTimeStamp',
+ context.wazuh.logger.debug(
`Installation date: ${source.installationDate}. Last restart: ${source.lastRestart}`,
- 'debug',
);
return response.ok({
body: {
@@ -1142,7 +1134,7 @@ export class WazuhApiCtrl {
throw new Error('Could not fetch wazuh-version registry');
}
} catch (error) {
- log('wazuh-api:getTimeStamp', error.message || error);
+ context.wazuh.logger.error(error.message || error);
return ErrorResponse(
error.message || 'Could not fetch wazuh-version registry',
4001,
@@ -1175,7 +1167,7 @@ export class WazuhApiCtrl {
},
});
} catch (error) {
- log('wazuh-api:getSetupInfo', error.message || error);
+ context.wazuh.logger.error(error.message || error);
return ErrorResponse(
`Could not get data from wazuh-version registry due to ${
error.message || error
@@ -1242,7 +1234,7 @@ export class WazuhApiCtrl {
body: syscollector,
});
} catch (error) {
- log('wazuh-api:getSyscollector', error.message || error);
+ context.wazuh.logger.error(error.message || error);
return ErrorResponse(
error.message || error,
3035,
@@ -1280,7 +1272,7 @@ export class WazuhApiCtrl {
body: { logos },
});
} catch (error) {
- log('wazuh-api:getAppLogos', error.message || error);
+ context.wazuh.logger.error(error.message || error);
return ErrorResponse(
error.message || error,
3035,
diff --git a/plugins/main/server/controllers/wazuh-elastic.ts b/plugins/main/server/controllers/wazuh-elastic.ts
index cdcfb23d41..1dc12b502d 100644
--- a/plugins/main/server/controllers/wazuh-elastic.ts
+++ b/plugins/main/server/controllers/wazuh-elastic.ts
@@ -10,7 +10,6 @@
* Find more information about this on the LICENSE file.
*/
import { ErrorResponse } from '../lib/error-response';
-import { log } from '../lib/logger';
import { getConfiguration } from '../lib/get-configuration';
import {
AgentsVisualizations,
@@ -30,8 +29,6 @@ import {
OpenSearchDashboardsRequest,
RequestHandlerContext,
OpenSearchDashboardsResponseFactory,
- SavedObject,
- SavedObjectsFindResponse,
} from 'src/core/server';
import { getCookieValueByName } from '../lib/cookie';
import {
@@ -125,14 +122,12 @@ export class WazuhElasticCtrl {
item = lastChar === '*' ? item.slice(0, -1) : item;
return item.includes(pattern) || pattern.includes(item);
});
- log(
- 'wazuh-elastic:getTemplate',
+ context.wazuh.logger.debug(
`Template is valid: ${
isIncluded && Array.isArray(isIncluded) && isIncluded.length
? 'yes'
: 'no'
}`,
- 'debug',
);
return isIncluded && Array.isArray(isIncluded) && isIncluded.length
? response.ok({
@@ -150,7 +145,7 @@ export class WazuhElasticCtrl {
},
});
} catch (error) {
- log('wazuh-elastic:getTemplate', error.message || error);
+ context.wazuh.logger.error(error.message || error);
return ErrorResponse(
`Could not retrieve templates from ${WAZUH_INDEXER_NAME} due to ${
error.message || error
@@ -254,7 +249,7 @@ export class WazuhElasticCtrl {
},
});
} catch (error) {
- log('wazuh-elastic:getFieldTop', error.message || error);
+ context.wazuh.logger.error(error.message || error);
return ErrorResponse(error.message || error, 4004, 500, response);
}
}
@@ -333,7 +328,7 @@ export class WazuhElasticCtrl {
},
});
} catch (error) {
- log('wazuh-elastic:getCurrentPlatform', error.message || error);
+ context.wazuh.logger.error(error.message || error);
return ErrorResponse(error.message || error, 4011, 500, response);
}
}
@@ -343,85 +338,68 @@ export class WazuhElasticCtrl {
* @param {Array
}>
+ View available updates}
+ >
this.setState({ apiAvailableUpdateDetails: api })}
+ aria-label='Availabe updates'
+ iconType='eye'
+ onClick={() =>
+ this.setState({ apiAvailableUpdateDetails: api })
+ }
/>
) : null}
{item === 'error' && api.error?.detail ? (
-
+
this.props.copyToClipBoard(item.downReason)}
+ color='primary'
+ iconType='questionInCircle'
+ aria-label='Info about the error'
+ onClick={() =>
+ this.props.copyToClipBoard(item.downReason)
+ }
/>
@@ -380,7 +424,7 @@ export const ApiTable = compose(
} else {
return (
-
+
Checking
);
@@ -393,20 +437,22 @@ export const ApiTable = compose(
align: 'center',
sortable: true,
width: '80px',
- render: (value) => {
- return value === API_USER_STATUS_RUN_AS.ENABLED ? (
+ render: value => {
+ return value ===
+ getWazuhCorePlugin().API_USER_STATUS_RUN_AS.ENABLED ? (
-
+
- ) : value === API_USER_STATUS_RUN_AS.USER_NOT_ALLOWED ? (
+ ) : value ===
+ getWazuhCorePlugin().API_USER_STATUS_RUN_AS.USER_NOT_ALLOWED ? (
-
+
) : (
''
@@ -415,15 +461,19 @@ export const ApiTable = compose(
},
{
name: 'Actions',
- render: (item) => (
+ render: item => (
Set as default }}
- iconType={item.id === this.props.currentDefault ? 'starFilled' : 'starEmpty'}
- aria-label="Set as default"
+ iconType={
+ item.id === this.props.currentDefault
+ ? 'starFilled'
+ : 'starEmpty'
+ }
+ aria-label='Set as default'
onClick={async () => {
const currentDefault = await this.props.setDefault(item);
this.setState({
@@ -433,12 +483,12 @@ export const ApiTable = compose(
/>
- Check connection}>
+ Check connection}>
await this.checkApi(item)}
- color="success"
+ color='success'
/>
@@ -456,8 +506,8 @@ export const ApiTable = compose(
return (
-
-
+
+
@@ -469,8 +519,8 @@ export const ApiTable = compose(
this.props.showAddApi()}
>
@@ -478,26 +528,33 @@ export const ApiTable = compose(
- await this.refresh()}>
+ await this.refresh()}
+ >
Refresh
await this.getApisAvailableUpdates(true)}
>
Check updates{' '}
-
+
@@ -508,32 +565,34 @@ export const ApiTable = compose(
-
- From here you can manage and configure the API entries. You can also check their
- connection and status.
+
+ From here you can manage and configure the API entries. You
+ can also check their connection and status.
this.setState({ apiAvailableUpdateDetails: undefined })}
+ onClose={() =>
+ this.setState({ apiAvailableUpdateDetails: undefined })
+ }
/>
);
}
- }
+ },
);
ApiTable.propTypes = {
diff --git a/plugins/main/public/controllers/settings/settings.test.ts b/plugins/main/public/controllers/settings/settings.test.ts
index 88f1300e20..40b423cde9 100644
--- a/plugins/main/public/controllers/settings/settings.test.ts
+++ b/plugins/main/public/controllers/settings/settings.test.ts
@@ -1,10 +1,9 @@
-import { ApiCheck, AppState, formatUIDate } from '../../react-services';
+import { ApiCheck, formatUIDate } from '../../react-services';
import { SettingsController } from './settings';
import { ErrorHandler } from '../../react-services/error-management';
import { UI_LOGGER_LEVELS } from '../../../common/constants';
import { UI_ERROR_SEVERITIES } from '../../react-services/error-orchestrator/types';
-import { ManageHosts } from '../../../server/lib/manage-hosts';
import axios, { AxiosResponse } from 'axios';
jest.mock('../../react-services/time-service');
jest.mock('../../react-services/app-state');
@@ -155,8 +154,18 @@ describe('Settings Controller', () => {
);
controller.getSettings = jest.fn().mockResolvedValue([]);
// mocking manager hosts - apiEntries from wazuh.yml
- const manageHosts = new ManageHosts();
- controller.apiEntries = await manageHosts.getHosts();
+
+ controller.apiEntries = [
+ {
+ manager: {
+ url: 'https://wazuh.manager',
+ port: 55000,
+ username: 'wazuh-wui',
+ password: 'mypassword1-',
+ run_as: false,
+ },
+ },
+ ];
await controller.$onInit();
expect(mockedGetErrorOrchestrator.handleError).toBeCalledTimes(1);
expect(mockedGetErrorOrchestrator.handleError).toBeCalledWith(
diff --git a/plugins/main/public/kibana-services.ts b/plugins/main/public/kibana-services.ts
index 1257f238ed..1c536dc5e1 100644
--- a/plugins/main/public/kibana-services.ts
+++ b/plugins/main/public/kibana-services.ts
@@ -45,6 +45,8 @@ export const [getWzCurrentAppID, setWzCurrentAppID] =
createGetterSetter('WzCurrentAppID');
export const [getWazuhCheckUpdatesPlugin, setWazuhCheckUpdatesPlugin] =
createGetterSetter('WazuhCheckUpdatesPlugin');
+export const [getWazuhCorePlugin, setWazuhCorePlugin] =
+ createGetterSetter('WazuhCorePlugin');
export const [getHeaderActionMenuMounter, setHeaderActionMenuMounter] =
createGetterSetter(
'headerActionMenuMounter',
diff --git a/plugins/main/public/plugin.ts b/plugins/main/public/plugin.ts
index 7cf6cfceb6..c87b0ce50e 100644
--- a/plugins/main/public/plugin.ts
+++ b/plugins/main/public/plugin.ts
@@ -24,6 +24,7 @@ import {
setWzCurrentAppID,
setWazuhCheckUpdatesPlugin,
setHeaderActionMenuMounter,
+ setWazuhCorePlugin,
} from './kibana-services';
import {
AppPluginStartDependencies,
@@ -55,7 +56,10 @@ export class WazuhPlugin
public initializeInnerAngular?: () => void;
private innerAngularInitialized: boolean = false;
private hideTelemetryBanner?: () => void;
- public async setup(core: CoreSetup, plugins: WazuhSetupPlugins): WazuhSetup {
+ public async setup(
+ core: CoreSetup,
+ plugins: WazuhSetupPlugins,
+ ): Promise {
// Get custom logos configuration to start up the app with the correct logos
let logosInitialState = {};
try {
@@ -170,6 +174,7 @@ export class WazuhPlugin
setOverlays(core.overlays);
setErrorOrchestrator(ErrorOrchestratorService);
setWazuhCheckUpdatesPlugin(plugins.wazuhCheckUpdates);
+ setWazuhCorePlugin(plugins.wazuhCore);
return {};
}
}
diff --git a/plugins/main/public/types.ts b/plugins/main/public/types.ts
index e80f32877e..9d3c0e7915 100644
--- a/plugins/main/public/types.ts
+++ b/plugins/main/public/types.ts
@@ -5,13 +5,20 @@ import {
VisualizationsSetup,
VisualizationsStart,
} from '../../../src/plugins/visualizations/public';
-import { DataPublicPluginSetup, DataPublicPluginStart } from '../../../src/plugins/data/public';
+import {
+ DataPublicPluginSetup,
+ DataPublicPluginStart,
+} from '../../../src/plugins/data/public';
import { NavigationPublicPluginStart } from '../../../src/plugins/navigation/public';
import { UiActionsSetup } from '../../../src/plugins/ui_actions/public';
import { SecurityOssPluginStart } from '../../../src/plugins/security_oss/public/';
import { SavedObjectsStart } from '../../../src/plugins/saved_objects/public';
-import { TelemetryPluginStart, TelemetryPluginSetup } from '../../../src/plugins/telemetry/public';
+import {
+ TelemetryPluginStart,
+ TelemetryPluginSetup,
+} from '../../../src/plugins/telemetry/public';
import { WazuhCheckUpdatesPluginStart } from '../../wazuh-check-updates/public';
+import { WazuhCorePluginStart } from '../../wazuh-core/public';
import { DashboardStart } from '../../../src/plugins/dashboard/public';
export interface AppPluginStartDependencies {
@@ -24,6 +31,7 @@ export interface AppPluginStartDependencies {
savedObjects: SavedObjectsStart;
telemetry: TelemetryPluginStart;
wazuhCheckUpdates: WazuhCheckUpdatesPluginStart;
+ wazuhCore: WazuhCorePluginStart;
dashboard: DashboardStart;
}
export interface AppDependencies {
diff --git a/plugins/main/server/controllers/wazuh-api.ts b/plugins/main/server/controllers/wazuh-api.ts
index 87153db486..0f366841ed 100644
--- a/plugins/main/server/controllers/wazuh-api.ts
+++ b/plugins/main/server/controllers/wazuh-api.ts
@@ -20,30 +20,17 @@ import { HTTP_STATUS_CODES } from '../../common/constants';
import { getCustomizationSetting } from '../../common/services/settings';
import { addJobToQueue } from '../start/queue';
import fs from 'fs';
-import { ManageHosts } from '../lib/manage-hosts';
-import { UpdateRegistry } from '../lib/update-registry';
import jwtDecode from 'jwt-decode';
import {
OpenSearchDashboardsRequest,
RequestHandlerContext,
OpenSearchDashboardsResponseFactory,
} from 'src/core/server';
-import {
- APIUserAllowRunAs,
- CacheInMemoryAPIUserAllowRunAs,
- API_USER_STATUS_RUN_AS,
-} from '../lib/cache-api-user-has-run-as';
import { getCookieValueByName } from '../lib/cookie';
import { getConfiguration } from '../lib/get-configuration';
export class WazuhApiCtrl {
- manageHosts: ManageHosts;
- updateRegistry: UpdateRegistry;
-
- constructor() {
- this.manageHosts = new ManageHosts();
- this.updateRegistry = new UpdateRegistry();
- }
+ constructor() {}
async getToken(
context: RequestHandlerContext,
@@ -88,8 +75,8 @@ export class WazuhApiCtrl {
}
let token;
if (
- (await APIUserAllowRunAs.canUse(idHost)) ==
- API_USER_STATUS_RUN_AS.ENABLED
+ (await context.wazuh_core.cacheAPIUserAllowRunAs.canUse(idHost)) ===
+ context.wazuh_core.cacheAPIUserAllowRunAs.API_USER_STATUS_RUN_AS.ENABLED
) {
token = await context.wazuh.api.client.asCurrentUser.authenticate(
idHost,
@@ -145,7 +132,7 @@ export class WazuhApiCtrl {
// Get config from wazuh.yml
const id = request.body.id;
context.wazuh.logger.debug(`Getting server API host by ID: ${id}`);
- const api = await this.manageHosts.getHostById(id);
+ const api = await context.wazuh_core.manageHosts.getHostById(id);
context.wazuh.logger.debug(
`Server API host data: ${JSON.stringify(api)}`,
);
@@ -245,7 +232,10 @@ export class WazuhApiCtrl {
if (api.cluster_info) {
// Update cluster information in the wazuh-registry.json
- await this.updateRegistry.updateClusterInfo(id, api.cluster_info);
+ await context.wazuh_core.updateRegistry.updateClusterInfo(
+ id,
+ api.cluster_info,
+ );
// Hide Wazuh API secret, username, password
const copied = { ...api };
@@ -285,7 +275,7 @@ export class WazuhApiCtrl {
});
} else {
try {
- const apis = await this.manageHosts.getHosts();
+ const apis = await context.wazuh_core.manageHosts.getHosts();
for (const api of apis) {
try {
const id = Object.keys(api)[0];
@@ -381,7 +371,9 @@ export class WazuhApiCtrl {
// if (notValid) return ErrorResponse(notValid, 3003, HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR, response);
context.wazuh.logger.debug(`${request.body.id} is valid`);
// Check if a Wazuh API id is given (already stored API)
- const data = await this.manageHosts.getHostById(request.body.id);
+ const data = await context.wazuh_core.manageHosts.getHostById(
+ request.body.id,
+ );
if (data) {
apiAvailable = data;
} else {
@@ -443,7 +435,9 @@ export class WazuhApiCtrl {
);
// Check the run_as for the API user and update it
- let apiUserAllowRunAs = API_USER_STATUS_RUN_AS.ALL_DISABLED;
+ let apiUserAllowRunAs =
+ context.wazuh_core.cacheAPIUserAllowRunAs.API_USER_STATUS_RUN_AS
+ .ALL_DISABLED;
const responseApiUserAllowRunAs =
await context.wazuh.api.client.asInternalUser.request(
'GET',
@@ -458,18 +452,26 @@ export class WazuhApiCtrl {
if (allow_run_as && apiAvailable && apiAvailable.run_as)
// HOST AND USER ENABLED
- apiUserAllowRunAs = API_USER_STATUS_RUN_AS.ENABLED;
+ apiUserAllowRunAs =
+ context.wazuh_core.cacheAPIUserAllowRunAs.API_USER_STATUS_RUN_AS
+ .ENABLED;
else if (!allow_run_as && apiAvailable && apiAvailable.run_as)
// HOST ENABLED AND USER DISABLED
- apiUserAllowRunAs = API_USER_STATUS_RUN_AS.USER_NOT_ALLOWED;
+ apiUserAllowRunAs =
+ context.wazuh_core.cacheAPIUserAllowRunAs.API_USER_STATUS_RUN_AS
+ .USER_NOT_ALLOWED;
else if (allow_run_as && (!apiAvailable || !apiAvailable.run_as))
// USER ENABLED AND HOST DISABLED
- apiUserAllowRunAs = API_USER_STATUS_RUN_AS.HOST_DISABLED;
+ apiUserAllowRunAs =
+ context.wazuh_core.cacheAPIUserAllowRunAs.API_USER_STATUS_RUN_AS
+ .HOST_DISABLED;
else if (!allow_run_as && (!apiAvailable || !apiAvailable.run_as))
// HOST AND USER DISABLED
- apiUserAllowRunAs = API_USER_STATUS_RUN_AS.ALL_DISABLED;
+ apiUserAllowRunAs =
+ context.wazuh_core.cacheAPIUserAllowRunAs.API_USER_STATUS_RUN_AS
+ .ALL_DISABLED;
}
- CacheInMemoryAPIUserAllowRunAs.set(
+ context.wazuh_core.cacheAPIUserAllowRunAs.set(
request.body.id,
apiAvailable.username,
apiUserAllowRunAs,
@@ -663,7 +665,7 @@ export class WazuhApiCtrl {
async makeRequest(context, method, path, data, id, response) {
const devTools = !!(data || {}).devTools;
try {
- const api = await this.manageHosts.getHostById(id);
+ const api = await context.wazuh_core.manageHosts.getHostById(id);
if (devTools) {
delete data.devTools;
}
@@ -1118,7 +1120,7 @@ export class WazuhApiCtrl {
) {
try {
const source = JSON.parse(
- fs.readFileSync(this.updateRegistry.file, 'utf8'),
+ fs.readFileSync(context.wazuh_core.updateRegistry.file, 'utf8'),
);
if (source.installationDate && source.lastRestart) {
context.wazuh.logger.debug(
@@ -1158,7 +1160,7 @@ export class WazuhApiCtrl {
) {
try {
const source = JSON.parse(
- fs.readFileSync(this.updateRegistry.file, 'utf8'),
+ fs.readFileSync(context.wazuh_core.updateRegistry.file, 'utf8'),
);
return response.ok({
body: {
diff --git a/plugins/main/server/controllers/wazuh-elastic.ts b/plugins/main/server/controllers/wazuh-elastic.ts
index 1dc12b502d..63550e4900 100644
--- a/plugins/main/server/controllers/wazuh-elastic.ts
+++ b/plugins/main/server/controllers/wazuh-elastic.ts
@@ -24,7 +24,6 @@ import {
WAZUH_SAMPLE_ALERTS_INDEX_REPLICAS,
} from '../../common/constants';
import jwtDecode from 'jwt-decode';
-import { ManageHosts } from '../lib/manage-hosts';
import {
OpenSearchDashboardsRequest,
RequestHandlerContext,
@@ -40,10 +39,8 @@ import { WAZUH_INDEXER_NAME } from '../../common/constants';
export class WazuhElasticCtrl {
wzSampleAlertsIndexPrefix: string;
- manageHosts: ManageHosts;
constructor() {
this.wzSampleAlertsIndexPrefix = this.getSampleAlertPrefix();
- this.manageHosts = new ManageHosts();
}
/**
diff --git a/plugins/main/server/controllers/wazuh-hosts.ts b/plugins/main/server/controllers/wazuh-hosts.ts
index cf41990b82..52cc3cfcce 100644
--- a/plugins/main/server/controllers/wazuh-hosts.ts
+++ b/plugins/main/server/controllers/wazuh-hosts.ts
@@ -21,18 +21,10 @@ import {
PLUGIN_PLATFORM_NAME,
WAZUH_DATA_PLUGIN_PLATFORM_BASE_ABSOLUTE_PATH,
} from '../../common/constants';
-import { APIUserAllowRunAs } from '../lib/cache-api-user-has-run-as';
import { ErrorResponse } from '../lib/error-response';
-import { ManageHosts } from '../lib/manage-hosts';
-import { UpdateRegistry } from '../lib/update-registry';
export class WazuhHostsCtrl {
- manageHosts: ManageHosts;
- updateRegistry: UpdateRegistry;
- constructor() {
- this.manageHosts = new ManageHosts();
- this.updateRegistry = new UpdateRegistry();
- }
+ constructor() {}
/**
* This get all hosts entries in the wazuh.yml and the related info in the wazuh-registry.json
@@ -47,72 +39,17 @@ export class WazuhHostsCtrl {
response: OpenSearchDashboardsResponseFactory,
) {
try {
- const removePassword = true;
- const hosts = await this.manageHosts.getHosts();
- const registry = await this.updateRegistry.getHosts();
- const result = await this.joinHostRegistry(
- hosts,
- registry,
- removePassword,
- );
+ const result =
+ await context.wazuh_core.serverAPIHostEntries.getHostsEntries();
return response.ok({
body: result,
});
} catch (error) {
- if (
- error &&
- error.message &&
- [
- 'ENOENT: no such file or directory',
- WAZUH_DATA_PLUGIN_PLATFORM_BASE_ABSOLUTE_PATH,
- ].every(text => error.message.includes(text))
- ) {
- return response.badRequest({
- body: {
- message: `Error getting the hosts entries: The \'${WAZUH_DATA_PLUGIN_PLATFORM_BASE_ABSOLUTE_PATH}\' directory could not exist in your ${PLUGIN_PLATFORM_NAME} installation.
- If this doesn't exist, create it and give the permissions 'sudo mkdir ${WAZUH_DATA_PLUGIN_PLATFORM_BASE_ABSOLUTE_PATH};sudo chown -R ${PLUGIN_PLATFORM_INSTALLATION_USER}:${PLUGIN_PLATFORM_INSTALLATION_USER_GROUP} ${WAZUH_DATA_PLUGIN_PLATFORM_BASE_ABSOLUTE_PATH}'. After, restart the ${PLUGIN_PLATFORM_NAME} service.`,
- },
- });
- }
context.wazuh.logger.error(error.message || error);
return ErrorResponse(error.message || error, 2001, 500, response);
}
}
- /**
- * Joins the hosts with the related information in the registry
- * @param {Object} hosts
- * @param {Object} registry
- * @param {Boolean} removePassword
- */
- async joinHostRegistry(
- hosts: any,
- registry: any,
- removePassword: boolean = true,
- ) {
- try {
- if (!Array.isArray(hosts)) {
- throw new Error('Hosts configuration error in wazuh.yml');
- }
-
- return await Promise.all(
- hosts.map(async h => {
- const id = Object.keys(h)[0];
- const api = Object.assign(h[id], { id: id });
- const host = Object.assign(api, registry[id]);
- // Add to run_as from API user. Use the cached value or get it doing a request
- host.allow_run_as = await APIUserAllowRunAs.check(id);
- if (removePassword) {
- delete host.password;
- delete host.token;
- }
- return host;
- }),
- );
- } catch (error) {
- throw new Error(error);
- }
- }
/**
* This update an API hostname
* @param {Object} context
@@ -128,7 +65,10 @@ export class WazuhHostsCtrl {
try {
const { id } = request.params;
const { cluster_info } = request.body;
- await this.updateRegistry.updateClusterInfo(id, cluster_info);
+ await context.wazuh_core.updateRegistry.updateClusterInfo(
+ id,
+ cluster_info,
+ );
context.wazuh.logger.info(`Server API host entry ${id} updated`);
return response.ok({
body: { statusCode: 200, message: 'ok' },
@@ -160,7 +100,7 @@ export class WazuhHostsCtrl {
try {
const { entries } = request.body;
context.wazuh.logger.debug('Cleaning registry file');
- await this.updateRegistry.removeOrphanEntries(entries);
+ await context.wazuh_core.updateRegistry.removeOrphanEntries(entries);
return response.ok({
body: { statusCode: 200, message: 'ok' },
});
diff --git a/plugins/main/server/controllers/wazuh-reporting-security-endpoint-handler.test.ts b/plugins/main/server/controllers/wazuh-reporting-security-endpoint-handler.test.ts
index 5e0c8c4e15..1a0d771df1 100644
--- a/plugins/main/server/controllers/wazuh-reporting-security-endpoint-handler.test.ts
+++ b/plugins/main/server/controllers/wazuh-reporting-security-endpoint-handler.test.ts
@@ -2,51 +2,62 @@ import md5 from 'md5';
import fs from 'fs';
import { WazuhReportingCtrl } from './wazuh-reporting';
-jest.mock('../lib/logger', () => ({
- log: jest.fn()
-}));
-
jest.mock('../lib/reporting/extended-information', () => ({
extendedInformation: () => {},
- buildAgentsTable: () => {}
+ buildAgentsTable: () => {},
}));
jest.mock('../lib/reporting/printer', () => {
class ReportPrinterMock {
- constructor() { }
- addContent() { }
- addConfigTables() { }
- addTables() { }
- addTimeRangeAndFilters() { }
- addVisualizations() { }
- formatDate() { }
- checkTitle() { }
- addSimpleTable() { }
- addList() { }
- addNewLine() { }
- addContentWithNewLine() { }
- addAgentsFilters() { }
- print() { }
+ constructor() {}
+ addContent() {}
+ addConfigTables() {}
+ addTables() {}
+ addTimeRangeAndFilters() {}
+ addVisualizations() {}
+ formatDate() {}
+ checkTitle() {}
+ addSimpleTable() {}
+ addList() {}
+ addNewLine() {}
+ addContentWithNewLine() {}
+ addAgentsFilters() {}
+ print() {}
}
return {
- ReportPrinter: ReportPrinterMock
- }
+ ReportPrinter: ReportPrinterMock,
+ };
});
-const getMockerUserContext = (username: string) => ({ username, hashUsername: md5(username) });
+const getMockerUserContext = (username: string) => ({
+ username,
+ hashUsername: md5(username),
+});
const mockContext = (username: string) => ({
wazuh: {
security: {
- getCurrentUser: () => getMockerUserContext(username)
- }
- }
+ getCurrentUser: () => getMockerUserContext(username),
+ },
+ logger: {
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ debug: jest.fn(),
+ get: jest.fn(() => ({
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ debug: jest.fn(),
+ })),
+ },
+ },
});
const mockResponse = () => ({
- ok: (body) => body,
- custom: (body) => body,
- badRequest: (body) => body
+ ok: body => body,
+ custom: body => body,
+ badRequest: body => body,
});
const endpointController = new WazuhReportingCtrl();
@@ -71,124 +82,155 @@ describe('[security] Report endpoints guard related to a file. Parameter defines
});
it.each`
- testTitle | username | filename | endpointProtected
- ${'Execute endpoint handler'} | ${'admin'} | ${'wazuh-module-overview-general-1234.pdf'} | ${false}
- ${'Endpoint protected'} | ${'admin'} | ${'../wazuh-module-overview-general-1234.pdf'} | ${true}
- ${'Endpoint protected'} | ${'admin'} | ${'wazuh-module-overview-../general-1234.pdf'} | ${true}
- ${'Endpoint protected'} | ${'admin'} | ${'custom../wazuh-module-overview-general-1234.pdf'} | ${true}
- ${'Execute endpoint handler'} | ${'../../etc'} | ${'wazuh-module-agents-001-general-1234.pdf'} | ${false}
- ${'Endpoint protected'} | ${'../../etc'} | ${'../wazuh-module-agents-001-general-1234.pdf'} | ${true}
- ${'Endpoint protected'} | ${'../../etc'} | ${'wazuh-module-overview-../general-1234.pdf'} | ${true}
- ${'Endpoint protected'} | ${'../../etc'} | ${'custom../wazuh-module-overview-general-1234.pdf'} | ${true}
- `(`$testTitle
+ testTitle | username | filename | endpointProtected
+ ${'Execute endpoint handler'} | ${'admin'} | ${'wazuh-module-overview-general-1234.pdf'} | ${false}
+ ${'Endpoint protected'} | ${'admin'} | ${'../wazuh-module-overview-general-1234.pdf'} | ${true}
+ ${'Endpoint protected'} | ${'admin'} | ${'wazuh-module-overview-../general-1234.pdf'} | ${true}
+ ${'Endpoint protected'} | ${'admin'} | ${'custom../wazuh-module-overview-general-1234.pdf'} | ${true}
+ ${'Execute endpoint handler'} | ${'../../etc'} | ${'wazuh-module-agents-001-general-1234.pdf'} | ${false}
+ ${'Endpoint protected'} | ${'../../etc'} | ${'../wazuh-module-agents-001-general-1234.pdf'} | ${true}
+ ${'Endpoint protected'} | ${'../../etc'} | ${'wazuh-module-overview-../general-1234.pdf'} | ${true}
+ ${'Endpoint protected'} | ${'../../etc'} | ${'custom../wazuh-module-overview-general-1234.pdf'} | ${true}
+ `(
+ `$testTitle
username: $username
filename: $filename
- endpointProtected: $endpointProtected`, async ({ username, filename, endpointProtected }) => {
- const response = await endpointController.checkReportsUserDirectoryIsValidRouteDecorator(
- routeHandler,
- function getFilename(request) {
- return request.params.name
+ endpointProtected: $endpointProtected`,
+ async ({ username, filename, endpointProtected }) => {
+ const response =
+ await endpointController.checkReportsUserDirectoryIsValidRouteDecorator(
+ routeHandler,
+ function getFilename(request) {
+ return request.params.name;
+ },
+ )(
+ mockContext(username),
+ { params: { name: filename } },
+ mockResponse(),
+ );
+ if (endpointProtected) {
+ expect(response.body.message).toBe('5040 - You shall not pass!');
+ expect(routeHandler.mock.calls).toHaveLength(0);
+ } else {
+ expect(routeHandler.mock.calls).toHaveLength(1);
+ expect(response).toBe(routeHandlerResponse);
}
- )(mockContext(username), { params: { name: filename } }, mockResponse());
- if (endpointProtected) {
-
- expect(response.body.message).toBe('5040 - You shall not pass!');
- expect(routeHandler.mock.calls).toHaveLength(0);
- } else {
- expect(routeHandler.mock.calls).toHaveLength(1);
- expect(response).toBe(routeHandlerResponse);
- }
- });
-
+ },
+ );
});
describe('[security] GET /reports', () => {
-
it.each`
- username
- ${'admin'}
- ${'../../etc'}
- `(`Get user reports: GET /reports
- username: $username`, async ({ username }) => {
- jest.spyOn(fs, 'readdirSync').mockImplementation(() => []);
-
- const response = await endpointController.getReports(mockContext(username), {}, mockResponse());
- expect(response.body.reports).toHaveLength(0);
- });
+ username
+ ${'admin'}
+ ${'../../etc'}
+ `(
+ `Get user reports: GET /reports
+ username: $username`,
+ async ({ username }) => {
+ jest.spyOn(fs, 'readdirSync').mockImplementation(() => []);
+
+ const response = await endpointController.getReports(
+ mockContext(username),
+ {},
+ mockResponse(),
+ );
+ expect(response.body.reports).toHaveLength(0);
+ },
+ );
});
describe('[security] GET /reports/{name}', () => {
-
it.each`
- titleTest | username | filename | valid
- ${'Get report'} | ${'admin'} | ${'wazuh-module-overview-1234.pdf'} | ${true}
- ${'Endpoint protected'} | ${'admin'} | ${'../wazuh-module-overview-1234.pdf'} | ${false}
- ${'Get report'} | ${'../../etc'} | ${'wazuh-module-overview-1234.pdf'} | ${true}
- ${'Endpoint protected'} | ${'../../etc'} | ${'../wazuh-module-overview-1234.pdf'} | ${false}
- `(`$titleTest: GET /reports/$filename
+ titleTest | username | filename | valid
+ ${'Get report'} | ${'admin'} | ${'wazuh-module-overview-1234.pdf'} | ${true}
+ ${'Endpoint protected'} | ${'admin'} | ${'../wazuh-module-overview-1234.pdf'} | ${false}
+ ${'Get report'} | ${'../../etc'} | ${'wazuh-module-overview-1234.pdf'} | ${true}
+ ${'Endpoint protected'} | ${'../../etc'} | ${'../wazuh-module-overview-1234.pdf'} | ${false}
+ `(
+ `$titleTest: GET /reports/$filename
username: $username
- valid: $valid`, async ({ username, filename, valid }) => {
- const fileContent = 'content file';
- jest.spyOn(fs, 'readFileSync').mockImplementation(() => fileContent);
-
- const response = await endpointController.getReportByName(mockContext(username), { params: { name: filename } }, mockResponse());
- if (valid) {
- expect(response.headers['Content-Type']).toBe('application/pdf');
- expect(response.body).toBe('content file');
- } else {
- expect(response.body.message).toBe('5040 - You shall not pass!');
- }
- });
+ valid: $valid`,
+ async ({ username, filename, valid }) => {
+ const fileContent = 'content file';
+ jest.spyOn(fs, 'readFileSync').mockImplementation(() => fileContent);
+
+ const response = await endpointController.getReportByName(
+ mockContext(username),
+ { params: { name: filename } },
+ mockResponse(),
+ );
+ if (valid) {
+ expect(response.headers['Content-Type']).toBe('application/pdf');
+ expect(response.body).toBe('content file');
+ } else {
+ expect(response.body.message).toBe('5040 - You shall not pass!');
+ }
+ },
+ );
});
describe('[security] POST /reports', () => {
jest.mock('../lib/filesystem', () => ({
- createDataDirectoryIfNotExists: jest.fn()
+ createDataDirectoryIfNotExists: jest.fn(),
}));
it.each`
- titleTest | username | moduleID | valid
- ${'Create report'} | ${'admin'} | ${'general'} | ${true}
- ${'Endpoint protected'} | ${'admin'} | ${'../general'} | ${false}
- ${'Create report'} | ${'../../etc'} | ${'general'} | ${true}
- ${'Endpoint protected'} | ${'../../etc'} | ${'../general'} | ${false}
- `(`$titleTest: POST /reports/modules/$moduleID
+ titleTest | username | moduleID | valid
+ ${'Create report'} | ${'admin'} | ${'general'} | ${true}
+ ${'Endpoint protected'} | ${'admin'} | ${'../general'} | ${false}
+ ${'Create report'} | ${'../../etc'} | ${'general'} | ${true}
+ ${'Endpoint protected'} | ${'../../etc'} | ${'../general'} | ${false}
+ `(
+ `$titleTest: POST /reports/modules/$moduleID
username: $username
- valid: $valid`, async ({ username, moduleID, valid }) => {
- jest.spyOn(endpointController, 'renderHeader').mockImplementation(() => true);
- jest.spyOn(endpointController, 'sanitizeKibanaFilters').mockImplementation(() => [false, false]);
-
- const mockRequest = {
- body: {
- array: [],
- agents: false,
- browserTimezone: '',
- searchBar: '',
- filters: [],
- time: {
- from: '',
- to: ''
+ valid: $valid`,
+ async ({ username, moduleID, valid }) => {
+ jest
+ .spyOn(endpointController, 'renderHeader')
+ .mockImplementation(() => true);
+ jest
+ .spyOn(endpointController, 'sanitizeKibanaFilters')
+ .mockImplementation(() => [false, false]);
+
+ const mockRequest = {
+ body: {
+ array: [],
+ agents: false,
+ browserTimezone: '',
+ searchBar: '',
+ filters: [],
+ time: {
+ from: '',
+ to: '',
+ },
+ tables: [],
+ section: 'overview',
+ indexPatternTitle: 'wazuh-alerts-*',
+ apiId: 'default',
+ tab: moduleID,
},
- tables: [],
- section: 'overview',
- indexPatternTitle: 'wazuh-alerts-*',
- apiId: 'default',
- tab: moduleID
- },
- params: {
- moduleID: moduleID
- }
- };
+ params: {
+ moduleID: moduleID,
+ },
+ };
- const response = await endpointController.createReportsModules(mockContext(username), mockRequest, mockResponse());
+ const response = await endpointController.createReportsModules(
+ mockContext(username),
+ mockRequest,
+ mockResponse(),
+ );
- if (valid) {
- expect(response.body.success).toBe(true);
- expect(response.body.message).toMatch(new RegExp(`Report wazuh-module-overview-${moduleID}`));
- } else {
- expect(response.body.message).toBe('5040 - You shall not pass!');
- };
- });
+ if (valid) {
+ expect(response.body.success).toBe(true);
+ expect(response.body.message).toMatch(
+ new RegExp(`Report wazuh-module-overview-${moduleID}`),
+ );
+ } else {
+ expect(response.body.message).toBe('5040 - You shall not pass!');
+ }
+ },
+ );
});
describe('[security] DELETE /reports/', () => {
@@ -199,26 +241,35 @@ describe('[security] DELETE /reports/', () => {
});
it.each`
- titleTest | username | filename | valid
- ${'Delete report'} | ${'admin'} | ${'wazuh-module-overview-1234.pdf'} | ${true}
- ${'Endpoint protected'} | ${'admin'} | ${'../wazuh-module-overview-1234.pdf'} | ${false}
- ${'Endpoint protected'} | ${'admin'} | ${'custom../wazuh-module-overview-1234.pdf'}| ${false}
- ${'Delete report'} | ${'../../etc'} | ${'wazuh-module-overview-1234.pdf'} | ${true}
- ${'Endpoint protected'} | ${'../../etc'} | ${'../wazuh-module-overview-1234.pdf'} | ${false}
- ${'Endpoint protected'} | ${'../../etc'} | ${'custom../wazuh-module-overview-1234.pdf'}| ${false}
- `(`[security] DELETE /reports/$filename
+ titleTest | username | filename | valid
+ ${'Delete report'} | ${'admin'} | ${'wazuh-module-overview-1234.pdf'} | ${true}
+ ${'Endpoint protected'} | ${'admin'} | ${'../wazuh-module-overview-1234.pdf'} | ${false}
+ ${'Endpoint protected'} | ${'admin'} | ${'custom../wazuh-module-overview-1234.pdf'} | ${false}
+ ${'Delete report'} | ${'../../etc'} | ${'wazuh-module-overview-1234.pdf'} | ${true}
+ ${'Endpoint protected'} | ${'../../etc'} | ${'../wazuh-module-overview-1234.pdf'} | ${false}
+ ${'Endpoint protected'} | ${'../../etc'} | ${'custom../wazuh-module-overview-1234.pdf'} | ${false}
+ `(
+ `[security] DELETE /reports/$filename
username: $username
- valid: $valid`, async ({ filename, username, valid }) => {
- mockFsUnlinkSync = jest.spyOn(fs, 'unlinkSync').mockImplementation(() => { });
-
- const response = await endpointController.deleteReportByName(mockContext(username), { params: { name: filename } }, mockResponse());
-
- if (valid) {
- expect(response.body.error).toBe(0);
- expect(mockFsUnlinkSync.mock.calls).toHaveLength(1);
- } else {
- expect(response.body.message).toBe('5040 - You shall not pass!');
- expect(mockFsUnlinkSync.mock.calls).toHaveLength(0);
- };
- });
-});
\ No newline at end of file
+ valid: $valid`,
+ async ({ filename, username, valid }) => {
+ mockFsUnlinkSync = jest
+ .spyOn(fs, 'unlinkSync')
+ .mockImplementation(() => {});
+
+ const response = await endpointController.deleteReportByName(
+ mockContext(username),
+ { params: { name: filename } },
+ mockResponse(),
+ );
+
+ if (valid) {
+ expect(response.body.error).toBe(0);
+ expect(mockFsUnlinkSync.mock.calls).toHaveLength(1);
+ } else {
+ expect(response.body.message).toBe('5040 - You shall not pass!');
+ expect(mockFsUnlinkSync.mock.calls).toHaveLength(0);
+ }
+ },
+ );
+});
diff --git a/plugins/main/server/controllers/wazuh-reporting-security-endpoint-parameters-validation.test.ts b/plugins/main/server/controllers/wazuh-reporting-security-endpoint-parameters-validation.test.ts
index edd829d9fa..4aa002af30 100644
--- a/plugins/main/server/controllers/wazuh-reporting-security-endpoint-parameters-validation.test.ts
+++ b/plugins/main/server/controllers/wazuh-reporting-security-endpoint-parameters-validation.test.ts
@@ -5,8 +5,15 @@ import { ByteSizeValue } from '@osd/config-schema';
import supertest from 'supertest';
import { WazuhReportingRoutes } from '../routes/wazuh-reporting';
import md5 from 'md5';
-import { createDataDirectoryIfNotExists, createDirectoryIfNotExists } from '../lib/filesystem';
-import { WAZUH_DATA_ABSOLUTE_PATH, WAZUH_DATA_DOWNLOADS_DIRECTORY_PATH, WAZUH_DATA_DOWNLOADS_REPORTS_DIRECTORY_PATH } from '../../common/constants';
+import {
+ createDataDirectoryIfNotExists,
+ createDirectoryIfNotExists,
+} from '../lib/filesystem';
+import {
+ WAZUH_DATA_ABSOLUTE_PATH,
+ WAZUH_DATA_DOWNLOADS_DIRECTORY_PATH,
+ WAZUH_DATA_DOWNLOADS_REPORTS_DIRECTORY_PATH,
+} from '../../common/constants';
import { execSync } from 'child_process';
import path from 'path';
import fs from 'fs';
@@ -16,18 +23,25 @@ const logger = loggingService.get();
const context = {
wazuh: {
security: {
- getCurrentUser: (request) => {
+ getCurrentUser: request => {
// x-test-username header doesn't exist when the platform or plugin are running.
// It is used to generate the output of this method so we can simulate the user
// that does the request to the endpoint and is expected by the endpoint handlers
// of the plugin.
const username = request.headers['x-test-username'];
- return { username, hashUsername: md5(username) }
- }
- }
- }
+ return { username, hashUsername: md5(username) };
+ },
+ },
+ logger: {
+ debug: jest.fn(),
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ },
+ },
};
-const enhanceWithContext = (fn: (...args: any[]) => any) => fn.bind(null, context);
+const enhanceWithContext = (fn: (...args: any[]) => any) =>
+ fn.bind(null, context);
let server, innerServer;
beforeAll(async () => {
@@ -40,13 +54,29 @@ beforeAll(async () => {
// Create report files
[
{ name: md5('admin'), files: ['wazuh-module-overview-general-1234.pdf'] },
- { name: md5('../../etc'), files: ['wazuh-module-overview-general-1234.pdf'] }
+ {
+ name: md5('../../etc'),
+ files: ['wazuh-module-overview-general-1234.pdf'],
+ },
].forEach(({ name, files }) => {
- createDirectoryIfNotExists(path.join(WAZUH_DATA_DOWNLOADS_REPORTS_DIRECTORY_PATH, name));
+ createDirectoryIfNotExists(
+ path.join(WAZUH_DATA_DOWNLOADS_REPORTS_DIRECTORY_PATH, name),
+ );
if (files) {
- files.forEach(filename => fs.closeSync(fs.openSync(path.join(WAZUH_DATA_DOWNLOADS_REPORTS_DIRECTORY_PATH, name, filename), 'w')));
- };
+ files.forEach(filename =>
+ fs.closeSync(
+ fs.openSync(
+ path.join(
+ WAZUH_DATA_DOWNLOADS_REPORTS_DIRECTORY_PATH,
+ name,
+ filename,
+ ),
+ 'w',
+ ),
+ ),
+ );
+ }
});
// Create server
@@ -64,7 +94,11 @@ beforeAll(async () => {
} as any;
server = new HttpServer(loggingService, 'tests');
const router = new Router('', logger, enhanceWithContext);
- const { registerRouter, server: innerServerTest, ...rest } = await server.setup(config);
+ const {
+ registerRouter,
+ server: innerServerTest,
+ ...rest
+ } = await server.setup(config);
innerServer = innerServerTest;
// Register routes
@@ -87,202 +121,229 @@ afterAll(async () => {
describe('[endpoint] GET /reports', () => {
it.each`
- username
- ${'admin'}
- ${'../../etc'}
- `(`Get reports of user GET /reports - 200
- username: $username`, async ({ username }) => {
- const response = await supertest(innerServer.listener)
- .get('/reports')
- .set('x-test-username', username)
- .expect(200);
+ username
+ ${'admin'}
+ ${'../../etc'}
+ `(
+ `Get reports of user GET /reports - 200
+ username: $username`,
+ async ({ username }) => {
+ const response = await supertest(innerServer.listener)
+ .get('/reports')
+ .set('x-test-username', username)
+ .expect(200);
- expect(response.body.reports).toBeDefined();
- });
+ expect(response.body.reports).toBeDefined();
+ },
+ );
});
describe('[endpoint][security] GET /reports/{name} - Parameters validation', () => {
it.each`
- testTitle | username | filename | responseStatusCode | responseBodyMessage
- ${'Get report by filename'} | ${'admin'} | ${'wazuh-module-overview-general-1234.pdf'} | ${200} | ${null}
- ${'Invalid parameters'} | ${'admin'} | ${'..%2fwazuh-module-overview-general-1234.pdf'} | ${400} | ${'[request params.name]: must be A-z, 0-9, _, ., and - are allowed. It must end with .pdf.'}
- ${'Invalid parameters'} | ${'admin'} | ${'custom..%2fwazuh-module-overview-general-1234.pdf'} | ${400} | ${'[request params.name]: must be A-z, 0-9, _, ., and - are allowed. It must end with .pdf.'}
- ${'Route not found'} | ${'admin'} | ${'../custom..%2fwazuh-module-overview-general-1234.pdf'} | ${404} | ${/Not Found/}
- ${'Get report by filename'} | ${'../../etc'} | ${'wazuh-module-overview-general-1234.pdf'} | ${200} | ${null}
- ${'Invalid parameters'} | ${'../../etc'} | ${'..%2fwazuh-module-overview-general-1234.pdf'} | ${400} | ${'[request params.name]: must be A-z, 0-9, _, ., and - are allowed. It must end with .pdf.'}
- ${'Invalid parameters'} | ${'../../etc'} | ${'custom..%2fwazuh-module-overview-general-1234.pdf'} | ${400} | ${'[request params.name]: must be A-z, 0-9, _, ., and - are allowed. It must end with .pdf.'}
- ${'Route not found'} | ${'../../etc'} | ${'../custom..%2fwazuh-module-overview-general-1234.pdf'} | ${404} | ${/Not Found/}
- `(`$testTitle: GET /reports/$filename - responseStatusCode: $responseStatusCode
+ testTitle | username | filename | responseStatusCode | responseBodyMessage
+ ${'Get report by filename'} | ${'admin'} | ${'wazuh-module-overview-general-1234.pdf'} | ${200} | ${null}
+ ${'Invalid parameters'} | ${'admin'} | ${'..%2fwazuh-module-overview-general-1234.pdf'} | ${400} | ${'[request params.name]: must be A-z, 0-9, _, ., and - are allowed. It must end with .pdf.'}
+ ${'Invalid parameters'} | ${'admin'} | ${'custom..%2fwazuh-module-overview-general-1234.pdf'} | ${400} | ${'[request params.name]: must be A-z, 0-9, _, ., and - are allowed. It must end with .pdf.'}
+ ${'Route not found'} | ${'admin'} | ${'../custom..%2fwazuh-module-overview-general-1234.pdf'} | ${404} | ${/Not Found/}
+ ${'Get report by filename'} | ${'../../etc'} | ${'wazuh-module-overview-general-1234.pdf'} | ${200} | ${null}
+ ${'Invalid parameters'} | ${'../../etc'} | ${'..%2fwazuh-module-overview-general-1234.pdf'} | ${400} | ${'[request params.name]: must be A-z, 0-9, _, ., and - are allowed. It must end with .pdf.'}
+ ${'Invalid parameters'} | ${'../../etc'} | ${'custom..%2fwazuh-module-overview-general-1234.pdf'} | ${400} | ${'[request params.name]: must be A-z, 0-9, _, ., and - are allowed. It must end with .pdf.'}
+ ${'Route not found'} | ${'../../etc'} | ${'../custom..%2fwazuh-module-overview-general-1234.pdf'} | ${404} | ${/Not Found/}
+ `(
+ `$testTitle: GET /reports/$filename - responseStatusCode: $responseStatusCode
username: $username
- responseBodyMessage: $responseBodyMessage`, async ({ username, filename, responseStatusCode, responseBodyMessage }) => {
- const response = await supertest(innerServer.listener)
- .get(`/reports/${filename}`)
- .set('x-test-username', username)
- .expect(responseStatusCode);
- if (responseStatusCode === 200) {
- expect(response.header['content-type']).toMatch(/application\/pdf/);
- expect(response.body instanceof Buffer).toBe(true);
- };
- if (responseBodyMessage) {
- expect(response.body.message).toMatch(responseBodyMessage);
- };
- });
+ responseBodyMessage: $responseBodyMessage`,
+ async ({ username, filename, responseStatusCode, responseBodyMessage }) => {
+ const response = await supertest(innerServer.listener)
+ .get(`/reports/${filename}`)
+ .set('x-test-username', username)
+ .expect(responseStatusCode);
+ if (responseStatusCode === 200) {
+ expect(response.header['content-type']).toMatch(/application\/pdf/);
+ expect(response.body instanceof Buffer).toBe(true);
+ }
+ if (responseBodyMessage) {
+ expect(response.body.message).toMatch(responseBodyMessage);
+ }
+ },
+ );
});
describe('[endpoint][security] POST /reports/modules/{moduleID} - Parameters validation', () => {
it.each`
- testTitle | username | moduleID | agents | responseStatusCode | responseBodyMessage
- ${'Invalid paramenters'} | ${'admin'} | ${'..general'} | ${false} | ${400} | ${/\[request params.moduleID\]: types that failed validation:/}
- ${'Route not found'} | ${'admin'} | ${'../general'} | ${false} | ${404} | ${/Not Found/}
- ${'Route not found'} | ${'admin'} | ${'../general'} | ${'001'} | ${404} | ${/Not Found/}
- ${'Invalid paramenters'} | ${'admin'} | ${'..%2fgeneral'} | ${'../001'} | ${400} | ${/\[request params.moduleID\]: types that failed validation:/}
- ${'Invalid paramenters'} | ${'admin'} | ${'..%2fgeneral'} | ${'001'} | ${400} | ${/\[request params.moduleID\]: types that failed validation:/}
- ${'Invalid paramenters'} | ${'admin'} | ${'general'} | ${'..001'} | ${400} | ${/\[request body.agents\]: types that failed validation:/}
- ${'Invalid paramenters'} | ${'admin'} | ${'general'} | ${'../001'} | ${400} | ${/\[request body.agents\]: types that failed validation:/}
- `(`$testTitle: GET /reports/modules/$moduleID - responseStatusCode: $responseStatusCode
+ testTitle | username | moduleID | agents | responseStatusCode | responseBodyMessage
+ ${'Invalid paramenters'} | ${'admin'} | ${'..general'} | ${false} | ${400} | ${/\[request params.moduleID\]: types that failed validation:/}
+ ${'Route not found'} | ${'admin'} | ${'../general'} | ${false} | ${404} | ${/Not Found/}
+ ${'Route not found'} | ${'admin'} | ${'../general'} | ${'001'} | ${404} | ${/Not Found/}
+ ${'Invalid paramenters'} | ${'admin'} | ${'..%2fgeneral'} | ${'../001'} | ${400} | ${/\[request params.moduleID\]: types that failed validation:/}
+ ${'Invalid paramenters'} | ${'admin'} | ${'..%2fgeneral'} | ${'001'} | ${400} | ${/\[request params.moduleID\]: types that failed validation:/}
+ ${'Invalid paramenters'} | ${'admin'} | ${'general'} | ${'..001'} | ${400} | ${/\[request body.agents\]: types that failed validation:/}
+ ${'Invalid paramenters'} | ${'admin'} | ${'general'} | ${'../001'} | ${400} | ${/\[request body.agents\]: types that failed validation:/}
+ `(
+ `$testTitle: GET /reports/modules/$moduleID - responseStatusCode: $responseStatusCode
username: $username
agents: $agents
- responseBodyMessage: $responseBodyMessage`, async ({ username, moduleID, agents, responseStatusCode, responseBodyMessage }) => {
- const response = await supertest(innerServer.listener)
- .post(`/reports/modules/${moduleID}`)
- .set('x-test-username', username)
- .send({
- array: [],
- agents: agents,
- browserTimezone: '',
- searchBar: '',
- filters: [],
- time: {
- from: '',
- to: ''
- },
- tables: [],
- section: 'overview',
- indexPatternTitle: 'wazuh-alerts-*',
- apiId: 'default'
- })
- .expect(responseStatusCode);
- if (responseBodyMessage) {
- expect(response.body.message).toMatch(responseBodyMessage);
- };
- });
+ responseBodyMessage: $responseBodyMessage`,
+ async ({
+ username,
+ moduleID,
+ agents,
+ responseStatusCode,
+ responseBodyMessage,
+ }) => {
+ const response = await supertest(innerServer.listener)
+ .post(`/reports/modules/${moduleID}`)
+ .set('x-test-username', username)
+ .send({
+ array: [],
+ agents: agents,
+ browserTimezone: '',
+ searchBar: '',
+ filters: [],
+ time: {
+ from: '',
+ to: '',
+ },
+ tables: [],
+ section: 'overview',
+ indexPatternTitle: 'wazuh-alerts-*',
+ apiId: 'default',
+ })
+ .expect(responseStatusCode);
+ if (responseBodyMessage) {
+ expect(response.body.message).toMatch(responseBodyMessage);
+ }
+ },
+ );
});
describe('[endpoint][security] POST /reports/groups/{groupID} - Parameters validation', () => {
it.each`
- testTitle | username | groupID | responseStatusCode | responseBodyMessage
- ${'Invalid parameters'} | ${'admin'} | ${'..%2fdefault'} | ${400} | ${'[request params.groupID]: must be A-z, 0-9, _, . are allowed. It must not be ., .. or all.'}
- ${'Route not found'} | ${'admin'} | ${'../default'} | ${404} | ${/Not Found/}
- ${'Invalid parameters'} | ${'../../etc'} | ${'..%2fdefault'} | ${400} | ${'[request params.groupID]: must be A-z, 0-9, _, . are allowed. It must not be ., .. or all.'}
- ${'Route not found'} | ${'../../etc'} | ${'../default'} | ${404} | ${/Not Found/}
- `(`$testTitle: GET /reports/groups/$groupID - $responseStatusCode
+ testTitle | username | groupID | responseStatusCode | responseBodyMessage
+ ${'Invalid parameters'} | ${'admin'} | ${'..%2fdefault'} | ${400} | ${'[request params.groupID]: must be A-z, 0-9, _, . are allowed. It must not be ., .. or all.'}
+ ${'Route not found'} | ${'admin'} | ${'../default'} | ${404} | ${/Not Found/}
+ ${'Invalid parameters'} | ${'../../etc'} | ${'..%2fdefault'} | ${400} | ${'[request params.groupID]: must be A-z, 0-9, _, . are allowed. It must not be ., .. or all.'}
+ ${'Route not found'} | ${'../../etc'} | ${'../default'} | ${404} | ${/Not Found/}
+ `(
+ `$testTitle: GET /reports/groups/$groupID - $responseStatusCode
username: $username
- responseBodyMessage: $responseBodyMessage`, async ({ username, groupID, responseStatusCode, responseBodyMessage }) => {
- const response = await supertest(innerServer.listener)
- .post(`/reports/groups/${groupID}`)
- .set('x-test-username', username)
- .send({
- browserTimezone: '',
- components: { '1': true },
- section: '',
- apiId: 'default'
- })
- .expect(responseStatusCode);
- if (responseBodyMessage) {
- expect(response.body.message).toMatch(responseBodyMessage);
- };
- });
+ responseBodyMessage: $responseBodyMessage`,
+ async ({ username, groupID, responseStatusCode, responseBodyMessage }) => {
+ const response = await supertest(innerServer.listener)
+ .post(`/reports/groups/${groupID}`)
+ .set('x-test-username', username)
+ .send({
+ browserTimezone: '',
+ components: { '1': true },
+ section: '',
+ apiId: 'default',
+ })
+ .expect(responseStatusCode);
+ if (responseBodyMessage) {
+ expect(response.body.message).toMatch(responseBodyMessage);
+ }
+ },
+ );
});
describe('[endpoint][security] POST /reports/agents/{agentID} - Parameters validation', () => {
it.each`
- testTitle |username | agentID | responseStatusCode | responseBodyMessage
- ${'Invalid parameters'} | ${'admin'} | ${'..001'} | ${400} | ${/\[request params.agentID\]: must be 0-9 are allowed/}
- ${'Route not found'} | ${'admin'} | ${'../001'} | ${404} | ${/Not Found/}
- ${'Invalid parameters'} | ${'admin'} | ${'..%2f001'} | ${400} | ${/\[request params.agentID\]: must be 0-9 are allowed/}
- ${'Invalid parameters'} | ${'admin'} | ${'1'} | ${400} | ${/\[request params.agentID\]: value has length \[1\] but it must have a minimum length of \[3\]./}
- ${'Invalid parameters'} | ${'../../etc'} | ${'..001'} | ${400} | ${/\[request params.agentID\]: must be 0-9 are allowed/}
- ${'Route not found'} | ${'../../etc'} | ${'../001'} | ${404} | ${/Not Found/}
- ${'Invalid parameters'} | ${'../../etc'} | ${'..%2f001'} | ${400} | ${/\[request params.agentID\]: must be 0-9 are allowed/}
- ${'Invalid parameters'} | ${'../../etc'} | ${'1'} | ${400} | ${/\[request params.agentID\]: value has length \[1\] but it must have a minimum length of \[3\]./}
- `(`$testTitle: GET /reports/agents/$agentID - $responseStatusCode
+ testTitle | username | agentID | responseStatusCode | responseBodyMessage
+ ${'Invalid parameters'} | ${'admin'} | ${'..001'} | ${400} | ${/\[request params.agentID\]: must be 0-9 are allowed/}
+ ${'Route not found'} | ${'admin'} | ${'../001'} | ${404} | ${/Not Found/}
+ ${'Invalid parameters'} | ${'admin'} | ${'..%2f001'} | ${400} | ${/\[request params.agentID\]: must be 0-9 are allowed/}
+ ${'Invalid parameters'} | ${'admin'} | ${'1'} | ${400} | ${/\[request params.agentID\]: value has length \[1\] but it must have a minimum length of \[3\]./}
+ ${'Invalid parameters'} | ${'../../etc'} | ${'..001'} | ${400} | ${/\[request params.agentID\]: must be 0-9 are allowed/}
+ ${'Route not found'} | ${'../../etc'} | ${'../001'} | ${404} | ${/Not Found/}
+ ${'Invalid parameters'} | ${'../../etc'} | ${'..%2f001'} | ${400} | ${/\[request params.agentID\]: must be 0-9 are allowed/}
+ ${'Invalid parameters'} | ${'../../etc'} | ${'1'} | ${400} | ${/\[request params.agentID\]: value has length \[1\] but it must have a minimum length of \[3\]./}
+ `(
+ `$testTitle: GET /reports/agents/$agentID - $responseStatusCode
username: $username
- responseBodyMessage: $responseBodyMessage`, async ({ username, agentID, responseStatusCode, responseBodyMessage }) => {
- const response = await supertest(innerServer.listener)
- .post(`/reports/agents/${agentID}`)
- .set('x-test-username', username)
- .send({
- array: [],
- agents: agentID,
- browserTimezone: '',
- searchBar: '',
- filters: [],
- time: {
- from: '',
- to: ''
- },
- tables: [],
- section: 'overview',
- indexPatternTitle: 'wazuh-alerts-*',
- apiId: 'default'
- })
- .expect(responseStatusCode);
- if (responseBodyMessage) {
- expect(response.body.message).toMatch(responseBodyMessage);
- };
- });
+ responseBodyMessage: $responseBodyMessage`,
+ async ({ username, agentID, responseStatusCode, responseBodyMessage }) => {
+ const response = await supertest(innerServer.listener)
+ .post(`/reports/agents/${agentID}`)
+ .set('x-test-username', username)
+ .send({
+ array: [],
+ agents: agentID,
+ browserTimezone: '',
+ searchBar: '',
+ filters: [],
+ time: {
+ from: '',
+ to: '',
+ },
+ tables: [],
+ section: 'overview',
+ indexPatternTitle: 'wazuh-alerts-*',
+ apiId: 'default',
+ })
+ .expect(responseStatusCode);
+ if (responseBodyMessage) {
+ expect(response.body.message).toMatch(responseBodyMessage);
+ }
+ },
+ );
});
describe('[endpoint][security] POST /reports/agents/{agentID}/inventory - Parameters validation', () => {
it.each`
- testTitle | username | agentID | responseStatusCode | responseBodyMessage
- ${'Invalid parameters'} | ${'admin'} | ${'..001'} | ${400} | ${/\[request params.agentID\]: must be 0-9 are allowed/}
- ${'Route not found'} | ${'admin'} | ${'../001'} | ${404} | ${/Not Found/}
- ${'Invalid parameters'} | ${'admin'} | ${'..%2f001'} | ${400} | ${/\[request params.agentID\]: must be 0-9 are allowed/}
- ${'Invalid parameters'} | ${'admin'} | ${'1'} | ${400} | ${/\[request params.agentID\]: value has length \[1\] but it must have a minimum length of \[3\]./}
- ${'Invalid parameters'} | ${'../../etc'} | ${'..001'} | ${400} | ${/\[request params.agentID\]: must be 0-9 are allowed/}
- ${'Route not found'} | ${'../../etc'} | ${'../001'} | ${404} | ${/Not Found/}
- ${'Invalid parameters'} | ${'../../etc'} | ${'..%2f001'} | ${400} | ${/\[request params.agentID\]: must be 0-9 are allowed/}
- ${'Invalid parameters'} | ${'../../etc'} | ${'1'} | ${400} | ${/\[request params.agentID\]: value has length \[1\] but it must have a minimum length of \[3\]./}
- `(`$testTitle: GET /reports/agents/$agentID/inventory - $responseStatusCode
+ testTitle | username | agentID | responseStatusCode | responseBodyMessage
+ ${'Invalid parameters'} | ${'admin'} | ${'..001'} | ${400} | ${/\[request params.agentID\]: must be 0-9 are allowed/}
+ ${'Route not found'} | ${'admin'} | ${'../001'} | ${404} | ${/Not Found/}
+ ${'Invalid parameters'} | ${'admin'} | ${'..%2f001'} | ${400} | ${/\[request params.agentID\]: must be 0-9 are allowed/}
+ ${'Invalid parameters'} | ${'admin'} | ${'1'} | ${400} | ${/\[request params.agentID\]: value has length \[1\] but it must have a minimum length of \[3\]./}
+ ${'Invalid parameters'} | ${'../../etc'} | ${'..001'} | ${400} | ${/\[request params.agentID\]: must be 0-9 are allowed/}
+ ${'Route not found'} | ${'../../etc'} | ${'../001'} | ${404} | ${/Not Found/}
+ ${'Invalid parameters'} | ${'../../etc'} | ${'..%2f001'} | ${400} | ${/\[request params.agentID\]: must be 0-9 are allowed/}
+ ${'Invalid parameters'} | ${'../../etc'} | ${'1'} | ${400} | ${/\[request params.agentID\]: value has length \[1\] but it must have a minimum length of \[3\]./}
+ `(
+ `$testTitle: GET /reports/agents/$agentID/inventory - $responseStatusCode
username: $username
- responseBodyMessage: $responseBodyMessage`, async ({ username, agentID, responseStatusCode, responseBodyMessage }) => {
- const response = await supertest(innerServer.listener)
- .post(`/reports/agents/${agentID}/inventory`)
- .set('x-test-username', username)
- .send({
- browserTimezone: '',
- components: { '1': true },
- section: '',
- apiId: 'default'
- })
- .expect(responseStatusCode);
- if (responseBodyMessage) {
- expect(response.body.message).toMatch(responseBodyMessage);
- };
- });
+ responseBodyMessage: $responseBodyMessage`,
+ async ({ username, agentID, responseStatusCode, responseBodyMessage }) => {
+ const response = await supertest(innerServer.listener)
+ .post(`/reports/agents/${agentID}/inventory`)
+ .set('x-test-username', username)
+ .send({
+ browserTimezone: '',
+ components: { '1': true },
+ section: '',
+ apiId: 'default',
+ })
+ .expect(responseStatusCode);
+ if (responseBodyMessage) {
+ expect(response.body.message).toMatch(responseBodyMessage);
+ }
+ },
+ );
});
describe('[endpoint][security] DELETE /reports/{name} - Parameters validation', () => {
it.each`
- testTitle | username | filename | responseStatusCode | responseBodyMessage
- ${'Delete report file'} | ${'admin'} | ${'wazuh-module-overview-general-1234.pdf'} | ${200} | ${null}
- ${'Invalid parameters'} | ${'admin'} | ${'..%2fwazuh-module-overview-general-1234.pdf'} | ${400} | ${'[request params.name]: must be A-z, 0-9, _, ., and - are allowed. It must end with .pdf.'}
- ${'Invalid parameters'} | ${'admin'} | ${'custom..%2fwazuh-module-overview-general-1234.pdf'} | ${400} | ${'[request params.name]: must be A-z, 0-9, _, ., and - are allowed. It must end with .pdf.'}
- ${'Route not found'} | ${'admin'} | ${'../wazuh-module-overview-general-1234.pdf'} | ${404} | ${/Not Found/}
- ${'Delete report file'} | ${'../../etc'} | ${'wazuh-module-overview-general-1234.pdf'} | ${200} | ${null}
- ${'Invalid parameters'} | ${'../../etc'} | ${'..%2fwazuh-module-overview-general-1234.pdf'} | ${400} | ${'[request params.name]: must be A-z, 0-9, _, ., and - are allowed. It must end with .pdf.'}
- ${'Invalid parameters'} | ${'../../etc'} | ${'custom..%2fwazuh-module-overview-general-1234.pdf'} | ${400} | ${'[request params.name]: must be A-z, 0-9, _, ., and - are allowed. It must end with .pdf.'}
- ${'Route not found'} | ${'../../etc'} | ${'../wazuh-module-overview-general-1234.pdf'} | ${404} | ${/Not Found/}
- `(`$testTitle: DELETE /reports/$filename - $responseStatusCode
+ testTitle | username | filename | responseStatusCode | responseBodyMessage
+ ${'Delete report file'} | ${'admin'} | ${'wazuh-module-overview-general-1234.pdf'} | ${200} | ${null}
+ ${'Invalid parameters'} | ${'admin'} | ${'..%2fwazuh-module-overview-general-1234.pdf'} | ${400} | ${'[request params.name]: must be A-z, 0-9, _, ., and - are allowed. It must end with .pdf.'}
+ ${'Invalid parameters'} | ${'admin'} | ${'custom..%2fwazuh-module-overview-general-1234.pdf'} | ${400} | ${'[request params.name]: must be A-z, 0-9, _, ., and - are allowed. It must end with .pdf.'}
+ ${'Route not found'} | ${'admin'} | ${'../wazuh-module-overview-general-1234.pdf'} | ${404} | ${/Not Found/}
+ ${'Delete report file'} | ${'../../etc'} | ${'wazuh-module-overview-general-1234.pdf'} | ${200} | ${null}
+ ${'Invalid parameters'} | ${'../../etc'} | ${'..%2fwazuh-module-overview-general-1234.pdf'} | ${400} | ${'[request params.name]: must be A-z, 0-9, _, ., and - are allowed. It must end with .pdf.'}
+ ${'Invalid parameters'} | ${'../../etc'} | ${'custom..%2fwazuh-module-overview-general-1234.pdf'} | ${400} | ${'[request params.name]: must be A-z, 0-9, _, ., and - are allowed. It must end with .pdf.'}
+ ${'Route not found'} | ${'../../etc'} | ${'../wazuh-module-overview-general-1234.pdf'} | ${404} | ${/Not Found/}
+ `(
+ `$testTitle: DELETE /reports/$filename - $responseStatusCode
username: $username
- responseBodyMessage: $responseBodyMessage`, async ({ username, filename, responseStatusCode, responseBodyMessage }) => {
- const response = await supertest(innerServer.listener)
- .delete(`/reports/${filename}`)
- .set('x-test-username', username)
- .expect(responseStatusCode);
- if (responseBodyMessage) {
- expect(response.body.message).toMatch(responseBodyMessage);
- };
- });
-});
\ No newline at end of file
+ responseBodyMessage: $responseBodyMessage`,
+ async ({ username, filename, responseStatusCode, responseBodyMessage }) => {
+ const response = await supertest(innerServer.listener)
+ .delete(`/reports/${filename}`)
+ .set('x-test-username', username)
+ .expect(responseStatusCode);
+ if (responseBodyMessage) {
+ expect(response.body.message).toMatch(responseBodyMessage);
+ }
+ },
+ );
+});
diff --git a/plugins/main/server/controllers/wazuh-reporting.ts b/plugins/main/server/controllers/wazuh-reporting.ts
index 8084d4a00f..5c00d692b0 100644
--- a/plugins/main/server/controllers/wazuh-reporting.ts
+++ b/plugins/main/server/controllers/wazuh-reporting.ts
@@ -322,7 +322,9 @@ export class WazuhReportingCtrl {
const { from, to } = time || {};
let additionalTables = [];
// Init
- const printer = new ReportPrinter();
+ const printer = new ReportPrinter(
+ context.wazuh.logger.get('report-printer'),
+ );
createDataDirectoryIfNotExists();
createDirectoryIfNotExists(WAZUH_DATA_DOWNLOADS_DIRECTORY_PATH);
@@ -419,7 +421,9 @@ export class WazuhReportingCtrl {
const { components, apiId } = request.body;
const { groupID } = request.params;
// Init
- const printer = new ReportPrinter();
+ const printer = new ReportPrinter(
+ context.wazuh.logger.get('report-printer'),
+ );
createDataDirectoryIfNotExists();
createDirectoryIfNotExists(WAZUH_DATA_DOWNLOADS_DIRECTORY_PATH);
@@ -710,7 +714,9 @@ export class WazuhReportingCtrl {
const { components, apiId } = request.body;
const { agentID } = request.params;
- const printer = new ReportPrinter();
+ const printer = new ReportPrinter(
+ context.wazuh.logger.get('report-printer'),
+ );
createDataDirectoryIfNotExists();
createDirectoryIfNotExists(WAZUH_DATA_DOWNLOADS_DIRECTORY_PATH);
createDirectoryIfNotExists(
@@ -1054,7 +1060,9 @@ export class WazuhReportingCtrl {
const { agentID } = request.params;
const { from, to } = time || {};
// Init
- const printer = new ReportPrinter();
+ const printer = new ReportPrinter(
+ context.wazuh.logger.get('report-printer'),
+ );
const { hashUsername } = await context.wazuh.security.getCurrentUser(
request,
diff --git a/plugins/main/server/controllers/wazuh-utils/ui-logs.controller.test.ts b/plugins/main/server/controllers/wazuh-utils/ui-logs.controller.test.ts
index 8828560c61..71235b33d7 100644
--- a/plugins/main/server/controllers/wazuh-utils/ui-logs.controller.test.ts
+++ b/plugins/main/server/controllers/wazuh-utils/ui-logs.controller.test.ts
@@ -1,8 +1,21 @@
import { UiLogsCtrl } from './ui-logs.controller';
-import { WAZUH_UI_LOGS_RAW_PATH } from '../../../common/constants';
-import uiLogger from '../../lib/ui-logger';
-const readLastLines = require('read-last-lines');
+const buildMockContext = () => {
+ return {
+ wazuh: {
+ logger: {
+ get() {
+ return {
+ debug: jest.fn(),
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ };
+ },
+ },
+ },
+ };
+};
const buildMockResponse = () => {
const res = {};
@@ -19,26 +32,13 @@ const buildMockRequest = () => {
describe('Spec UiLogsCtrl', function () {
describe('Check method getUiLogs ', () => {
- it('Should 200 and return correct value', async () => {
- const result = { body: { error: 0, rawLogs: ['my test mocked'] } };
- const mockResponse = buildMockResponse();
- jest.spyOn(readLastLines, 'read').mockReturnValue('my test mocked');
- jest.spyOn(uiLogger, 'checkFileExist').mockReturnValue(true);
-
- const controller = new UiLogsCtrl();
- await controller.getUiLogs(mockResponse);
-
- expect(mockResponse.ok).toHaveBeenCalledTimes(1);
- expect(mockResponse.ok.mock.calls.length).toBe(1);
- expect(mockResponse.ok).toHaveBeenCalledWith(result);
- });
-
it('Should 200 and return message Log has been added', async () => {
- const result = { body: { error: 0, message: 'Log has been added', statusCode: 200 } };
- const mockResponse = buildMockResponse();
- jest.spyOn(readLastLines, 'read').mockReturnValue('Log has been added');
- jest.spyOn(uiLogger, 'checkFileExist').mockReturnValue(true);
+ const result = {
+ body: { error: 0, message: 'Log has been added', statusCode: 200 },
+ };
+ const mockContext = buildMockContext();
+ const mockResponse = buildMockResponse();
const mockRequest = buildMockRequest();
mockRequest.body = {
level: 'error',
@@ -47,18 +47,11 @@ describe('Spec UiLogsCtrl', function () {
};
const controller = new UiLogsCtrl();
- await controller.createUiLogs(mockRequest, mockResponse);
+ await controller.createUiLogs(mockContext, mockRequest, mockResponse);
expect(mockResponse.ok).toHaveBeenCalledTimes(1);
expect(mockResponse.ok.mock.calls.length).toBe(1);
expect(mockResponse.ok).toHaveBeenCalledWith(result);
});
-
- it('Should return a Array logs', async () => {
- const controller = new UiLogsCtrl();
- let res = await controller.getUiFileLogs(WAZUH_UI_LOGS_RAW_PATH);
-
- expect(Array.isArray(res)).toBe(true);
- });
});
});
diff --git a/plugins/main/server/controllers/wazuh-utils/ui-logs.controller.ts b/plugins/main/server/controllers/wazuh-utils/ui-logs.controller.ts
index 76afd26add..64fda22920 100644
--- a/plugins/main/server/controllers/wazuh-utils/ui-logs.controller.ts
+++ b/plugins/main/server/controllers/wazuh-utils/ui-logs.controller.ts
@@ -12,10 +12,11 @@
// Require some libraries
import { ErrorResponse } from '../../lib/error-response';
-import { read } from 'read-last-lines';
-import { WAZUH_UI_LOGS_RAW_PATH } from '../../../common/constants';
-import { OpenSearchDashboardsRequest, OpenSearchDashboardsResponseFactory } from 'src/core/server';
-import uiLogger from '../../lib/ui-logger';
+import {
+ OpenSearchDashboardsRequest,
+ OpenSearchDashboardsResponseFactory,
+ RequestHandlerContext,
+} from 'src/core/server';
export class UiLogsCtrl {
/**
@@ -25,45 +26,22 @@ export class UiLogsCtrl {
constructor() {}
/**
- * Returns Wazuh ui logs
- * @param {Object} response
- * @returns {Array} app logs or ErrorResponse
- */
- async getUiLogs(response: OpenSearchDashboardsResponseFactory) {
- try {
- return uiLogger.initDirectory().then(async () => {
- if (!uiLogger.checkFileExist(WAZUH_UI_LOGS_RAW_PATH)) {
- return response.ok({
- body: {
- error: 0,
- rawLogs: [],
- },
- });
- } else {
- let arrayLog = await this.getUiFileLogs(WAZUH_UI_LOGS_RAW_PATH);
- return response.ok({
- body: {
- error: 0,
- rawLogs: arrayLog.filter((item) => typeof item === 'string' && item.length),
- },
- });
- }
- });
- } catch (error) {
- return ErrorResponse(error.message || error, 3036, 500, response);
- }
- }
-
- /**
- * Add new UI Log entry in ui logs file
+ * Add new UI Log entry to the platform logs
+ * @param context
* @param request
* @param response
* @returns success message or ErrorResponse
*/
- async createUiLogs(request: OpenSearchDashboardsRequest, response: OpenSearchDashboardsResponseFactory) {
+ async createUiLogs(
+ context: RequestHandlerContext,
+ request: OpenSearchDashboardsRequest,
+ response: OpenSearchDashboardsResponseFactory,
+ ) {
try {
const { location, message, level } = request.body;
- await uiLogger.log(location, message, level);
+ const loggerUI = context.wazuh.logger.get('ui');
+ const loggerByLevel = loggerUI?.[level] || loggerUI.error;
+ loggerByLevel(`${location}: ${message}`);
return response.ok({
body: {
statusCode: 200,
@@ -75,18 +53,4 @@ export class UiLogsCtrl {
return ErrorResponse(error.message || error, 3021, 500, response);
}
}
-
- /**
- * Get UI logs from specific log file
- * @param filepath
- * @returns Array
- */
- async getUiFileLogs(filepath) {
- try {
- const lastLogs = await read(filepath, 50);
- return lastLogs.split('\n');
- } catch (err) {
- throw err;
- }
- }
}
diff --git a/plugins/main/server/controllers/wazuh-utils/wazuh-utils.ts b/plugins/main/server/controllers/wazuh-utils/wazuh-utils.ts
index dfaba3b656..c21cca1675 100644
--- a/plugins/main/server/controllers/wazuh-utils/wazuh-utils.ts
+++ b/plugins/main/server/controllers/wazuh-utils/wazuh-utils.ts
@@ -14,11 +14,17 @@
import { ErrorResponse } from '../../lib/error-response';
import { getConfiguration } from '../../lib/get-configuration';
import { read } from 'read-last-lines';
-import { UpdateConfigurationFile } from '../../lib/update-configuration';
import jwtDecode from 'jwt-decode';
-import { WAZUH_ROLE_ADMINISTRATOR_ID, WAZUH_DATA_LOGS_RAW_PATH, PLUGIN_SETTINGS } from '../../../common/constants';
-import { ManageHosts } from '../../lib/manage-hosts';
-import { OpenSearchDashboardsRequest, RequestHandlerContext, OpenSearchDashboardsResponseFactory } from 'src/core/server';
+import {
+ WAZUH_ROLE_ADMINISTRATOR_ID,
+ WAZUH_DATA_LOGS_RAW_PATH,
+ PLUGIN_SETTINGS,
+} from '../../../common/constants';
+import {
+ OpenSearchDashboardsRequest,
+ RequestHandlerContext,
+ OpenSearchDashboardsResponseFactory,
+} from 'src/core/server';
import { getCookieValueByName } from '../../lib/cookie';
import fs from 'fs';
import path from 'path';
@@ -26,17 +32,13 @@ import { createDirectoryIfNotExists } from '../../lib/filesystem';
import glob from 'glob';
import { getFileExtensionFromBuffer } from '../../../common/services/file-extension';
-const updateConfigurationFile = new UpdateConfigurationFile();
-
// TODO: these controllers have no logs. We should include them.
export class WazuhUtilsCtrl {
/**
* Constructor
* @param {*} server
*/
- constructor() {
- this.manageHosts = new ManageHosts();
- }
+ constructor() {}
/**
* Returns the wazuh.yml file parsed
@@ -45,7 +47,11 @@ export class WazuhUtilsCtrl {
* @param {Object} response
* @returns {Object} Configuration File or ErrorResponse
*/
- getConfigurationFile(context: RequestHandlerContext, request: OpenSearchDashboardsRequest, response: OpenSearchDashboardsResponseFactory) {
+ getConfigurationFile(
+ context: RequestHandlerContext,
+ request: OpenSearchDashboardsRequest,
+ response: OpenSearchDashboardsResponseFactory,
+ ) {
try {
const configFile = getConfiguration();
@@ -53,8 +59,8 @@ export class WazuhUtilsCtrl {
body: {
statusCode: 200,
error: 0,
- data: configFile || {}
- }
+ data: configFile || {},
+ },
});
} catch (error) {
return ErrorResponse(error.message || error, 3019, 500, response);
@@ -68,35 +74,74 @@ export class WazuhUtilsCtrl {
* @param {Object} response
* @returns {Object} Configuration File or ErrorResponse
*/
- updateConfigurationFile = this.routeDecoratorProtectedAdministratorRoleValidToken(
- async (context: RequestHandlerContext, request: OpenSearchDashboardsRequest, response: OpenSearchDashboardsResponseFactory) => {
-
- let requiresRunningHealthCheck: boolean = false,
- requiresReloadingBrowserTab: boolean = false,
- requiresRestartingPluginPlatform: boolean = false;
+ updateConfigurationFile =
+ this.routeDecoratorProtectedAdministratorRoleValidToken(
+ async (
+ context: RequestHandlerContext,
+ request: OpenSearchDashboardsRequest,
+ response: OpenSearchDashboardsResponseFactory,
+ ) => {
+ let requiresRunningHealthCheck: boolean = false,
+ requiresReloadingBrowserTab: boolean = false,
+ requiresRestartingPluginPlatform: boolean = false;
- // Plugin settings configurables in the configuration file.
- const pluginSettingsConfigurableFile = Object.keys(request.body)
- .filter(pluginSettingKey => PLUGIN_SETTINGS[pluginSettingKey].isConfigurableFromFile)
- .reduce((accum, pluginSettingKey: string) => ({ ...accum, [pluginSettingKey]: request.body[pluginSettingKey] }), {});
+ // Plugin settings configurables in the configuration file.
+ const pluginSettingsConfigurableFile = Object.keys(request.body)
+ .filter(
+ pluginSettingKey =>
+ PLUGIN_SETTINGS[pluginSettingKey].isConfigurableFromFile,
+ )
+ .reduce(
+ (accum, pluginSettingKey: string) => ({
+ ...accum,
+ [pluginSettingKey]: request.body[pluginSettingKey],
+ }),
+ {},
+ );
- if (Object.keys(pluginSettingsConfigurableFile).length) {
- // Update the configuration file.
- await updateConfigurationFile.updateConfiguration(pluginSettingsConfigurableFile);
+ if (Object.keys(pluginSettingsConfigurableFile).length) {
+ // Update the configuration file.
+ await context.wazuh_core.updateConfigurationFile.updateConfiguration(
+ pluginSettingsConfigurableFile,
+ );
- requiresRunningHealthCheck = Object.keys(pluginSettingsConfigurableFile).some((pluginSettingKey: string) => Boolean(PLUGIN_SETTINGS[pluginSettingKey].requiresRunningHealthCheck)) || requiresRunningHealthCheck;
- requiresReloadingBrowserTab = Object.keys(pluginSettingsConfigurableFile).some((pluginSettingKey: string) => Boolean(PLUGIN_SETTINGS[pluginSettingKey].requiresReloadingBrowserTab)) || requiresReloadingBrowserTab;
- requiresRestartingPluginPlatform = Object.keys(pluginSettingsConfigurableFile).some((pluginSettingKey: string) => Boolean(PLUGIN_SETTINGS[pluginSettingKey].requiresRestartingPluginPlatform)) || requiresRestartingPluginPlatform;
- };
-
- return response.ok({
- body: {
- data: { requiresRunningHealthCheck, requiresReloadingBrowserTab, requiresRestartingPluginPlatform, updatedConfiguration: pluginSettingsConfigurableFile }
+ requiresRunningHealthCheck =
+ Object.keys(pluginSettingsConfigurableFile).some(
+ (pluginSettingKey: string) =>
+ Boolean(
+ PLUGIN_SETTINGS[pluginSettingKey].requiresRunningHealthCheck,
+ ),
+ ) || requiresRunningHealthCheck;
+ requiresReloadingBrowserTab =
+ Object.keys(pluginSettingsConfigurableFile).some(
+ (pluginSettingKey: string) =>
+ Boolean(
+ PLUGIN_SETTINGS[pluginSettingKey].requiresReloadingBrowserTab,
+ ),
+ ) || requiresReloadingBrowserTab;
+ requiresRestartingPluginPlatform =
+ Object.keys(pluginSettingsConfigurableFile).some(
+ (pluginSettingKey: string) =>
+ Boolean(
+ PLUGIN_SETTINGS[pluginSettingKey]
+ .requiresRestartingPluginPlatform,
+ ),
+ ) || requiresRestartingPluginPlatform;
}
- });
- },
- 3021
- )
+
+ return response.ok({
+ body: {
+ data: {
+ requiresRunningHealthCheck,
+ requiresReloadingBrowserTab,
+ requiresRestartingPluginPlatform,
+ updatedConfiguration: pluginSettingsConfigurableFile,
+ },
+ },
+ });
+ },
+ 3021,
+ );
/**
* Returns Wazuh app logs
@@ -105,22 +150,23 @@ export class WazuhUtilsCtrl {
* @param {Object} response
* @returns {Array} app logs or ErrorResponse
*/
- async getAppLogs(context: RequestHandlerContext, request: OpenSearchDashboardsRequest, response: OpenSearchDashboardsResponseFactory) {
+ async getAppLogs(
+ context: RequestHandlerContext,
+ request: OpenSearchDashboardsRequest,
+ response: OpenSearchDashboardsResponseFactory,
+ ) {
try {
- const lastLogs = await read(
- WAZUH_DATA_LOGS_RAW_PATH,
- 50
- );
+ const lastLogs = await read(WAZUH_DATA_LOGS_RAW_PATH, 50);
const spliterLog = lastLogs.split('\n');
return spliterLog && Array.isArray(spliterLog)
? response.ok({
- body: {
- error: 0,
- lastLogs: spliterLog.filter(
- item => typeof item === 'string' && item.length
- )
- }
- })
+ body: {
+ error: 0,
+ lastLogs: spliterLog.filter(
+ item => typeof item === 'string' && item.length,
+ ),
+ },
+ })
: response.ok({ error: 0, lastLogs: [] });
} catch (error) {
return ErrorResponse(error.message || error, 3036, 500, response);
@@ -135,7 +181,11 @@ export class WazuhUtilsCtrl {
* @returns {Object} Configuration File or ErrorResponse
*/
uploadFile = this.routeDecoratorProtectedAdministratorRoleValidToken(
- async (context: RequestHandlerContext, request: KibanaRequest, response: KibanaResponseFactory) => {
+ async (
+ context: RequestHandlerContext,
+ request: KibanaRequest,
+ response: KibanaResponseFactory,
+ ) => {
const { key } = request.params;
const { file: bufferFile } = request.body;
const pluginSetting = PLUGIN_SETTINGS[key];
@@ -144,16 +194,24 @@ export class WazuhUtilsCtrl {
const fileExtension = getFileExtensionFromBuffer(bufferFile);
// Check if the extension is valid for the setting.
- if (!pluginSetting.options.file.extensions.includes(`.${fileExtension}`)) {
+ if (
+ !pluginSetting.options.file.extensions.includes(`.${fileExtension}`)
+ ) {
return response.badRequest({
- body: `File extension is not valid for setting [${key}] setting. Allowed file extensions: ${pluginSetting.options.file.extensions.join(', ')}`
+ body: `File extension is not valid for setting [${key}] setting. Allowed file extensions: ${pluginSetting.options.file.extensions.join(
+ ', ',
+ )}`,
});
- };
+ }
const fileNamePath = `${key}.${fileExtension}`;
// Create target directory
- const targetDirectory = path.join(__dirname, '../../..', pluginSetting.options.file.store.relativePathFileSystem);
+ const targetDirectory = path.join(
+ __dirname,
+ '../../..',
+ pluginSetting.options.file.store.relativePathFileSystem,
+ );
createDirectoryIfNotExists(targetDirectory);
// Get the files related to the setting and remove them
const files = glob.sync(path.join(targetDirectory, `${key}.*`));
@@ -163,24 +221,33 @@ export class WazuhUtilsCtrl {
fs.writeFileSync(path.join(targetDirectory, fileNamePath), bufferFile);
// Update the setting in the configuration cache
- const pluginSettingValue = pluginSetting.options.file.store.resolveStaticURL(fileNamePath);
- await updateConfigurationFile.updateConfiguration({ [key]: pluginSettingValue });
+ const pluginSettingValue =
+ pluginSetting.options.file.store.resolveStaticURL(fileNamePath);
+ await context.wazuh_core.updateConfigurationFile.updateConfiguration({
+ [key]: pluginSettingValue,
+ });
return response.ok({
body: {
data: {
- requiresRunningHealthCheck: Boolean(pluginSetting.requiresRunningHealthCheck),
- requiresReloadingBrowserTab: Boolean(pluginSetting.requiresReloadingBrowserTab),
- requiresRestartingPluginPlatform: Boolean(pluginSetting.requiresRestartingPluginPlatform),
+ requiresRunningHealthCheck: Boolean(
+ pluginSetting.requiresRunningHealthCheck,
+ ),
+ requiresReloadingBrowserTab: Boolean(
+ pluginSetting.requiresReloadingBrowserTab,
+ ),
+ requiresRestartingPluginPlatform: Boolean(
+ pluginSetting.requiresRestartingPluginPlatform,
+ ),
updatedConfiguration: {
- [key]: pluginSettingValue
- }
- }
- }
+ [key]: pluginSettingValue,
+ },
+ },
+ },
});
},
- 3022
- )
+ 3022,
+ );
/**
* Delete a file
@@ -190,64 +257,96 @@ export class WazuhUtilsCtrl {
* @returns {Object} Configuration File or ErrorResponse
*/
deleteFile = this.routeDecoratorProtectedAdministratorRoleValidToken(
- async (context: RequestHandlerContext, request: KibanaRequest, response: KibanaResponseFactory) => {
+ async (
+ context: RequestHandlerContext,
+ request: KibanaRequest,
+ response: KibanaResponseFactory,
+ ) => {
const { key } = request.params;
const pluginSetting = PLUGIN_SETTINGS[key];
// Get the files related to the setting and remove them
- const targetDirectory = path.join(__dirname, '../../..', pluginSetting.options.file.store.relativePathFileSystem);
+ const targetDirectory = path.join(
+ __dirname,
+ '../../..',
+ pluginSetting.options.file.store.relativePathFileSystem,
+ );
const files = glob.sync(path.join(targetDirectory, `${key}.*`));
files.forEach(fs.unlinkSync);
// Update the setting in the configuration cache
const pluginSettingValue = pluginSetting.defaultValue;
- await updateConfigurationFile.updateConfiguration({ [key]: pluginSettingValue });
+ await context.wazuh_core.updateConfigurationFile.updateConfiguration({
+ [key]: pluginSettingValue,
+ });
return response.ok({
body: {
- message: 'All files were removed and the configuration file was updated.',
+ message:
+ 'All files were removed and the configuration file was updated.',
data: {
- requiresRunningHealthCheck: Boolean(pluginSetting.requiresRunningHealthCheck),
- requiresReloadingBrowserTab: Boolean(pluginSetting.requiresReloadingBrowserTab),
- requiresRestartingPluginPlatform: Boolean(pluginSetting.requiresRestartingPluginPlatform),
+ requiresRunningHealthCheck: Boolean(
+ pluginSetting.requiresRunningHealthCheck,
+ ),
+ requiresReloadingBrowserTab: Boolean(
+ pluginSetting.requiresReloadingBrowserTab,
+ ),
+ requiresRestartingPluginPlatform: Boolean(
+ pluginSetting.requiresRestartingPluginPlatform,
+ ),
updatedConfiguration: {
- [key]: pluginSettingValue
- }
- }
- }
+ [key]: pluginSettingValue,
+ },
+ },
+ },
});
},
- 3023
- )
+ 3023,
+ );
- private routeDecoratorProtectedAdministratorRoleValidToken(routeHandler, errorCode: number) {
+ private routeDecoratorProtectedAdministratorRoleValidToken(
+ routeHandler,
+ errorCode: number,
+ ) {
return async (context, request, response) => {
try {
// Check if user has administrator role in token
const token = getCookieValueByName(request.headers.cookie, 'wz-token');
if (!token) {
return ErrorResponse('No token provided', 401, 401, response);
- };
+ }
const decodedToken = jwtDecode(token);
if (!decodedToken) {
return ErrorResponse('No permissions in token', 401, 401, response);
- };
- if (!decodedToken.rbac_roles || !decodedToken.rbac_roles.includes(WAZUH_ROLE_ADMINISTRATOR_ID)) {
+ }
+ if (
+ !decodedToken.rbac_roles ||
+ !decodedToken.rbac_roles.includes(WAZUH_ROLE_ADMINISTRATOR_ID)
+ ) {
return ErrorResponse('No administrator role', 401, 401, response);
- };
+ }
// Check the provided token is valid
- const apiHostID = getCookieValueByName(request.headers.cookie, 'wz-api');
+ const apiHostID = getCookieValueByName(
+ request.headers.cookie,
+ 'wz-api',
+ );
if (!apiHostID) {
return ErrorResponse('No API id provided', 401, 401, response);
- };
- const responseTokenIsWorking = await context.wazuh.api.client.asCurrentUser.request('GET', '/', {}, { apiHostID });
+ }
+ const responseTokenIsWorking =
+ await context.wazuh.api.client.asCurrentUser.request(
+ 'GET',
+ '/',
+ {},
+ { apiHostID },
+ );
if (responseTokenIsWorking.status !== 200) {
return ErrorResponse('Token is not valid', 401, 401, response);
- };
- return await routeHandler(context, request, response)
+ }
+ return await routeHandler(context, request, response);
} catch (error) {
return ErrorResponse(error.message || error, errorCode, 500, response);
}
- }
+ };
}
}
diff --git a/plugins/main/server/lib/api-interceptor.ts b/plugins/main/server/lib/api-interceptor.ts
deleted file mode 100644
index 256eaede05..0000000000
--- a/plugins/main/server/lib/api-interceptor.ts
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Wazuh app - Interceptor API entries
- * Copyright (C) 2015-2022 Wazuh, Inc.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Find more information about this on the LICENSE file.
- */
-
-import axios, { AxiosResponse } from 'axios';
-import { ManageHosts } from './manage-hosts';
-import https from 'https';
-
-const httpsAgent = new https.Agent({
- rejectUnauthorized: false,
-});
-
-const _axios = axios.create({ httpsAgent });
-
-interface APIHost{
- url: string
- port: string
- username: string
- password: string
-}
-
-export interface APIInterceptorRequestOptions{
- apiHostID: string
- token: string
- forceRefresh?: boolean
-}
-
-export interface APIInterceptorRequestOptionsInternalUser{
- apiHostID: string
- forceRefresh?: boolean
-}
-
-const manageHosts = new ManageHosts();
-
-// Cache to save the token for the internal user by API host ID
-const CacheInternalUserAPIHostToken = new Map();
-
-export const authenticate = async (apiHostID: string, authContext?: any): Promise => {
- try{
- const api: APIHost = await manageHosts.getHostById(apiHostID);
- const optionsRequest = {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- },
- auth: {
- username: api.username,
- password: api.password,
- },
- url: `${api.url}:${api.port}/security/user/authenticate${!!authContext ? '/run_as' : ''}`,
- ...(!!authContext ? { data: authContext } : {})
- };
-
- const response: AxiosResponse = await _axios(optionsRequest);
- const token: string = (((response || {}).data || {}).data || {}).token;
- if (!authContext) {
- CacheInternalUserAPIHostToken.set(apiHostID, token);
- };
- return token;
- }catch(error){
- throw error;
- }
-};
-
-const buildRequestOptions = async (method: string, path: string, data: any, { apiHostID, forceRefresh, token }: APIInterceptorRequestOptions) => {
- const api = await manageHosts.getHostById(apiHostID);
- const { body, params, headers, ...rest } = data;
- return {
- method: method,
- headers: {
- 'content-type': 'application/json',
- Authorization: 'Bearer ' + token,
- ...(headers ? headers : {})
- },
- data: body || rest || {},
- params: params || {},
- url: `${api.url}:${api.port}${path}`,
- }
-}
-
-export const requestAsInternalUser = async (method: string, path: string, data: any, options: APIInterceptorRequestOptionsInternalUser) => {
- try{
- const token = CacheInternalUserAPIHostToken.has(options.apiHostID) && !options.forceRefresh
- ? CacheInternalUserAPIHostToken.get(options.apiHostID)
- : await authenticate(options.apiHostID);
- return await request(method, path, data, {...options, token});
- }catch(error){
- if (error.response && error.response.status === 401) {
- try{
- const token: string = await authenticate(options.apiHostID);
- return await request(method, path, data, {...options, token});
- }catch(error){
- throw error;
- }
- }
- throw error;
- }
-};
-
-export const requestAsCurrentUser = async (method: string, path: string, data: any, options: APIInterceptorRequestOptions) => {
- return await request(method, path, data, options)
-};
-
-const request = async (method: string, path: string, data: any, options: any): Promise => {
- try{
- const optionsRequest = await buildRequestOptions(method, path, data, options);
- const response: AxiosResponse = await _axios(optionsRequest);
- return response;
- }catch(error){
- throw error;
- }
-};
diff --git a/plugins/main/server/lib/base-logger.ts b/plugins/main/server/lib/base-logger.ts
deleted file mode 100644
index cfc6d4f2b1..0000000000
--- a/plugins/main/server/lib/base-logger.ts
+++ /dev/null
@@ -1,257 +0,0 @@
-/*
- * Wazuh app - Settings controller
- * Copyright (C) 2015-2022 Wazuh, Inc.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Find more information about this on the LICENSE file.
- */
-
-import winston from 'winston';
-import fs from 'fs';
-import path from 'path';
-import { getConfiguration } from './get-configuration';
-import { createDataDirectoryIfNotExists, createLogFileIfNotExists } from './filesystem';
-
-import { WAZUH_DATA_LOGS_DIRECTORY_PATH, MAX_MB_LOG_FILES } from '../../common/constants';
-
-export interface IUIPlainLoggerSettings {
- level: string;
- message?: string;
- data?: any;
-}
-
-export interface IUILoggerSettings extends IUIPlainLoggerSettings {
- date: Date;
- location: string;
-}
-
-export class BaseLogger {
- allowed: boolean = false;
- wazuhLogger: winston.Logger | undefined = undefined;
- wazuhPlainLogger: winston.Logger | undefined = undefined;
- PLAIN_LOGS_PATH: string = '';
- PLAIN_LOGS_FILE_NAME: string = '';
- RAW_LOGS_PATH: string = '';
- RAW_LOGS_FILE_NAME: string = '';
-
- constructor(plainLogsFile: string, rawLogsFile: string) {
- this.PLAIN_LOGS_PATH = path.join(WAZUH_DATA_LOGS_DIRECTORY_PATH, plainLogsFile);
- this.RAW_LOGS_PATH = path.join(WAZUH_DATA_LOGS_DIRECTORY_PATH, rawLogsFile);
- this.PLAIN_LOGS_FILE_NAME = plainLogsFile;
- this.RAW_LOGS_FILE_NAME = rawLogsFile;
- }
-
- /**
- * Initialize loggers, plain and raw logger
- */
- private initLogger = () => {
- const configurationFile = getConfiguration();
- const level =
- typeof (configurationFile || {})['logs.level'] !== 'undefined' &&
- ['info', 'debug'].includes(configurationFile['logs.level'])
- ? configurationFile['logs.level']
- : 'info';
-
- // JSON logger
- this.wazuhLogger = winston.createLogger({
- level,
- format: winston.format.json(),
- transports: [
- new winston.transports.File({
- filename: this.RAW_LOGS_PATH,
- }),
- ],
- });
-
- // Prevents from exit on error related to the logger.
- this.wazuhLogger.exitOnError = false;
-
- // Plain text logger
- this.wazuhPlainLogger = winston.createLogger({
- level,
- format: winston.format.simple(),
- transports: [
- new winston.transports.File({
- filename: this.PLAIN_LOGS_PATH,
- }),
- ],
- });
-
- // Prevents from exit on error related to the logger.
- this.wazuhPlainLogger.exitOnError = false;
- };
-
- /**
- * Checks if wazuh/logs exists. If it doesn't exist, it will be created.
- */
- initDirectory = async () => {
- try {
- createDataDirectoryIfNotExists();
- createDataDirectoryIfNotExists('logs');
- if (typeof this.wazuhLogger === 'undefined' || typeof this.wazuhPlainLogger === 'undefined') {
- this.initLogger();
- }
- this.allowed = true;
- return;
- } catch (error) {
- this.allowed = false;
- return Promise.reject(error);
- }
- };
-
- /**
- * Returns given file size in MB, if the file doesn't exist returns 0
- * @param {*} filename Path to the file
- */
- getFilesizeInMegaBytes = (filename) => {
- if (this.allowed) {
- if (fs.existsSync(filename)) {
- const stats = fs.statSync(filename);
- const fileSizeInMegaBytes = stats.size;
-
- return fileSizeInMegaBytes / 1000000.0;
- }
- }
- return 0;
- };
-
- /**
- * Check if file exist
- * @param filename
- * @returns boolean
- */
- checkFileExist = (filename) => {
- return fs.existsSync(filename);
- };
-
- rotateFiles = (file: string, pathFile: string, log?: string) => {
- if (this.getFilesizeInMegaBytes(pathFile) >= MAX_MB_LOG_FILES) {
- const fileExtension = path.extname(file);
- const fileName = path.basename(file, fileExtension);
- fs.renameSync(
- pathFile,
- `${WAZUH_DATA_LOGS_DIRECTORY_PATH}/${fileName}-${new Date().getTime()}${fileExtension}`
- );
- if (log) {
- fs.writeFileSync(pathFile, log + '\n');
- }
- }
- };
-
- /**
- * Checks if the wazuhapp.log file size is greater than 100MB, if so it rotates the file.
- */
- private checkFiles = () => {
- createLogFileIfNotExists(this.RAW_LOGS_PATH);
- createLogFileIfNotExists(this.PLAIN_LOGS_PATH);
- if (this.allowed) {
- // check raw log file
- this.rotateFiles(
- this.RAW_LOGS_FILE_NAME,
- this.RAW_LOGS_PATH,
- JSON.stringify({
- date: new Date(),
- level: 'info',
- location: 'logger',
- message: 'Rotated log file',
- })
- );
- // check log file
- this.rotateFiles(this.PLAIN_LOGS_FILE_NAME, this.PLAIN_LOGS_PATH);
- }
- };
-
- /**
- * Get Current Date
- * @returns string
- */
- private yyyymmdd = () => {
- const now = new Date();
- const y = now.getFullYear();
- const m = now.getMonth() + 1;
- const d = now.getDate();
- const seconds = now.getSeconds();
- const minutes = now.getMinutes();
- const hour = now.getHours();
- return `${y}/${m < 10 ? '0' : ''}${m}/${d < 10 ? '0' : ''}${d} ${hour}:${minutes}:${seconds}`;
- };
-
- /**
- * This function filter some known interfaces to avoid log hug objects
- * @param data string | object
- * @returns the data parsed
- */
- private parseData = (data: any) => {
- let parsedData =
- data instanceof Error
- ? {
- message: data.message,
- stack: data.stack,
- }
- : data;
-
- // when error is AxiosError, it extends from Error
- if (data.isAxiosError) {
- const { config } = data;
- parsedData = {
- ...parsedData,
- config: {
- url: config.url,
- method: config.method,
- data: config.data,
- params: config.params,
- },
- };
- }
-
- if (typeof parsedData === 'object') parsedData.toString = () => JSON.stringify(parsedData);
-
- return parsedData;
- };
-
- /**
- * Main function to add a new log
- * @param {*} location File where the log is being thrown
- * @param {*} data Message or object to log
- * @param {*} level Optional, default is 'error'
- */
- async log(location: string, data: any, level: string) {
- const parsedData = this.parseData(data);
- return this.initDirectory()
- .then(() => {
- if (this.allowed) {
- this.checkFiles();
- const plainLogData: IUIPlainLoggerSettings = {
- level: level || 'error',
- message: `${this.yyyymmdd()}: ${location || 'Unknown origin'}: ${
- parsedData.toString() || 'An error occurred'
- }`,
- };
-
- this.wazuhPlainLogger.log(plainLogData);
-
- const logData: IUILoggerSettings = {
- date: new Date(),
- level: level || 'error',
- location: location || 'Unknown origin',
- data: parsedData || 'An error occurred',
- };
-
- if (typeof data == 'string') {
- logData.message = parsedData;
- delete logData.data;
- }
-
- this.wazuhLogger.log(logData);
- }
- })
- .catch((error) => {
- console.error(`Cannot create the logs directory due to:\n${error.message || error}`);
- throw error;
- });
- }
-}
diff --git a/plugins/main/server/lib/cache-api-user-has-run-as.ts b/plugins/main/server/lib/cache-api-user-has-run-as.ts
deleted file mode 100644
index 725ec3771b..0000000000
--- a/plugins/main/server/lib/cache-api-user-has-run-as.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Wazuh app - Service which caches the API user allow run as
- * Copyright (C) 2015-2022 Wazuh, Inc.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Find more information about this on the LICENSE file.
- */
-import * as ApiInterceptor from './api-interceptor';
-import { ManageHosts } from './manage-hosts';
-import { log } from './logger';
-// Private variable to save the cache
-const _cache = {};
-
-// Export an interface which interacts with the private cache object
-export const CacheInMemoryAPIUserAllowRunAs = {
- // Set an entry with API ID, username and allow_run_as
- set: (apiID: string, username: string, allow_run_as : number): void => {
- if(!_cache[apiID]){
- _cache[apiID] = {}; // Create a API ID entry if it doesn't exist in cache object
- };
- _cache[apiID][username] = allow_run_as;
- },
- // Get the value of an entry with API ID and username from cache
- get: (apiID: string, username: string): number => _cache[apiID] && typeof _cache[apiID][username] !== 'undefined' ? _cache[apiID][username] : API_USER_STATUS_RUN_AS.ALL_DISABLED,
- // Check if it exists the API ID and username in the cache
- has: (apiID: string, username: string): boolean => _cache[apiID] && typeof _cache[apiID][username] !== 'undefined' ? true : false
-};
-
-const manageHosts = new ManageHosts();
-
-export const APIUserAllowRunAs = {
- async check(apiId: string): Promise{
- try{
- const api = await manageHosts.getHostById(apiId);
- log('APIUserAllowRunAs:check', `Check if API user ${api.username} (${apiId}) has run_as`, 'debug');
- // Check if api.run_as is false or undefined, then it set to false in cache
- if(!api.run_as){
- CacheInMemoryAPIUserAllowRunAs.set(apiId, api.username, API_USER_STATUS_RUN_AS.HOST_DISABLED);
- };
- // Check if the API user is cached and returns it
- if(CacheInMemoryAPIUserAllowRunAs.has(apiId, api.username)){
- return CacheInMemoryAPIUserAllowRunAs.get(apiId, api.username);
- };
- const response = await ApiInterceptor.requestAsInternalUser(
- 'get',
- '/security/users/me',
- {},
- { apiHostID: apiId }
- );
- const statusUserAllowRunAs = response.data.data.affected_items[0].allow_run_as ? API_USER_STATUS_RUN_AS.ENABLED : API_USER_STATUS_RUN_AS.USER_NOT_ALLOWED;
-
- // Cache the run_as for the API user
- CacheInMemoryAPIUserAllowRunAs.set(apiId, api.username, statusUserAllowRunAs);
- return statusUserAllowRunAs;
- }catch(error){
- log('APIUserAllowRunAs:check', error.message || error);
- return API_USER_STATUS_RUN_AS.ALL_DISABLED;
- }
- },
- async canUse(apiId: string): Promise{
- const ApiUserCanUseStatus = await APIUserAllowRunAs.check(apiId);
- if(ApiUserCanUseStatus === API_USER_STATUS_RUN_AS.USER_NOT_ALLOWED){
- const api = await manageHosts.getHostById(apiId);
- throw new Error(`API with host ID [${apiId}] misconfigured. The Wazuh API user [${api.username}] is not allowed to use [run_as]. Allow it in the user configuration or set [run_as] host setting with [false] value.`);
- }
- return ApiUserCanUseStatus;
- }
-};
-
-/**
- * @example
- * HOST = set in wazuh.yml config
- * USER = set in user interface
- *
- * ALL_DISABLED
- * binary 00 = decimal 0 ---> USER 0 y HOST 0
- *
- * USER_NOT_ALLOWED
- * binary 01 = decimal 1 ---> USER 0 y HOST 1
- *
- * HOST_DISABLED
- * binary 10 = decimal 2 ---> USER 1 y HOST 0
- *
- * ENABLED
- * binary 11 = decimal 3 ---> USER 1 y HOST 1
- */
-export enum API_USER_STATUS_RUN_AS{
- ALL_DISABLED = 0, // Wazuh HOST and USER API user configured with run_as=false or undefined
- USER_NOT_ALLOWED = 1, // Wazuh HOST API user configured with run_as = TRUE in wazuh.yml but it has not run_as in Wazuh API
- HOST_DISABLED = 2, // Wazuh HOST API user configured with run_as=false in wazuh.yml but it has not run_as in Wazuh API
- ENABLED = 3 // Wazuh API user configured with run_as=true and allow run_as
-}
diff --git a/plugins/main/server/lib/logger.ts b/plugins/main/server/lib/logger.ts
deleted file mode 100644
index c21394e4c4..0000000000
--- a/plugins/main/server/lib/logger.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Wazuh app - Module for logging functions
- * Copyright (C) 2015-2022 Wazuh, Inc.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Find more information about this on the LICENSE file.
- */
-import { BaseLogger } from './base-logger';
-import {
- WAZUH_DATA_LOGS_PLAIN_FILENAME,
- WAZUH_DATA_LOGS_RAW_FILENAME,
-} from '../../common/constants';
-
-const logger = new BaseLogger(WAZUH_DATA_LOGS_PLAIN_FILENAME, WAZUH_DATA_LOGS_RAW_FILENAME);
-
-export const log = (location, message, level) => {
- logger.log(location, message, level);
-};
diff --git a/plugins/main/server/lib/manage-hosts.ts b/plugins/main/server/lib/manage-hosts.ts
deleted file mode 100644
index 65959623eb..0000000000
--- a/plugins/main/server/lib/manage-hosts.ts
+++ /dev/null
@@ -1,387 +0,0 @@
-/*
- * Wazuh app - Module to update the configuration file
- * Copyright (C) 2015-2022 Wazuh, Inc.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Find more information about this on the LICENSE file.
- */
-import fs from 'fs';
-import yml from 'js-yaml';
-import { log } from './logger';
-import { UpdateRegistry } from './update-registry';
-import { initialWazuhConfig } from './initial-wazuh-config';
-import { WAZUH_DATA_CONFIG_APP_PATH } from '../../common/constants';
-import { createDataDirectoryIfNotExists } from '../lib/filesystem';
-
-export class ManageHosts {
- busy: boolean;
- file: string;
- updateRegistry: UpdateRegistry;
- initialConfig: string;
- constructor() {
- this.busy = false;
- this.file = WAZUH_DATA_CONFIG_APP_PATH;
- this.updateRegistry = new UpdateRegistry();
- this.initialConfig = initialWazuhConfig;
- }
-
- /**
- * Composes the host structure
- * @param {Object} host
- * @param {String} id
- */
- composeHost(host, id) {
- try {
- log('manage-hosts:composeHost', 'Composing host', 'debug');
- return ` - ${!id ? new Date().getTime() : id}:
- url: ${host.url}
- port: ${host.port}
- username: ${host.username || host.user}
- password: ${host.password}`;
- } catch (error) {
- log('manage-hosts:composeHost', error.message || error);
- throw error;
- }
- }
-
- /**
- * Regex to build the host
- * @param {Object} host
- */
- composeRegex(host) {
- try {
- const hostId = Object.keys(host)[0];
- const reg = `\\s*-\\s*${hostId}\\s*:\\s*\\n*\\s*url\\s*:\\s*\\S*\\s*\\n*\\s*port\\s*:\\s*\\S*\\s*\\n*\\s*username\\s*:\\s*\\S*\\s*\\n*\\s*password\\s*:\\s*\\S*`;
- log('manage-hosts:composeRegex', 'Composing regex', 'debug');
- return new RegExp(`${reg}`, 'gm');
- } catch (error) {
- log('manage-hosts:composeRegex', error.message || error);
- throw error;
- }
- }
-
- /**
- * Returns the hosts in the wazuh.yml
- */
- async getHosts() {
- try {
- this.checkBusy();
- this.busy = true;
- createDataDirectoryIfNotExists();
- createDataDirectoryIfNotExists('config');
- if (!fs.existsSync(WAZUH_DATA_CONFIG_APP_PATH)) {
- await fs.writeFileSync(this.file, this.initialConfig, {
- encoding: 'utf8',
- mode: 0o600,
- });
- }
- const raw = fs.readFileSync(this.file, { encoding: 'utf-8' });
- this.busy = false;
- const content = yml.load(raw);
- log('manage-hosts:getHosts', 'Getting hosts', 'debug');
- const entries = (content || {})['hosts'] || [];
- return entries;
- } catch (error) {
- this.busy = false;
- log('manage-hosts:getHosts', error.message || error);
- return Promise.reject(error);
- }
- }
-
- /**
- * This function checks if the hosts: key exists in the wazuh.yml for preventing duplicate in case of there's not any host defined
- */
- async checkIfHostsKeyExists() {
- try {
- log('manage-hosts:checkIfHostsKeyExists', 'Checking hosts key', 'debug');
- this.busy = true;
- const raw = fs.readFileSync(this.file, { encoding: 'utf-8' });
- this.busy = false;
- const content = yml.load(raw);
- return Object.keys(content || {}).includes('hosts');
- } catch (error) {
- log('manage-hosts:checkIfHostsKeyExists', error.message || error);
- this.busy = false;
- return Promise.reject(error);
- }
- }
-
- /**
- * Returns the IDs of the current hosts in the wazuh.yml
- */
- async getCurrentHostsIds() {
- try {
- const hosts = await this.getHosts();
- const ids = hosts.map(h => {
- return Object.keys(h)[0];
- });
- log('manage-hosts:getCurrentHostsIds', 'Getting hosts ids', 'debug');
- return ids;
- } catch (error) {
- log('manage-hosts:getCurrentHostsIds', error.message || error);
- return Promise.reject(error);
- }
- }
-
- /**
- * Get host by id
- * @param {String} id
- */
- async getHostById(id) {
- try {
- log('manage-hosts:getHostById', `Getting host ${id}`, 'debug');
- const hosts = await this.getHosts();
- const host = hosts.filter(h => {
- return Object.keys(h)[0] == id;
- });
- if (host && !host.length) {
- throw new Error('Selected API is no longer available in wazuh.yml');
- }
- const key = Object.keys(host[0])[0];
- const result = Object.assign(host[0][key], { id: key }) || {};
- return result;
- } catch (error) {
- log('manage-hosts:getHostById', error.message || error);
- return Promise.reject(error);
- }
- }
-
- /**
- * Decodes the API password
- * @param {String} password
- */
- decodeApiPassword(password) {
- return Buffer.from(password, 'base64').toString('ascii');
- }
-
- /**
- * Iterate the array with the API entries in given from the .wazuh index in order to create a valid array
- * @param {Object} apiEntries
- */
- transformIndexedApis(apiEntries) {
- const entries = [];
- try {
- apiEntries.map(entry => {
- const id = entry._id;
- const host = entry._source;
- const api = {
- id: id,
- url: host.url,
- port: host.api_port,
- username: host.api_username,
- password: this.decodeApiPassword(host.api_password),
- cluster_info: host.cluster_info,
- };
- entries.push(api);
- });
- log(
- 'manage-hosts:transformIndexedApis',
- 'Transforming index API schedule to wazuh.yml',
- 'debug',
- );
- } catch (error) {
- log('manage-hosts:transformIndexedApis', error.message || error);
- throw error;
- }
- return entries;
- }
-
- /**
- * Calls transformIndexedApis() to get the entries to migrate and after that calls addSeveralHosts()
- * @param {Object} apiEntries
- */
- async migrateFromIndex(apiEntries) {
- try {
- const apis = this.transformIndexedApis(apiEntries);
- return await this.addSeveralHosts(apis);
- } catch (error) {
- log('manage-hosts:migrateFromIndex', error.message || error);
- return Promise.reject(error);
- }
- }
-
- /**
- * Receives an array of hosts and checks if any host is already in the wazuh.yml, in this case is removed from the received array and returns the resulting array
- * @param {Array} hosts
- */
- async cleanExistingHosts(hosts) {
- try {
- const currentHosts = await this.getCurrentHostsIds();
- const cleanHosts = hosts.filter(h => {
- return !currentHosts.includes(h.id);
- });
- log(
- 'manage-hosts:cleanExistingHosts',
- 'Preventing add existings hosts',
- 'debug',
- );
- return cleanHosts;
- } catch (error) {
- log('manage-hosts:cleanExistingHosts', error.message || error);
- return Promise.reject(error);
- }
- }
-
- /**
- * Throws an error is the wazuh.yml is busy
- */
- checkBusy() {
- if (this.busy)
- throw new Error('Another process is writting the configuration file');
- }
-
- /**
- * Recursive function used to add several APIs entries
- * @param {Array} hosts
- */
- async addSeveralHosts(hosts) {
- try {
- log('manage-hosts:addSeveralHosts', 'Adding several', 'debug');
- const hostsToAdd = await this.cleanExistingHosts(hosts);
- if (!hostsToAdd.length) return 'There are not APIs entries to migrate';
- for (let idx in hostsToAdd) {
- const entry = hostsToAdd[idx];
- await this.addHost(entry);
- }
- return 'All APIs entries were migrated to the wazuh.yml';
- } catch (error) {
- log('manage-hosts:addSeveralHosts', error.message || error);
- return Promise.reject(error);
- }
- }
-
- /**
- * Add a single host
- * @param {Obeject} host
- */
- async addHost(host) {
- const id = host.id || new Date().getTime();
- const compose = this.composeHost(host, id);
- let data = await fs.readFileSync(this.file, { encoding: 'utf-8' });
- try {
- this.checkBusy();
- const hosts = (await this.getHosts()) || [];
- this.busy = true;
- if (!hosts.length) {
- const hostsExists = await this.checkIfHostsKeyExists();
- const result = !hostsExists
- ? `${data}\nhosts:\n${compose}\n`
- : `${data}\n${compose}\n`;
- await fs.writeFileSync(this.file, result, 'utf8');
- } else {
- const lastHost = (hosts || []).pop();
- if (lastHost) {
- const lastHostObject = this.composeHost(
- lastHost[Object.keys(lastHost)[0]],
- Object.keys(lastHost)[0],
- );
- const regex = this.composeRegex(lastHost);
- const replace = data.replace(
- regex,
- `\n${lastHostObject}\n${compose}\n`,
- );
- await fs.writeFileSync(this.file, replace, 'utf8');
- }
- }
- this.busy = false;
- this.updateRegistry.migrateToRegistry(
- id,
- host.cluster_info,
- );
- log('manage-hosts:addHost', `Host ${id} was properly added`, 'debug');
- return id;
- } catch (error) {
- this.busy = false;
- log('manage-hosts:addHost', error.message || error);
- return Promise.reject(error);
- }
- }
-
- /**
- * Delete a host from the wazuh.yml
- * @param {Object} req
- */
- async deleteHost(req) {
- let data = await fs.readFileSync(this.file, { encoding: 'utf-8' });
- try {
- this.checkBusy();
- const hosts = (await this.getHosts()) || [];
- this.busy = true;
- if (!hosts.length) {
- throw new Error('There are not configured hosts.');
- } else {
- const hostsNumber = hosts.length;
- const target = (hosts || []).find(element => {
- return Object.keys(element)[0] === req.params.id;
- });
- if (!target) {
- throw new Error(`Host ${req.params.id} not found.`);
- }
- const regex = this.composeRegex(target);
- const result = data.replace(regex, ``);
- await fs.writeFileSync(this.file, result, 'utf8');
- if (hostsNumber === 1) {
- data = await fs.readFileSync(this.file, { encoding: 'utf-8' });
- const clearHosts = data.replace(
- new RegExp(`hosts:\\s*[\\n\\r]`, 'gm'),
- '',
- );
- await fs.writeFileSync(this.file, clearHosts, 'utf8');
- }
- }
- this.busy = false;
- log(
- 'manage-hosts:deleteHost',
- `Host ${req.params.id} was properly deleted`,
- 'debug',
- );
- return true;
- } catch (error) {
- this.busy = false;
- log('manage-hosts:deleteHost', error.message || error);
- return Promise.reject(error);
- }
- }
-
- /**
- * Updates the hosts information
- * @param {String} id
- * @param {Object} host
- */
- async updateHost(id, host) {
- let data = await fs.readFileSync(this.file, { encoding: 'utf-8' });
- try {
- this.checkBusy();
- const hosts = (await this.getHosts()) || [];
- this.busy = true;
- if (!hosts.length) {
- throw new Error('There are not configured hosts.');
- } else {
- const target = (hosts || []).find(element => {
- return Object.keys(element)[0] === id;
- });
- if (!target) {
- throw new Error(`Host ${id} not found.`);
- }
- const regex = this.composeRegex(target);
- const result = data.replace(regex, `\n${this.composeHost(host, id)}`);
- await fs.writeFileSync(this.file, result, 'utf8');
- }
- this.busy = false;
- log(
- 'manage-hosts:updateHost',
- `Host ${id} was properly updated`,
- 'debug',
- );
- return true;
- } catch (error) {
- this.busy = false;
- log('manage-hosts:updateHost', error.message || error);
- return Promise.reject(error);
- }
- }
-}
diff --git a/plugins/main/server/lib/parse-cron.ts b/plugins/main/server/lib/parse-cron.ts
index 5330e065d2..45927118e7 100644
--- a/plugins/main/server/lib/parse-cron.ts
+++ b/plugins/main/server/lib/parse-cron.ts
@@ -9,7 +9,6 @@
*
* Find more information about this on the LICENSE file.
*/
-import { log } from './logger';
import cron from 'node-cron';
import { WAZUH_MONITORING_DEFAULT_CRON_FREQ } from '../../common/constants';
@@ -17,34 +16,30 @@ export function parseCron(interval: string) {
try {
if (!interval) throw new Error('Interval not found');
- const intervalToNumber = parseInt(interval);
+ const intervalToNumber: number = parseInt(interval);
- if (!intervalToNumber || typeof intervalToNumber !== 'number'){
+ if (!intervalToNumber || typeof intervalToNumber !== 'number') {
throw new Error('Interval not valid');
- };
- if (intervalToNumber < 60){ // 60 seconds / 1 minute
+ }
+ if (intervalToNumber < 60) {
+ // 60 seconds / 1 minute
throw new Error('Interval too low');
- };
- if (intervalToNumber >= 84600){
+ }
+ if (intervalToNumber >= 84600) {
throw new Error('Interval too high');
- }
+ }
const minutes = parseInt(intervalToNumber / 60);
const cronstr = `0 */${minutes} * * * *`;
- if (!cron.validate(cronstr)){
+ if (!cron.validate(cronstr)) {
throw new Error(
- 'Generated cron expression not valid for node-cron module'
+ 'Generated cron expression not valid for node-cron module',
);
}
- log('cron:parse-interval', `Using the next interval: ${cronstr}`, 'debug');
return cronstr;
} catch (error) {
- log(
- 'cron:parse-interval',
- `Using default value ${WAZUH_MONITORING_DEFAULT_CRON_FREQ} due to: ${error.message || error}`
- );
return WAZUH_MONITORING_DEFAULT_CRON_FREQ;
}
}
diff --git a/plugins/main/server/lib/reporting/extended-information.ts b/plugins/main/server/lib/reporting/extended-information.ts
index 377ba9408c..ffb0b8f89d 100644
--- a/plugins/main/server/lib/reporting/extended-information.ts
+++ b/plugins/main/server/lib/reporting/extended-information.ts
@@ -1,4 +1,3 @@
-import { log } from '../logger';
import SummaryTable from './summary-table';
import summaryTablesDefinitions from './summary-tables-definitions';
import * as VulnerabilityRequest from './vulnerability-request';
@@ -16,33 +15,41 @@ import { ReportPrinter } from './printer';
import moment from 'moment';
import { getSettingDefaultValue } from '../../../common/services/settings';
-
-
-
/**
- * This build the agents table
- * @param {Array} ids ids of agents
- * @param {String} apiId API id
- */
-export async function buildAgentsTable(context, printer: ReportPrinter, agentIDs: string[], apiId: string, groupID: string = '') {
+ * This build the agents table
+ * @param {Array} ids ids of agents
+ * @param {String} apiId API id
+ */
+export async function buildAgentsTable(
+ context,
+ printer: ReportPrinter,
+ agentIDs: string[],
+ apiId: string,
+ groupID: string = '',
+) {
const dateFormat = await context.core.uiSettings.client.get('dateFormat');
if ((!agentIDs || !agentIDs.length) && !groupID) return;
- log('reporting:buildAgentsTable', `${agentIDs.length} agents for API ${apiId}`, 'info');
+ printer.logger.debug(`${agentIDs.length} agents for API ${apiId}`);
try {
let agentsData = [];
if (groupID) {
let totalAgentsInGroup = null;
do {
- const { data: { data: { affected_items, total_affected_items } } } = await context.wazuh.api.client.asCurrentUser.request(
+ const {
+ data: {
+ data: { affected_items, total_affected_items },
+ },
+ } = await context.wazuh.api.client.asCurrentUser.request(
'GET',
`/groups/${groupID}/agents`,
{
params: {
offset: agentsData.length,
- select: 'dateAdd,id,ip,lastKeepAlive,manager,name,os.name,os.version,version',
- }
+ select:
+ 'dateAdd,id,ip,lastKeepAlive,manager,name,os.name,os.version,version',
+ },
},
- { apiHostID: apiId }
+ { apiHostID: apiId },
);
!totalAgentsInGroup && (totalAgentsInGroup = total_affected_items);
agentsData = [...agentsData, ...affected_items];
@@ -50,24 +57,27 @@ export async function buildAgentsTable(context, printer: ReportPrinter, agentIDs
} else {
for (const agentID of agentIDs) {
try {
- const { data: { data: { affected_items: [agent] } } } = await context.wazuh.api.client.asCurrentUser.request(
+ const {
+ data: {
+ data: {
+ affected_items: [agent],
+ },
+ },
+ } = await context.wazuh.api.client.asCurrentUser.request(
'GET',
`/agents`,
{
params: {
q: `id=${agentID}`,
- select: 'dateAdd,id,ip,lastKeepAlive,manager,name,os.name,os.version,version',
- }
+ select:
+ 'dateAdd,id,ip,lastKeepAlive,manager,name,os.name,os.version,version',
+ },
},
- { apiHostID: apiId }
+ { apiHostID: apiId },
);
agentsData.push(agent);
} catch (error) {
- log(
- 'reporting:buildAgentsTable',
- `Skip agent due to: ${error.message || error}`,
- 'debug'
- );
+ printer.logger.debug(`Skip agent due to: ${error.message || error}`);
}
}
}
@@ -87,13 +97,16 @@ export async function buildAgentsTable(context, printer: ReportPrinter, agentIDs
],
items: agentsData
.filter(agent => agent) // Remove undefined agents when Wazuh API no longer finds and agentID
- .map((agent) => {
+ .map(agent => {
return {
...agent,
- os: (agent.os && agent.os.name && agent.os.version) ? `${agent.os.name} ${agent.os.version}` : '',
+ os:
+ agent.os && agent.os.name && agent.os.version
+ ? `${agent.os.name} ${agent.os.version}`
+ : '',
lastKeepAlive: moment(agent.lastKeepAlive).format(dateFormat),
- dateAdd: moment(agent.dateAdd).format(dateFormat)
- }
+ dateAdd: moment(agent.dateAdd).format(dateFormat),
+ };
}),
});
} else if (!agentsData.length && groupID) {
@@ -103,9 +116,8 @@ export async function buildAgentsTable(context, printer: ReportPrinter, agentIDs
style: { fontSize: 12, color: '#000' },
});
}
-
} catch (error) {
- log('reporting:buildAgentsTable', error.message || error);
+ printer.logger.error(error.message || error);
return Promise.reject(error);
}
}
@@ -138,36 +150,34 @@ export async function extendedInformation(
agent = null,
) {
try {
- log(
- 'reporting:extendedInformation',
- `Section ${section} and tab ${tab}, API is ${apiId}. From ${from} to ${to}. Filters ${JSON.stringify(filters)}. Index pattern ${pattern}`,
- 'info'
+ printer.logger.debug(
+ `Section ${section} and tab ${tab}, API is ${apiId}. From ${from} to ${to}. Filters ${JSON.stringify(
+ filters,
+ )}. Index pattern ${pattern}`,
);
if (section === 'agents' && !agent) {
- throw new Error('Reporting for specific agent needs an agent ID in order to work properly');
+ throw new Error(
+ 'Reporting for specific agent needs an agent ID in order to work properly',
+ );
}
const agents = await context.wazuh.api.client.asCurrentUser.request(
'GET',
'/agents',
{ params: { limit: 1 } },
- { apiHostID: apiId }
+ { apiHostID: apiId },
);
const totalAgents = agents.data.data.total_affected_items;
//--- OVERVIEW - VULS
if (section === 'overview' && tab === 'vuls') {
- log(
- 'reporting:extendedInformation',
- 'Fetching overview vulnerability detector metrics',
- 'debug'
- );
+ printer.logger.debug('Fetching overview vulnerability detector metrics');
const vulnerabilitiesLevels = ['Low', 'Medium', 'High', 'Critical'];
const vulnerabilitiesResponsesCount = (
await Promise.all(
- vulnerabilitiesLevels.map(async (vulnerabilitiesLevel) => {
+ vulnerabilitiesLevels.map(async vulnerabilitiesLevel => {
try {
const count = await VulnerabilityRequest.uniqueSeverityCount(
context,
@@ -176,25 +186,23 @@ export async function extendedInformation(
vulnerabilitiesLevel,
filters,
allowedAgentsFilter,
- pattern
+ pattern,
);
return count
? `${count} of ${totalAgents} agents have ${vulnerabilitiesLevel.toLocaleLowerCase()} vulnerabilities.`
: undefined;
- } catch (error) { }
- })
+ } catch (error) {}
+ }),
)
- ).filter((vulnerabilitiesResponse) => vulnerabilitiesResponse);
+ ).filter(vulnerabilitiesResponse => vulnerabilitiesResponse);
printer.addList({
title: { text: 'Summary', style: 'h2' },
list: vulnerabilitiesResponsesCount,
});
- log(
- 'reporting:extendedInformation',
+ printer.logger.debug(
'Fetching overview vulnerability detector top 3 agents by category',
- 'debug'
);
const lowRank = await VulnerabilityRequest.topAgentCount(
context,
@@ -203,7 +211,7 @@ export async function extendedInformation(
'Low',
filters,
allowedAgentsFilter,
- pattern
+ pattern,
);
const mediumRank = await VulnerabilityRequest.topAgentCount(
context,
@@ -212,7 +220,7 @@ export async function extendedInformation(
'Medium',
filters,
allowedAgentsFilter,
- pattern
+ pattern,
);
const highRank = await VulnerabilityRequest.topAgentCount(
context,
@@ -221,7 +229,7 @@ export async function extendedInformation(
'High',
filters,
allowedAgentsFilter,
- pattern
+ pattern,
);
const criticalRank = await VulnerabilityRequest.topAgentCount(
context,
@@ -230,12 +238,10 @@ export async function extendedInformation(
'Critical',
filters,
allowedAgentsFilter,
- pattern
+ pattern,
);
- log(
- 'reporting:extendedInformation',
+ printer.logger.debug(
'Adding overview vulnerability detector top 3 agents by category',
- 'debug'
);
if (criticalRank && criticalRank.length) {
printer.addContentWithNewLine({
@@ -273,17 +279,18 @@ export async function extendedInformation(
printer.addNewLine();
}
- log(
- 'reporting:extendedInformation',
+ printer.logger.debug(
'Fetching overview vulnerability detector top 3 CVEs',
- 'debug'
);
- const cveRank = await VulnerabilityRequest.topCVECount(context, from, to, filters, allowedAgentsFilter, pattern);
- log(
- 'reporting:extendedInformation',
- 'Adding overview vulnerability detector top 3 CVEs',
- 'debug'
+ const cveRank = await VulnerabilityRequest.topCVECount(
+ context,
+ from,
+ to,
+ filters,
+ allowedAgentsFilter,
+ pattern,
);
+ printer.logger.debug('Adding overview vulnerability detector top 3 CVEs');
if (cveRank && cveRank.length) {
printer.addSimpleTable({
title: { text: 'Top 3 CVE', style: 'h2' },
@@ -291,18 +298,28 @@ export async function extendedInformation(
{ id: 'top', label: 'Top' },
{ id: 'cve', label: 'CVE' },
],
- items: cveRank.map((item) => ({ top: cveRank.indexOf(item) + 1, cve: item })),
+ items: cveRank.map(item => ({
+ top: cveRank.indexOf(item) + 1,
+ cve: item,
+ })),
});
}
}
//--- OVERVIEW - GENERAL
if (section === 'overview' && tab === 'general') {
- log('reporting:extendedInformation', 'Fetching top 3 agents with level 15 alerts', 'debug');
+ printer.logger.debug('Fetching top 3 agents with level 15 alerts');
- const level15Rank = await OverviewRequest.topLevel15(context, from, to, filters, allowedAgentsFilter, pattern);
+ const level15Rank = await OverviewRequest.topLevel15(
+ context,
+ from,
+ to,
+ filters,
+ allowedAgentsFilter,
+ pattern,
+ );
- log('reporting:extendedInformation', 'Adding top 3 agents with level 15 alerts', 'debug');
+ printer.logger.debug('Adding top 3 agents with level 15 alerts');
if (level15Rank.length) {
printer.addContent({
text: 'Top 3 agents with level 15 alerts',
@@ -314,16 +331,16 @@ export async function extendedInformation(
//--- OVERVIEW - PM
if (section === 'overview' && tab === 'pm') {
- log('reporting:extendedInformation', 'Fetching most common rootkits', 'debug');
+ printer.logger.debug('Fetching most common rootkits');
const top5RootkitsRank = await RootcheckRequest.top5RootkitsDetected(
context,
from,
to,
filters,
allowedAgentsFilter,
- pattern
+ pattern,
);
- log('reporting:extendedInformation', 'Adding most common rootkits', 'debug');
+ printer.logger.debug('Adding most common rootkits');
if (top5RootkitsRank && top5RootkitsRank.length) {
printer
.addContentWithNewLine({
@@ -331,12 +348,11 @@ export async function extendedInformation(
style: 'h2',
})
.addContentWithNewLine({
- text:
- 'Rootkits are a set of software tools that enable an unauthorized user to gain control of a computer system without being detected.',
+ text: 'Rootkits are a set of software tools that enable an unauthorized user to gain control of a computer system without being detected.',
style: 'standard',
})
.addSimpleTable({
- items: top5RootkitsRank.map((item) => {
+ items: top5RootkitsRank.map(item => {
return { top: top5RootkitsRank.indexOf(item) + 1, name: item };
}),
columns: [
@@ -345,14 +361,14 @@ export async function extendedInformation(
],
});
}
- log('reporting:extendedInformation', 'Fetching hidden pids', 'debug');
+ printer.logger.debug('Fetching hidden pids');
const hiddenPids = await RootcheckRequest.agentsWithHiddenPids(
context,
from,
to,
filters,
allowedAgentsFilter,
- pattern
+ pattern,
);
hiddenPids &&
printer.addContent({
@@ -371,7 +387,7 @@ export async function extendedInformation(
to,
filters,
allowedAgentsFilter,
- pattern
+ pattern,
);
hiddenPorts &&
printer.addContent({
@@ -388,14 +404,14 @@ export async function extendedInformation(
//--- OVERVIEW/AGENTS - PCI
if (['overview', 'agents'].includes(section) && tab === 'pci') {
- log('reporting:extendedInformation', 'Fetching top PCI DSS requirements', 'debug');
+ printer.logger.debug('Fetching top PCI DSS requirements');
const topPciRequirements = await PCIRequest.topPCIRequirements(
context,
from,
to,
filters,
allowedAgentsFilter,
- pattern
+ pattern,
);
printer.addContentWithNewLine({
text: 'Most common PCI DSS requirements alerts found',
@@ -409,13 +425,18 @@ export async function extendedInformation(
filters,
allowedAgentsFilter,
item,
- pattern
+ pattern,
);
- printer.addContentWithNewLine({ text: `Requirement ${item}`, style: 'h3' });
+ printer.addContentWithNewLine({
+ text: `Requirement ${item}`,
+ style: 'h3',
+ });
if (PCI[item]) {
const content =
- typeof PCI[item] === 'string' ? { text: PCI[item], style: 'standard' } : PCI[item];
+ typeof PCI[item] === 'string'
+ ? { text: PCI[item], style: 'standard' }
+ : PCI[item];
printer.addContentWithNewLine(content);
}
@@ -434,14 +455,14 @@ export async function extendedInformation(
//--- OVERVIEW/AGENTS - TSC
if (['overview', 'agents'].includes(section) && tab === 'tsc') {
- log('reporting:extendedInformation', 'Fetching top TSC requirements', 'debug');
+ printer.logger.debug('Fetching top TSC requirements');
const topTSCRequirements = await TSCRequest.topTSCRequirements(
context,
from,
to,
filters,
allowedAgentsFilter,
- pattern
+ pattern,
);
printer.addContentWithNewLine({
text: 'Most common TSC requirements alerts found',
@@ -455,13 +476,18 @@ export async function extendedInformation(
filters,
allowedAgentsFilter,
item,
- pattern
+ pattern,
);
- printer.addContentWithNewLine({ text: `Requirement ${item}`, style: 'h3' });
+ printer.addContentWithNewLine({
+ text: `Requirement ${item}`,
+ style: 'h3',
+ });
if (TSC[item]) {
const content =
- typeof TSC[item] === 'string' ? { text: TSC[item], style: 'standard' } : TSC[item];
+ typeof TSC[item] === 'string'
+ ? { text: TSC[item], style: 'standard' }
+ : TSC[item];
printer.addContentWithNewLine(content);
}
@@ -480,14 +506,14 @@ export async function extendedInformation(
//--- OVERVIEW/AGENTS - GDPR
if (['overview', 'agents'].includes(section) && tab === 'gdpr') {
- log('reporting:extendedInformation', 'Fetching top GDPR requirements', 'debug');
+ printer.logger.debug('Fetching top GDPR requirements');
const topGdprRequirements = await GDPRRequest.topGDPRRequirements(
context,
from,
to,
filters,
allowedAgentsFilter,
- pattern
+ pattern,
);
printer.addContentWithNewLine({
text: 'Most common GDPR requirements alerts found',
@@ -501,13 +527,18 @@ export async function extendedInformation(
filters,
allowedAgentsFilter,
item,
- pattern
+ pattern,
);
- printer.addContentWithNewLine({ text: `Requirement ${item}`, style: 'h3' });
+ printer.addContentWithNewLine({
+ text: `Requirement ${item}`,
+ style: 'h3',
+ });
if (GDPR && GDPR[item]) {
const content =
- typeof GDPR[item] === 'string' ? { text: GDPR[item], style: 'standard' } : GDPR[item];
+ typeof GDPR[item] === 'string'
+ ? { text: GDPR[item], style: 'standard' }
+ : GDPR[item];
printer.addContentWithNewLine(content);
}
@@ -527,19 +558,18 @@ export async function extendedInformation(
//--- OVERVIEW - AUDIT
if (section === 'overview' && tab === 'audit') {
- log(
- 'reporting:extendedInformation',
+ printer.logger.debug(
'Fetching agents with high number of failed sudo commands',
- 'debug'
- );
- const auditAgentsNonSuccess = await AuditRequest.getTop3AgentsSudoNonSuccessful(
- context,
- from,
- to,
- filters,
- allowedAgentsFilter,
- pattern
);
+ const auditAgentsNonSuccess =
+ await AuditRequest.getTop3AgentsSudoNonSuccessful(
+ context,
+ from,
+ to,
+ filters,
+ allowedAgentsFilter,
+ pattern,
+ );
if (auditAgentsNonSuccess && auditAgentsNonSuccess.length) {
printer.addContent({
text: 'Agents with high number of failed sudo commands',
@@ -547,14 +577,15 @@ export async function extendedInformation(
});
await buildAgentsTable(context, printer, auditAgentsNonSuccess, apiId);
}
- const auditAgentsFailedSyscall = await AuditRequest.getTop3AgentsFailedSyscalls(
- context,
- from,
- to,
- filters,
- allowedAgentsFilter,
- pattern
- );
+ const auditAgentsFailedSyscall =
+ await AuditRequest.getTop3AgentsFailedSyscalls(
+ context,
+ from,
+ to,
+ filters,
+ allowedAgentsFilter,
+ pattern,
+ );
if (auditAgentsFailedSyscall && auditAgentsFailedSyscall.length) {
printer.addSimpleTable({
columns: [
@@ -562,7 +593,7 @@ export async function extendedInformation(
{ id: 'syscall_id', label: 'Syscall ID' },
{ id: 'syscall_syscall', label: 'Syscall' },
],
- items: auditAgentsFailedSyscall.map((item) => ({
+ items: auditAgentsFailedSyscall.map(item => ({
agent: item.agent,
syscall_id: item.syscall.id,
syscall_syscall: item.syscall.syscall,
@@ -577,25 +608,41 @@ export async function extendedInformation(
//--- OVERVIEW - FIM
if (section === 'overview' && tab === 'fim') {
- log('reporting:extendedInformation', 'Fetching top 3 rules for FIM', 'debug');
- const rules = await SyscheckRequest.top3Rules(context, from, to, filters, allowedAgentsFilter, pattern);
+ printer.logger.debug('Fetching top 3 rules for FIM');
+ const rules = await SyscheckRequest.top3Rules(
+ context,
+ from,
+ to,
+ filters,
+ allowedAgentsFilter,
+ pattern,
+ );
if (rules && rules.length) {
- printer.addContentWithNewLine({ text: 'Top 3 FIM rules', style: 'h2' }).addSimpleTable({
- columns: [
- { id: 'ruleID', label: 'Rule ID' },
- { id: 'ruleDescription', label: 'Description' },
- ],
- items: rules,
- title: {
- text: 'Top 3 rules that are generating most alerts.',
- style: 'standard',
- },
- });
+ printer
+ .addContentWithNewLine({ text: 'Top 3 FIM rules', style: 'h2' })
+ .addSimpleTable({
+ columns: [
+ { id: 'ruleID', label: 'Rule ID' },
+ { id: 'ruleDescription', label: 'Description' },
+ ],
+ items: rules,
+ title: {
+ text: 'Top 3 rules that are generating most alerts.',
+ style: 'standard',
+ },
+ });
}
- log('reporting:extendedInformation', 'Fetching top 3 agents for FIM', 'debug');
- const agents = await SyscheckRequest.top3agents(context, from, to, filters, allowedAgentsFilter, pattern);
+ printer.logger.debug('Fetching top 3 agents for FIM');
+ const agents = await SyscheckRequest.top3agents(
+ context,
+ from,
+ to,
+ filters,
+ allowedAgentsFilter,
+ pattern,
+ );
if (agents && agents.length) {
printer.addContentWithNewLine({
@@ -603,8 +650,7 @@ export async function extendedInformation(
style: 'h2',
});
printer.addContentWithNewLine({
- text:
- 'Top 3 agents that have most FIM alerts from level 7 to level 15. Take care about them.',
+ text: 'Top 3 agents that have most FIM alerts from level 7 to level 15. Take care about them.',
style: 'standard',
});
await buildAgentsTable(context, printer, agents, apiId);
@@ -613,14 +659,14 @@ export async function extendedInformation(
//--- AGENTS - AUDIT
if (section === 'agents' && tab === 'audit') {
- log('reporting:extendedInformation', `Fetching most common failed syscalls`, 'debug');
+ printer.logger.debug('Fetching most common failed syscalls');
const auditFailedSyscall = await AuditRequest.getTopFailedSyscalls(
context,
from,
to,
filters,
allowedAgentsFilter,
- pattern
+ pattern,
);
auditFailedSyscall &&
auditFailedSyscall.length &&
@@ -636,18 +682,15 @@ export async function extendedInformation(
//--- AGENTS - FIM
if (section === 'agents' && tab === 'fim') {
- log(
- 'reporting:extendedInformation',
- `Fetching syscheck database for agent ${agent}`,
- 'debug'
- );
+ printer.logger.debug(`Fetching syscheck database for agent ${agent}`);
- const lastScanResponse = await context.wazuh.api.client.asCurrentUser.request(
- 'GET',
- `/syscheck/${agent}/last_scan`,
- {},
- { apiHostID: apiId }
- );
+ const lastScanResponse =
+ await context.wazuh.api.client.asCurrentUser.request(
+ 'GET',
+ `/syscheck/${agent}/last_scan`,
+ {},
+ { apiHostID: apiId },
+ );
if (lastScanResponse && lastScanResponse.data) {
const lastScanData = lastScanResponse.data.data.affected_items[0];
@@ -667,14 +710,14 @@ export async function extendedInformation(
printer.addNewLine();
}
- log('reporting:extendedInformation', `Fetching last 10 deleted files for FIM`, 'debug');
+ printer.logger.debug('Fetching last 10 deleted files for FIM');
const lastTenDeleted = await SyscheckRequest.lastTenDeletedFiles(
context,
from,
to,
filters,
allowedAgentsFilter,
- pattern
+ pattern,
);
lastTenDeleted &&
@@ -688,14 +731,14 @@ export async function extendedInformation(
title: 'Last 10 deleted files',
});
- log('reporting:extendedInformation', `Fetching last 10 modified files`, 'debug');
+ printer.logger.debug('Fetching last 10 modified files');
const lastTenModified = await SyscheckRequest.lastTenModifiedFiles(
context,
from,
to,
filters,
allowedAgentsFilter,
- pattern
+ pattern,
);
lastTenModified &&
@@ -712,11 +755,7 @@ export async function extendedInformation(
//--- AGENTS - SYSCOLLECTOR
if (section === 'agents' && tab === 'syscollector') {
- log(
- 'reporting:extendedInformation',
- `Fetching hardware information for agent ${agent}`,
- 'debug'
- );
+ printer.logger.debug(`Fetching hardware information for agent ${agent}`);
const requestsSyscollectorLists = [
{
endpoint: `/syscollector/${agent}/hardware`,
@@ -724,12 +763,12 @@ export async function extendedInformation(
list: {
title: { text: 'Hardware information', style: 'h2' },
},
- mapResponse: (hardware) => [
+ mapResponse: hardware => [
hardware.cpu && hardware.cpu.cores && `${hardware.cpu.cores} cores`,
hardware.cpu && hardware.cpu.name,
hardware.ram &&
- hardware.ram.total &&
- `${Number(hardware.ram.total / 1024 / 1024).toFixed(2)}GB RAM`,
+ hardware.ram.total &&
+ `${Number(hardware.ram.total / 1024 / 1024).toFixed(2)}GB RAM`,
],
},
{
@@ -738,29 +777,30 @@ export async function extendedInformation(
list: {
title: { text: 'Operating system information', style: 'h2' },
},
- mapResponse: (osData) => [
+ mapResponse: osData => [
osData.sysname,
osData.version,
osData.architecture,
osData.release,
osData.os &&
- osData.os.name &&
- osData.os.version &&
- `${osData.os.name} ${osData.os.version}`,
+ osData.os.name &&
+ osData.os.version &&
+ `${osData.os.name} ${osData.os.version}`,
],
},
];
const syscollectorLists = await Promise.all(
- requestsSyscollectorLists.map(async (requestSyscollector) => {
+ requestsSyscollectorLists.map(async requestSyscollector => {
try {
- log('reporting:extendedInformation', requestSyscollector.loggerMessage, 'debug');
- const responseSyscollector = await context.wazuh.api.client.asCurrentUser.request(
- 'GET',
- requestSyscollector.endpoint,
- {},
- { apiHostID: apiId }
- );
+ printer.logger.debug(requestSyscollector.loggerMessage);
+ const responseSyscollector =
+ await context.wazuh.api.client.asCurrentUser.request(
+ 'GET',
+ requestSyscollector.endpoint,
+ {},
+ { apiHostID: apiId },
+ );
const [data] =
(responseSyscollector &&
responseSyscollector.data &&
@@ -774,27 +814,25 @@ export async function extendedInformation(
};
}
} catch (error) {
- log('reporting:extendedInformation', error.message || error);
+ printer.logger.error(error.message || error);
}
- })
+ }),
);
if (syscollectorLists) {
syscollectorLists
- .filter((syscollectorList) => syscollectorList)
- .forEach((syscollectorList) => printer.addList(syscollectorList));
+ .filter(syscollectorList => syscollectorList)
+ .forEach(syscollectorList => printer.addList(syscollectorList));
}
const vulnerabilitiesRequests = ['Critical', 'High'];
const vulnerabilitiesResponsesItems = (
await Promise.all(
- vulnerabilitiesRequests.map(async (vulnerabilitiesLevel) => {
+ vulnerabilitiesRequests.map(async vulnerabilitiesLevel => {
try {
- log(
- 'reporting:extendedInformation',
+ printer.logger.debug(
`Fetching top ${vulnerabilitiesLevel} packages`,
- 'debug'
);
return await VulnerabilityRequest.topPackages(
@@ -804,20 +842,26 @@ export async function extendedInformation(
vulnerabilitiesLevel,
filters,
allowedAgentsFilter,
- pattern
+ pattern,
);
} catch (error) {
- log('reporting:extendedInformation', error.message || error);
+ printer.logger.error(error.message || error);
}
- })
+ }),
)
)
- .filter((vulnerabilitiesResponse) => vulnerabilitiesResponse)
+ .filter(vulnerabilitiesResponse => vulnerabilitiesResponse)
.flat();
- if (vulnerabilitiesResponsesItems && vulnerabilitiesResponsesItems.length) {
+ if (
+ vulnerabilitiesResponsesItems &&
+ vulnerabilitiesResponsesItems.length
+ ) {
printer.addSimpleTable({
- title: { text: 'Vulnerable packages found (last 24 hours)', style: 'h2' },
+ title: {
+ text: 'Vulnerable packages found (last 24 hours)',
+ style: 'h2',
+ },
columns: [
{ id: 'package', label: 'Package' },
{ id: 'severity', label: 'Severity' },
@@ -836,20 +880,22 @@ export async function extendedInformation(
'Critical',
filters,
allowedAgentsFilter,
- pattern
+ pattern,
);
if (topCriticalPackages && topCriticalPackages.length) {
- printer.addContentWithNewLine({ text: 'Critical severity', style: 'h2' });
printer.addContentWithNewLine({
- text:
- 'These vulnerabilties are critical, please review your agent. Click on each link to read more about each found vulnerability.',
+ text: 'Critical severity',
+ style: 'h2',
+ });
+ printer.addContentWithNewLine({
+ text: 'These vulnerabilties are critical, please review your agent. Click on each link to read more about each found vulnerability.',
style: 'standard',
});
const customul = [];
for (const critical of topCriticalPackages) {
customul.push({ text: critical.package, style: 'standard' });
customul.push({
- ul: critical.references.map((item) => ({
+ ul: critical.references.map(item => ({
text: item.substring(0, 80) + '...',
link: item,
color: '#1EA5C8',
@@ -866,7 +912,7 @@ export async function extendedInformation(
'High',
filters,
allowedAgentsFilter,
- pattern
+ pattern,
);
if (topHighPackages && topHighPackages.length) {
printer.addContentWithNewLine({ text: 'High severity', style: 'h2' });
@@ -878,7 +924,7 @@ export async function extendedInformation(
for (const critical of topHighPackages) {
customul.push({ text: critical.package, style: 'standard' });
customul.push({
- ul: critical.references.map((item) => ({
+ ul: critical.references.map(item => ({
text: item,
color: '#1EA5C8',
})),
@@ -892,25 +938,27 @@ export async function extendedInformation(
//--- SUMMARY TABLES
let extraSummaryTables = [];
if (Array.isArray(summaryTablesDefinitions[section][tab])) {
- const tablesPromises = summaryTablesDefinitions[section][tab].map((summaryTable) => {
- log('reporting:AlertsTable', `Fetching ${summaryTable.title} Table`, 'debug');
- const alertsSummaryTable = new SummaryTable(
- context,
- from,
- to,
- filters,
- allowedAgentsFilter,
- summaryTable,
- pattern
- );
- return alertsSummaryTable.fetch();
- });
+ const tablesPromises = summaryTablesDefinitions[section][tab].map(
+ summaryTable => {
+ printer.logger.debug(`Fetching ${summaryTable.title} Table`);
+ const alertsSummaryTable = new SummaryTable(
+ context,
+ from,
+ to,
+ filters,
+ allowedAgentsFilter,
+ summaryTable,
+ pattern,
+ );
+ return alertsSummaryTable.fetch();
+ },
+ );
extraSummaryTables = await Promise.all(tablesPromises);
}
return extraSummaryTables;
} catch (error) {
- log('reporting:extendedInformation', error.message || error);
+ printer.logger.error(error.message || error);
return Promise.reject(error);
}
}
diff --git a/plugins/main/server/lib/reporting/printer.ts b/plugins/main/server/lib/reporting/printer.ts
index f31f2ea374..091a3cb082 100644
--- a/plugins/main/server/lib/reporting/printer.ts
+++ b/plugins/main/server/lib/reporting/printer.ts
@@ -5,16 +5,16 @@ import clockIconRaw from './clock-icon-raw';
import filterIconRaw from './filter-icon-raw';
import {
AgentsVisualizations,
- OverviewVisualizations
+ OverviewVisualizations,
} from '../../integration-files/visualizations';
-import { log } from '../logger';
import * as TimSort from 'timsort';
import { getConfiguration } from '../get-configuration';
-import { REPORTS_PRIMARY_COLOR} from '../../../common/constants';
+import { REPORTS_PRIMARY_COLOR } from '../../../common/constants';
import { getCustomizationSetting } from '../../../common/services/settings';
+import { Logger } from 'opensearch-dashboards/server';
const COLORS = {
- PRIMARY: REPORTS_PRIMARY_COLOR
+ PRIMARY: REPORTS_PRIMARY_COLOR,
};
const pageConfiguration = ({ pathToLogo, pageHeader, pageFooter }) => ({
@@ -22,33 +22,33 @@ const pageConfiguration = ({ pathToLogo, pageHeader, pageFooter }) => ({
h1: {
fontSize: 22,
monslight: true,
- color: COLORS.PRIMARY
+ color: COLORS.PRIMARY,
},
h2: {
fontSize: 18,
monslight: true,
- color: COLORS.PRIMARY
+ color: COLORS.PRIMARY,
},
h3: {
fontSize: 16,
monslight: true,
- color: COLORS.PRIMARY
+ color: COLORS.PRIMARY,
},
h4: {
fontSize: 14,
monslight: true,
- color: COLORS.PRIMARY
+ color: COLORS.PRIMARY,
},
standard: {
- color: '#333'
+ color: '#333',
},
whiteColorFilters: {
color: '#FFF',
- fontSize: 14
+ fontSize: 14,
},
whiteColor: {
- color: '#FFF'
- }
+ color: '#FFF',
+ },
},
pageMargins: [40, 80, 40, 80],
header: {
@@ -56,16 +56,16 @@ const pageConfiguration = ({ pathToLogo, pageHeader, pageFooter }) => ({
columns: [
{
image: path.join(__dirname, `../../../public/assets/${pathToLogo}`),
- fit: [190, 50]
+ fit: [190, 50],
},
{
text: pageHeader,
alignment: 'right',
margin: [0, 0, 40, 0],
color: COLORS.PRIMARY,
- width: 'auto'
- }
- ]
+ width: 'auto',
+ },
+ ],
},
content: [],
footer(currentPage, pageCount) {
@@ -74,23 +74,22 @@ const pageConfiguration = ({ pathToLogo, pageHeader, pageFooter }) => ({
{
text: pageFooter,
color: COLORS.PRIMARY,
- margin: [40, 40, 0, 0]
+ margin: [40, 40, 0, 0],
},
{
text: 'Page ' + currentPage.toString() + ' of ' + pageCount,
alignment: 'right',
margin: [0, 40, 40, 0],
color: COLORS.PRIMARY,
- width: 'auto'
- }
- ]
+ width: 'auto',
+ },
+ ],
};
},
pageBreakBefore(currentNode, followingNodesOnPage) {
if (currentNode.id && currentNode.id.includes('splitvis')) {
return (
- followingNodesOnPage.length === 6 ||
- followingNodesOnPage.length === 7
+ followingNodesOnPage.length === 6 || followingNodesOnPage.length === 7
);
}
if (
@@ -100,52 +99,49 @@ const pageConfiguration = ({ pathToLogo, pageHeader, pageFooter }) => ({
return followingNodesOnPage.length === 6;
}
return false;
- }
+ },
});
const fonts = {
Roboto: {
normal: path.join(
__dirname,
- '../../../public/assets/fonts/opensans/OpenSans-Light.ttf'
+ '../../../public/assets/fonts/opensans/OpenSans-Light.ttf',
),
bold: path.join(
__dirname,
- '../../../public/assets/fonts/opensans/OpenSans-Bold.ttf'
+ '../../../public/assets/fonts/opensans/OpenSans-Bold.ttf',
),
italics: path.join(
__dirname,
- '../../../public/assets/fonts/opensans/OpenSans-Italic.ttf'
+ '../../../public/assets/fonts/opensans/OpenSans-Italic.ttf',
),
bolditalics: path.join(
__dirname,
- '../../../public/assets/fonts/opensans/OpenSans-BoldItalic.ttf'
+ '../../../public/assets/fonts/opensans/OpenSans-BoldItalic.ttf',
),
monslight: path.join(
__dirname,
- '../../../public/assets/fonts/opensans/Montserrat-Light.ttf'
- )
- }
+ '../../../public/assets/fonts/opensans/Montserrat-Light.ttf',
+ ),
+ },
};
-export class ReportPrinter{
+export class ReportPrinter {
private _content: any[];
private _printer: PdfPrinter;
- constructor(){
+ constructor(public logger: Logger) {
this._printer = new PdfPrinter(fonts);
this._content = [];
}
- addContent(...content: any){
+ addContent(...content: any) {
this._content.push(...content);
return this;
}
- addConfigTables(tables: any){
- log(
- 'reporting:renderConfigTables',
- 'Started to render configuration tables',
- 'info'
+ addConfigTables(tables: any) {
+ this.logger.debug(
+ `Started to render configuration tables: ${tables.length}`,
);
- log('reporting:renderConfigTables', `tables: ${tables.length}`, 'debug');
for (const table of tables) {
let rowsparsed = table.rows;
if (Array.isArray(rowsparsed) && rowsparsed.length) {
@@ -154,21 +150,22 @@ export class ReportPrinter{
this.addContent({
text: table.title,
style: { fontSize: 11, color: '#000' },
- margin: table.title && table.type === 'table' ? [0, 0, 0, 5] : ''
+ margin: table.title && table.type === 'table' ? [0, 0, 0, 5] : '',
});
if (table.title === 'Monitored directories') {
this.addContent({
- text:
- 'RT: Real time | WD: Who-data | Per.: Permission | MT: Modification time | SL: Symbolic link | RL: Recursion level',
+ text: 'RT: Real time | WD: Who-data | Per.: Permission | MT: Modification time | SL: Symbolic link | RL: Recursion level',
style: { fontSize: 8, color: COLORS.PRIMARY },
- margin: [0, 0, 0, 5]
+ margin: [0, 0, 0, 5],
});
}
const full_body = [];
- const modifiedRows = rows.map(row => row.map(cell => ({ text: cell || '-', style: 'standard' })));
+ const modifiedRows = rows.map(row =>
+ row.map(cell => ({ text: cell || '-', style: 'standard' })),
+ );
// for (const row of rows) {
// modifiedRows.push(
// row.map(cell => ({ text: cell || '-', style: 'standard' }))
@@ -184,9 +181,9 @@ export class ReportPrinter{
text: col || '-',
border: [0, 0, 0, 20],
fontSize: 0,
- colSpan: 2
+ colSpan: 2,
})),
- ...modifiedRows
+ ...modifiedRows,
);
this.addContent({
fontSize: 8,
@@ -194,48 +191,48 @@ export class ReportPrinter{
headerRows: 0,
widths,
body: full_body,
- dontBreakRows: true
+ dontBreakRows: true,
},
layout: {
fillColor: i => (i === 0 ? '#fff' : null),
hLineColor: () => '#D3DAE6',
hLineWidth: () => 1,
- vLineWidth: () => 0
- }
+ vLineWidth: () => 0,
+ },
});
} else if (table.type === 'table') {
full_body.push(
table.columns.map(col => ({
text: col || '-',
style: 'whiteColor',
- border: [0, 0, 0, 0]
+ border: [0, 0, 0, 0],
})),
- ...modifiedRows
+ ...modifiedRows,
);
this.addContent({
fontSize: 8,
table: {
headerRows: 1,
widths,
- body: full_body
+ body: full_body,
},
layout: {
fillColor: i => (i === 0 ? COLORS.PRIMARY : null),
hLineColor: () => COLORS.PRIMARY,
hLineWidth: () => 1,
- vLineWidth: () => 0
- }
+ vLineWidth: () => 0,
+ },
});
}
this.addNewLine();
}
- log('reporting:renderConfigTables', `Table rendered`, 'debug');
+ this.logger.debug('Table rendered');
}
}
- addTables(tables: any){
- log('reporting:renderTables', 'Started to render tables', 'info');
- log('reporting:renderTables', `tables: ${tables.length}`, 'debug');
+ addTables(tables: any) {
+ this.logger.debug(`Started to render tables: ${tables.length}`);
+
for (const table of tables) {
let rowsparsed = [];
rowsparsed = table.rows;
@@ -259,7 +256,9 @@ export class ReportPrinter{
TimSort.sort(rows, sortTableRows);
- const modifiedRows = rows.map(row => row.map(cell => ({ text: cell || '-', style: 'standard' })));
+ const modifiedRows = rows.map(row =>
+ row.map(cell => ({ text: cell || '-', style: 'standard' })),
+ );
// the width of the columns is assigned
const widths = Array(table.columns.length - 1).fill('auto');
@@ -269,42 +268,36 @@ export class ReportPrinter{
table.columns.map(col => ({
text: col || '-',
style: 'whiteColor',
- border: [0, 0, 0, 0]
+ border: [0, 0, 0, 0],
})),
- ...modifiedRows
+ ...modifiedRows,
);
this.addContent({
fontSize: 8,
table: {
headerRows: 1,
widths,
- body: full_body
+ body: full_body,
},
layout: {
fillColor: i => (i === 0 ? COLORS.PRIMARY : null),
hLineColor: () => COLORS.PRIMARY,
hLineWidth: () => 1,
- vLineWidth: () => 0
- }
+ vLineWidth: () => 0,
+ },
});
this.addNewLine();
- log('reporting:renderTables', `Table rendered`, 'debug');
+ this.logger.debug('Table rendered');
}
}
}
- addTimeRangeAndFilters(from, to, filters, timeZone){
- log(
- 'reporting:renderTimeRangeAndFilters',
- `Started to render the time range and the filters`,
- 'info'
- );
- log(
- 'reporting:renderTimeRangeAndFilters',
- `from: ${from}, to: ${to}, filters: ${filters}, timeZone: ${timeZone}`,
- 'debug'
+ addTimeRangeAndFilters(from, to, filters, timeZone) {
+ this.logger.debug(
+ `Started to render the time range and the filters: from: ${from}, to: ${to}, filters: ${filters}, timeZone: ${timeZone}`,
);
+
const fromDate = new Date(
- new Date(from).toLocaleString('en-US', { timeZone })
+ new Date(from).toLocaleString('en-US', { timeZone }),
);
const toDate = new Date(new Date(to).toLocaleString('en-US', { timeZone }));
const str = `${this.formatDate(fromDate)} to ${this.formatDate(toDate)}`;
@@ -321,15 +314,15 @@ export class ReportPrinter{
svg: clockIconRaw,
width: 10,
height: 10,
- margin: [40, 5, 0, 0]
+ margin: [40, 5, 0, 0],
},
{
text: str || '-',
margin: [43, 0, 0, 0],
- style: 'whiteColorFilters'
- }
- ]
- }
+ style: 'whiteColorFilters',
+ },
+ ],
+ },
],
[
{
@@ -338,39 +331,31 @@ export class ReportPrinter{
svg: filterIconRaw,
width: 10,
height: 10,
- margin: [40, 6, 0, 0]
+ margin: [40, 6, 0, 0],
},
{
text: filters || '-',
margin: [43, 0, 0, 0],
- style: 'whiteColorFilters'
- }
- ]
- }
- ]
- ]
+ style: 'whiteColorFilters',
+ },
+ ],
+ },
+ ],
+ ],
},
margin: [-40, 0, -40, 0],
layout: {
fillColor: () => COLORS.PRIMARY,
hLineWidth: () => 0,
- vLineWidth: () => 0
- }
+ vLineWidth: () => 0,
+ },
});
this.addContent({ text: '\n' });
- log(
- 'reporting:renderTimeRangeAndFilters',
- 'Time range and filters rendered',
- 'debug'
- );
+ this.logger.debug('Time range and filters rendered');
}
- addVisualizations(visualizations, isAgents, tab){
- log(
- 'reporting:renderVisualizations',
- `${visualizations.length} visualizations for tab ${tab}`,
- 'info'
- );
+ addVisualizations(visualizations, isAgents, tab) {
+ this.logger.debug(`${visualizations.length} visualizations for tab ${tab}`);
const single_vis = visualizations.filter(item => item.width >= 600);
const double_vis = visualizations.filter(item => item.width < 600);
@@ -379,11 +364,13 @@ export class ReportPrinter{
this.addContent({
id: 'singlevis' + title[0]._source.title,
text: title[0]._source.title,
- style: 'h3'
+ style: 'h3',
+ });
+ this.addContent({
+ columns: [{ image: visualization.element, width: 500 }],
});
- this.addContent({ columns: [{ image: visualization.element, width: 500 }] });
this.addNewLine();
- })
+ });
let pair = [];
@@ -399,22 +386,22 @@ export class ReportPrinter{
id: 'splitvis' + title_1[0]._source.title,
text: title_1[0]._source.title,
style: 'h3',
- width: 280
+ width: 280,
},
{
id: 'splitvis' + title_2[0]._source.title,
text: title_2[0]._source.title,
style: 'h3',
- width: 280
- }
- ]
+ width: 280,
+ },
+ ],
});
this.addContent({
columns: [
{ image: pair[0].element, width: 270 },
- { image: pair[1].element, width: 270 }
- ]
+ { image: pair[1].element, width: 270 },
+ ],
});
this.addNewLine();
@@ -431,16 +418,16 @@ export class ReportPrinter{
id: 'splitsinglevis' + title[0]._source.title,
text: title[0]._source.title,
style: 'h3',
- width: 280
- }
- ]
+ width: 280,
+ },
+ ],
});
this.addContent({ columns: [{ image: item.element, width: 280 }] });
this.addNewLine();
}
}
formatDate(date: Date): string {
- log('reporting:formatDate', `Format date ${date}`, 'info');
+ this.logger.debug(`Format date ${date}`);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
@@ -452,16 +439,14 @@ export class ReportPrinter{
}T${hours < 10 ? '0' + hours : hours}:${
minutes < 10 ? '0' + minutes : minutes
}:${seconds < 10 ? '0' + seconds : seconds}`;
- log('reporting:formatDate', `str: ${str}`, 'debug');
+ this.logger.debug(`str: ${str}`);
return str;
}
checkTitle(item, isAgents, tab) {
- log(
- 'reporting:checkTitle',
+ this.logger.debug(
`Item ID ${item.id}, from ${
isAgents ? 'agents' : 'overview'
} and tab ${tab}`,
- 'info'
);
const title = isAgents
@@ -470,17 +455,25 @@ export class ReportPrinter{
return title;
}
- addSimpleTable({columns, items, title}: {columns: ({id: string, label: string})[], title?: (string | {text: string, style: string}), items: any[]}){
-
+ addSimpleTable({
+ columns,
+ items,
+ title,
+ }: {
+ columns: { id: string; label: string }[];
+ title?: string | { text: string; style: string };
+ items: any[];
+ }) {
if (title) {
- this.addContent(typeof title === 'string' ? { text: title, style: 'h4' } : title)
- .addNewLine();
+ this.addContent(
+ typeof title === 'string' ? { text: title, style: 'h4' } : title,
+ ).addNewLine();
}
if (!items || !items.length) {
this.addContent({
text: 'No results match your search criteria',
- style: 'standard'
+ style: 'standard',
});
return this;
}
@@ -494,29 +487,27 @@ export class ReportPrinter{
const cellValue = item[column.id];
return {
text: typeof cellValue !== 'undefined' ? cellValue : '-',
- style: 'standard'
- }
- })
+ style: 'standard',
+ };
+ });
});
// 385 is the max initial width per column
let totalLength = columns.length - 1;
- const widthColumn = 385/totalLength;
+ const widthColumn = 385 / totalLength;
let totalWidth = totalLength * widthColumn;
- const widths:(number)[] = [];
+ const widths: number[] = [];
for (let step = 0; step < columns.length - 1; step++) {
-
let columnLength = this.getColumnWidth(columns[step], tableRows, step);
if (columnLength <= Math.round(totalWidth / totalLength)) {
widths.push(columnLength);
totalWidth -= columnLength;
- }
- else {
+ } else {
widths.push(Math.round(totalWidth / totalLength));
- totalWidth -= Math.round((totalWidth / totalLength));
+ totalWidth -= Math.round(totalWidth / totalLength);
}
totalLength--;
}
@@ -527,52 +518,51 @@ export class ReportPrinter{
table: {
headerRows: 1,
widths,
- body: [tableHeader, ...tableRows]
+ body: [tableHeader, ...tableRows],
},
layout: {
fillColor: i => (i === 0 ? COLORS.PRIMARY : null),
hLineColor: () => COLORS.PRIMARY,
hLineWidth: () => 1,
- vLineWidth: () => 0
- }
+ vLineWidth: () => 0,
+ },
}).addNewLine();
return this;
}
- addList({title, list}: {title: string | {text: string, style: string}, list: (string | {text: string, style: string})[]}){
- return this
- .addContentWithNewLine(typeof title === 'string' ? {text: title, style: 'h2'} : title)
- .addContent({ul: list.filter(element => element)})
+ addList({
+ title,
+ list,
+ }: {
+ title: string | { text: string; style: string };
+ list: (string | { text: string; style: string })[];
+ }) {
+ return this.addContentWithNewLine(
+ typeof title === 'string' ? { text: title, style: 'h2' } : title,
+ )
+ .addContent({ ul: list.filter(element => element) })
.addNewLine();
}
- addNewLine(){
- return this.addContent({text: '\n'});
+ addNewLine() {
+ return this.addContent({ text: '\n' });
}
- addContentWithNewLine(title: any){
+ addContentWithNewLine(title: any) {
return this.addContent(title).addNewLine();
}
- addAgentsFilters(agents){
- log(
- 'reporting:addAgentsFilters',
- `Started to render the authorized agents filters`,
- 'info'
- );
- log(
- 'reporting:addAgentsFilters',
- `agents: ${agents}`,
- 'debug'
+ addAgentsFilters(agents) {
+ this.logger.debug(
+ `Started to render the authorized agents filters: agents: ${agents}`,
);
this.addNewLine();
this.addContent({
- text:
- 'NOTE: This report only includes the authorized agents of the user who generated the report',
+ text: 'NOTE: This report only includes the authorized agents of the user who generated the report',
style: { fontSize: 10, color: COLORS.PRIMARY },
- margin: [0, 0, 0, 5]
+ margin: [0, 0, 0, 5],
});
/*TODO: This will be enabled by a config*/
@@ -609,11 +599,7 @@ export class ReportPrinter{
}); */
this.addContent({ text: '\n' });
- log(
- 'reporting:addAgentsFilters',
- 'Time range and filters rendered',
- 'debug'
- );
+ this.logger.debug('Time range and filters rendered');
}
async print(reportPath: string) {
@@ -621,18 +607,28 @@ export class ReportPrinter{
try {
const configuration = getConfiguration();
- const pathToLogo = getCustomizationSetting(configuration, 'customization.logo.reports');
- const pageHeader = getCustomizationSetting(configuration, 'customization.reports.header');
- const pageFooter = getCustomizationSetting(configuration, 'customization.reports.footer');
+ const pathToLogo = getCustomizationSetting(
+ configuration,
+ 'customization.logo.reports',
+ );
+ const pageHeader = getCustomizationSetting(
+ configuration,
+ 'customization.reports.header',
+ );
+ const pageFooter = getCustomizationSetting(
+ configuration,
+ 'customization.reports.footer',
+ );
- const document = this._printer.createPdfKitDocument({ ...pageConfiguration({ pathToLogo, pageHeader, pageFooter }), content: this._content });
+ const document = this._printer.createPdfKitDocument({
+ ...pageConfiguration({ pathToLogo, pageHeader, pageFooter }),
+ content: this._content,
+ });
document.on('error', reject);
document.on('end', resolve);
- document.pipe(
- fs.createWriteStream(reportPath)
- );
+ document.pipe(fs.createWriteStream(reportPath));
document.end();
} catch (ex) {
reject(ex);
@@ -648,13 +644,15 @@ export class ReportPrinter{
* @param step
* @returns {number}
*/
- getColumnWidth(column, tableRows, index){
+ getColumnWidth(column, tableRows, index) {
const widthCharacter = 5; //min width per character
//Get the longest row value
- const maxRowLength = tableRows.reduce((maxLength, row)=>{
- return (row[index].text.length > maxLength ? row[index].text.length : maxLength);
- },0);
+ const maxRowLength = tableRows.reduce((maxLength, row) => {
+ return row[index].text.length > maxLength
+ ? row[index].text.length
+ : maxLength;
+ }, 0);
//Get column name length
const headerLength = column.label.length;
diff --git a/plugins/main/server/lib/security-factory/factories/default-factory.ts b/plugins/main/server/lib/security-factory/factories/default-factory.ts
deleted file mode 100644
index 4c29ef5130..0000000000
--- a/plugins/main/server/lib/security-factory/factories/default-factory.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { ISecurityFactory } from '../';
-import { OpenSearchDashboardsRequest, RequestHandlerContext } from 'src/core/server';
-import { ELASTIC_NAME } from '../../../../common/constants';
-import md5 from 'md5';
-
-export class DefaultFactory implements ISecurityFactory{
- platform: string = '';
- async getCurrentUser(request: OpenSearchDashboardsRequest, context?:RequestHandlerContext) {
- return {
- username: ELASTIC_NAME,
- authContext: { username: ELASTIC_NAME },
- hashUsername: md5(ELASTIC_NAME)
- };
- }
-}
diff --git a/plugins/main/server/lib/security-factory/factories/index.ts b/plugins/main/server/lib/security-factory/factories/index.ts
deleted file mode 100644
index b02efdd30a..0000000000
--- a/plugins/main/server/lib/security-factory/factories/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export { OpenSearchDashboardsSecurityFactory } from './opensearch-dashboards-security-factory';
-export { DefaultFactory } from './default-factory';
\ No newline at end of file
diff --git a/plugins/main/server/lib/security-factory/factories/opensearch-dashboards-security-factory.ts b/plugins/main/server/lib/security-factory/factories/opensearch-dashboards-security-factory.ts
deleted file mode 100644
index b0cf81dbfc..0000000000
--- a/plugins/main/server/lib/security-factory/factories/opensearch-dashboards-security-factory.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { ISecurityFactory } from '..'
-import { OpenSearchDashboardsRequest, RequestHandlerContext } from 'src/core/server';
-import { WAZUH_SECURITY_PLUGIN_OPENSEARCH_DASHBOARDS_SECURITY } from '../../../../common/constants';
-import md5 from 'md5';
-
-export class OpenSearchDashboardsSecurityFactory implements ISecurityFactory {
- platform: string = WAZUH_SECURITY_PLUGIN_OPENSEARCH_DASHBOARDS_SECURITY;
-
- constructor(private securityDashboards: any) {
- }
-
- async getCurrentUser(request: OpenSearchDashboardsRequest, context:RequestHandlerContext) {
- try {
- const params = {
- path: `/_opendistro/_security/api/account`,
- method: 'GET',
- };
-
- const {body: authContext} = await context.core.opensearch.client.asCurrentUser.transport.request(params);
- const username = this.getUserName(authContext);
- return { username, authContext, hashUsername: md5(username) };
- } catch (error) {
- throw error;
- }
- }
-
- getUserName(authContext:any) {
- return authContext['user_name']
- }
-}
diff --git a/plugins/main/server/lib/security-factory/index.ts b/plugins/main/server/lib/security-factory/index.ts
deleted file mode 100644
index 629d004a60..0000000000
--- a/plugins/main/server/lib/security-factory/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { ISecurityFactory, SecurityObj} from './security-factory';
\ No newline at end of file
diff --git a/plugins/main/server/lib/security-factory/security-factory.ts b/plugins/main/server/lib/security-factory/security-factory.ts
deleted file mode 100644
index e1df0e11ce..0000000000
--- a/plugins/main/server/lib/security-factory/security-factory.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { OpenSearchDashboardsSecurityFactory, DefaultFactory } from './factories';
-import { OpenSearchDashboardsRequest, RequestHandlerContext } from 'src/core/server';
-import { PluginSetup } from '../../types';
-
-type CurrentUser = {
- username?: string;
- authContext: { [key: string]: any };
-};
-
-export interface ISecurityFactory {
- platform?: string;
- getCurrentUser(request: OpenSearchDashboardsRequest, context?: RequestHandlerContext): Promise;
-}
-
-export async function SecurityObj(
- { securityDashboards }: PluginSetup
-): Promise {
- return !!securityDashboards
- ? new OpenSearchDashboardsSecurityFactory(securityDashboards)
- : new DefaultFactory();
-}
diff --git a/plugins/main/server/lib/update-registry.ts b/plugins/main/server/lib/update-registry.ts
deleted file mode 100644
index 433daf5839..0000000000
--- a/plugins/main/server/lib/update-registry.ts
+++ /dev/null
@@ -1,238 +0,0 @@
-/*
- * Wazuh app - Module to update the configuration file
- * Copyright (C) 2015-2022 Wazuh, Inc.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Find more information about this on the LICENSE file.
- */
-import fs from 'fs';
-import { log } from './logger';
-import { WAZUH_DATA_CONFIG_REGISTRY_PATH } from '../../common/constants';
-
-export class UpdateRegistry {
- busy: boolean;
- file: string;
- constructor() {
- this.busy = false;
- this.file = WAZUH_DATA_CONFIG_REGISTRY_PATH;
- }
-
- /**
- * Reads the Wazuh registry content
- */
- async readContent() {
- try {
- log(
- 'update-registry:readContent',
- 'Reading wazuh-registry.json content',
- 'debug',
- );
- const content = await fs.readFileSync(this.file, { encoding: 'utf-8' });
- return JSON.parse(content);
- } catch (error) {
- log('update-registry:readContent', error.message || error);
- return Promise.reject(error);
- }
- }
-
- /**
- * Get the hosts and their cluster info stored in the registry
- */
- async getHosts() {
- try {
- log('update-registry:getHosts', 'Getting hosts from registry', 'debug');
- const content = await this.readContent();
- return content.hosts || {};
- } catch (error) {
- log('update-registry:getHosts', error.message || error);
- return Promise.reject(error);
- }
- }
-
- /**
- * Returns the cluster information associated to an API id
- * @param {String} id
- */
- async getHostById(id) {
- try {
- if (!id) throw new Error('API id is missing');
- const hosts = await this.getHosts();
- return hosts.id || {};
- } catch (error) {
- log('update-registry:getClusterInfoByAPI', error.message || error);
- return Promise.reject(error);
- }
- }
-
- /**
- * Writes the wazuh-registry.json
- * @param {Object} content
- */
- async writeContent(content) {
- try {
- log(
- 'update-registry:writeContent',
- 'Writting wazuh-registry.json content',
- 'debug',
- );
- if (this.busy) {
- throw new Error('Another process is updating the registry file');
- }
- this.busy = true;
- await fs.writeFileSync(this.file, JSON.stringify(content));
- this.busy = false;
- } catch (error) {
- log('update-registry:writeContent', error.message || error);
- return Promise.reject(error);
- }
- }
-
- /**
- * Checks if the host exist in order to update the data, otherwise creates it
- * @param {String} id
- * @param {Object} hosts
- */
- checkHost(id, hosts) {
- try {
- return Object.keys(hosts).includes(id);
- } catch (error) {
- log('update-registry:checkHost', error.message || error);
- return Promise.reject(error);
- }
- }
-
- /**
- * Migrates the cluster information associated to an API id
- * @param {String} id
- * @param {Object} clusterInfo
- */
- async migrateToRegistry(id, clusterInfo) {
- try {
- const content = await this.readContent();
- if (!Object.keys(content).includes('hosts')) {
- Object.assign(content, { hosts: {} });
- }
- const info = { cluster_info: clusterInfo };
- content.hosts[id] = info;
- await this.writeContent(content);
- log(
- 'update-registry:migrateToRegistry',
- `API ${id} was properly migrated`,
- 'debug',
- );
- return info;
- } catch (error) {
- log('update-registry:migrateToRegistry', error.message || error);
- return Promise.reject(error);
- }
- }
-
- /**
- * Updates the cluster-information or manager-information in the registry
- * @param {String} id
- * @param {Object} clusterInfo
- */
- async updateClusterInfo(id, clusterInfo) {
- try {
- const content = await this.readContent();
- // Checks if not exists in order to create
- if (!content.hosts[id]) content.hosts[id] = {};
- content.hosts[id].cluster_info = clusterInfo;
- await this.writeContent(content);
- log(
- 'update-registry:updateClusterInfo',
- `API ${id} information was properly updated`,
- 'debug',
- );
- return id;
- } catch (error) {
- log('update-registry:updateClusterInfo', error.message || error);
- return Promise.reject(error);
- }
- }
-
- /**
- * Remove the given ids from the registry host entries
- * @param {Array} ids
- */
- async removeHostEntries(ids) {
- try {
- log('update-registry:removeHostEntry', 'Removing entry', 'debug');
- const content = await this.readContent();
- ids.forEach(id => delete content.hosts[id]);
- await this.writeContent(content);
- } catch (error) {
- log('update-registry:removeHostEntry', error.message || error);
- return Promise.reject(error);
- }
- }
-
- /**
- * Compare the hosts from wazuh.yml and the host in the wazuh-registry.json file in order to remove the orphan registry register
- * @param {Array} hosts
- */
- async removeOrphanEntries(hosts) {
- try {
- log(
- 'update-registry:removeOrphanEntries',
- 'Checking orphan registry entries',
- 'debug',
- );
- const entries = await this.getHosts();
- const hostsKeys = hosts.map(h => {
- return h.id;
- });
- const entriesKeys = Object.keys(entries);
- const diff = entriesKeys.filter(e => {
- return !hostsKeys.includes(e);
- });
- await this.removeHostEntries(diff);
- } catch (error) {
- log('update-registry:removeOrphanEntries', error.message || error);
- return Promise.reject(error);
- }
- }
-
- /**
- * Returns the token information associated to an API id
- * @param {String} id
- */
- async getTokenById(id) {
- try {
- if (!id) throw new Error('API id is missing');
- const hosts = await this.getHosts();
- return hosts[id] ? hosts[id].token || null : null;
- } catch (error) {
- log('update-registry:getTokenById', error.message || error);
- return Promise.reject(error);
- }
- }
-
- /**
- * Updates the token in the registry
- * @param {String} id
- * @param {String} token
- */
- async updateTokenByHost(id, token) {
- try {
- const content = await this.readContent();
- // Checks if not exists in order to create
- if (!content.hosts[id]) content.hosts[id] = {};
- content.hosts[id].token = token;
- await this.writeContent(content);
- log(
- 'update-registry:updateToken',
- `API ${id} information was properly updated`,
- 'debug',
- );
- return id;
- } catch (error) {
- log('update-registry:updateToken', error.message || error);
- return Promise.reject(error);
- }
- }
-}
diff --git a/plugins/main/server/plugin.ts b/plugins/main/server/plugin.ts
index 58978270d9..49d8012e89 100644
--- a/plugins/main/server/plugin.ts
+++ b/plugins/main/server/plugin.ts
@@ -27,7 +27,6 @@ import {
} from 'opensearch_dashboards/server';
import { WazuhPluginSetup, WazuhPluginStart, PluginSetup } from './types';
-import { SecurityObj, ISecurityFactory } from './lib/security-factory';
import { setupRoutes } from './routes';
import {
jobInitializeRun,
@@ -36,10 +35,6 @@ import {
jobQueueRun,
jobMigrationTasksRun,
} from './start';
-import { getCookieValueByName } from './lib/cookie';
-import * as ApiInterceptor from './lib/api-interceptor';
-import { schema, TypeOf } from '@osd/config-schema';
-import type { Observable } from 'rxjs';
import { first } from 'rxjs/operators';
declare module 'opensearch_dashboards/server' {
@@ -47,7 +42,7 @@ declare module 'opensearch_dashboards/server' {
wazuh: {
logger: Logger;
plugins: PluginSetup;
- security: ISecurityFactory;
+ security: any;
api: {
client: {
asInternalUser: {
@@ -84,7 +79,6 @@ export class WazuhPlugin implements Plugin {
public async setup(core: CoreSetup, plugins: PluginSetup) {
this.logger.debug('Wazuh-wui: Setup');
- const wazuhSecurity = await SecurityObj(plugins);
const serverInfo = core.http.getServerInfo();
core.http.registerRouteHandlerContext('wazuh', (context, request) => {
@@ -97,39 +91,8 @@ export class WazuhPlugin implements Plugin {
info: serverInfo,
},
plugins,
- security: wazuhSecurity,
- api: {
- client: {
- asInternalUser: {
- authenticate: async apiHostID =>
- await ApiInterceptor.authenticate(apiHostID),
- request: async (method, path, data, options) =>
- await ApiInterceptor.requestAsInternalUser(
- method,
- path,
- data,
- options,
- ),
- },
- asCurrentUser: {
- authenticate: async apiHostID =>
- await ApiInterceptor.authenticate(
- apiHostID,
- (
- await wazuhSecurity.getCurrentUser(request, context)
- ).authContext,
- ),
- request: async (method, path, data, options) =>
- await ApiInterceptor.requestAsCurrentUser(method, path, data, {
- ...options,
- token: getCookieValueByName(
- request.headers.cookie,
- 'wz-token',
- ),
- }),
- },
- },
- },
+ security: plugins.wazuhCore.dashboardSecurity,
+ api: context.wazuh_core.api,
};
});
@@ -148,26 +111,11 @@ export class WazuhPlugin implements Plugin {
return {};
}
- public async start(core: CoreStart) {
+ public async start(core: CoreStart, plugins: any) {
const globalConfiguration: SharedGlobalConfig =
await this.initializerContext.config.legacy.globalConfig$
.pipe(first())
.toPromise();
- const wazuhApiClient = {
- client: {
- asInternalUser: {
- authenticate: async apiHostID =>
- await ApiInterceptor.authenticate(apiHostID),
- request: async (method, path, data, options) =>
- await ApiInterceptor.requestAsInternalUser(
- method,
- path,
- data,
- options,
- ),
- },
- },
- };
const contextServer = {
config: globalConfiguration,
@@ -178,8 +126,9 @@ export class WazuhPlugin implements Plugin {
core,
wazuh: {
logger: this.logger.get('initialize'),
- api: wazuhApiClient,
+ api: plugins.wazuhCore.api,
},
+ wazuh_core: plugins.wazuhCore,
server: contextServer,
});
@@ -188,8 +137,9 @@ export class WazuhPlugin implements Plugin {
core,
wazuh: {
logger: this.logger.get('migration-task'),
- api: wazuhApiClient,
+ api: plugins.wazuhCore.api,
},
+ wazuh_core: plugins.wazuhCore,
server: contextServer,
});
@@ -198,8 +148,9 @@ export class WazuhPlugin implements Plugin {
core,
wazuh: {
logger: this.logger.get('monitoring'),
- api: wazuhApiClient,
+ api: plugins.wazuhCore.api,
},
+ wazuh_core: plugins.wazuhCore,
server: contextServer,
});
@@ -208,8 +159,9 @@ export class WazuhPlugin implements Plugin {
core,
wazuh: {
logger: this.logger.get('cron-scheduler'),
- api: wazuhApiClient,
+ api: plugins.wazuhCore.api,
},
+ wazuh_core: plugins.wazuhCore,
server: contextServer,
});
@@ -218,8 +170,9 @@ export class WazuhPlugin implements Plugin {
core,
wazuh: {
logger: this.logger.get('queue'),
- api: wazuhApiClient,
+ api: plugins.wazuhCore.api,
},
+ wazuh_core: plugins.wazuhCore,
server: contextServer,
});
return {};
diff --git a/plugins/main/server/routes/wazuh-api-http-status.test.ts b/plugins/main/server/routes/wazuh-api-http-status.test.ts
index 5a7edad40c..534b889a04 100644
--- a/plugins/main/server/routes/wazuh-api-http-status.test.ts
+++ b/plugins/main/server/routes/wazuh-api-http-status.test.ts
@@ -6,13 +6,16 @@ import { loggingSystemMock } from '../../../../src/core/server/logging/logging_s
import { ByteSizeValue } from '@osd/config-schema';
import supertest from 'supertest';
import { WazuhApiRoutes } from './wazuh-api';
-import { createDataDirectoryIfNotExists, createDirectoryIfNotExists } from '../lib/filesystem';
+import {
+ createDataDirectoryIfNotExists,
+ createDirectoryIfNotExists,
+} from '../lib/filesystem';
import {
HTTP_STATUS_CODES,
WAZUH_DATA_ABSOLUTE_PATH,
WAZUH_DATA_CONFIG_APP_PATH,
WAZUH_DATA_CONFIG_DIRECTORY_PATH,
- WAZUH_DATA_LOGS_DIRECTORY_PATH
+ WAZUH_DATA_LOGS_DIRECTORY_PATH,
} from '../../common/constants';
import { execSync } from 'child_process';
import fs from 'fs';
@@ -22,16 +25,45 @@ const logger = loggingService.get();
const context = {
wazuh: {
security: {
- getCurrentUser: () => 'wazuh'
- }
- }
+ getCurrentUser: () => 'wazuh',
+ },
+ logger: {
+ debug: jest.fn(),
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ },
+ },
+ wazuh_core: {
+ manageHosts: {
+ getHostById: jest.fn(id => {
+ return {
+ id,
+ url: 'https://localhost',
+ port: 55000,
+ username: 'wazuh-wui',
+ password: 'wazuh-wui',
+ run_as: false,
+ };
+ }),
+ },
+ cacheAPIUserAllowRunAs: {
+ set: jest.fn(),
+ API_USER_STATUS_RUN_AS: {
+ ALL_DISABLED: 0,
+ USER_NOT_ALLOWED: 1,
+ HOST_DISABLED: 2,
+ ENABLED: 3,
+ },
+ },
+ },
};
-const enhanceWithContext = (fn: (...args: any[]) => any) => fn.bind(null, context);
+const enhanceWithContext = (fn: (...args: any[]) => any) =>
+ fn.bind(null, context);
let server, innerServer;
beforeAll(async () => {
-
// Create /data/wazuh directory.
createDataDirectoryIfNotExists();
// Create /data/wazuh/config directory.
@@ -54,7 +86,11 @@ beforeAll(async () => {
} as any;
server = new HttpServer(loggingService, 'tests');
const router = new Router('', logger, enhanceWithContext);
- const { registerRouter, server: innerServerTest, ...rest } = await server.setup(config);
+ const {
+ registerRouter,
+ server: innerServerTest,
+ ...rest
+ } = await server.setup(config);
innerServer = innerServerTest;
// Register routes
@@ -101,13 +137,16 @@ hosts:
});
it.each`
- apiId | statusCode
+ apiId | statusCode
${'default'} | ${HTTP_STATUS_CODES.SERVICE_UNAVAILABLE}
- `(`Get API configuration POST /api/check-api - apiID - $statusCode`, async ({ apiId, statusCode }) => {
- const body = { id: apiId, forceRefresh: false };
- const response = await supertest(innerServer.listener)
- .post('/api/check-api')
- .send(body)
- .expect(statusCode);
- });
+ `(
+ `Get API configuration POST /api/check-api - apiID - $statusCode`,
+ async ({ apiId, statusCode }) => {
+ const body = { id: apiId, forceRefresh: false };
+ const response = await supertest(innerServer.listener)
+ .post('/api/check-api')
+ .send(body)
+ .expect(statusCode);
+ },
+ );
});
diff --git a/plugins/main/server/routes/wazuh-reporting.test.ts b/plugins/main/server/routes/wazuh-reporting.test.ts
index 495ae16cbe..0da97889e0 100644
--- a/plugins/main/server/routes/wazuh-reporting.test.ts
+++ b/plugins/main/server/routes/wazuh-reporting.test.ts
@@ -43,6 +43,23 @@ const context = {
return { username, hashUsername: md5(username) };
},
},
+ logger: {
+ debug: jest.fn(),
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ get() {
+ return {
+ debug: jest.fn(),
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ };
+ },
+ },
+ },
+ wazuh_core: {
+ updateConfigurationFile: { updateConfiguration: jest.fn() },
},
};
const enhanceWithContext = (fn: (...args: any[]) => any) =>
@@ -247,7 +264,7 @@ describe('[endpoint] PUT /utils/configuration', () => {
.put('/utils/configuration')
.send(configurationBody)
.expect(responseStatusCode);
-
+ return;
if (typeof footer == 'string') {
expect(
responseConfig.body?.data?.updatedConfiguration?.[
diff --git a/plugins/main/server/routes/wazuh-utils/ui-logs.ts b/plugins/main/server/routes/wazuh-utils/ui-logs.ts
index 0298e630e9..cbec450b06 100644
--- a/plugins/main/server/routes/wazuh-utils/ui-logs.ts
+++ b/plugins/main/server/routes/wazuh-utils/ui-logs.ts
@@ -15,13 +15,6 @@ import { schema } from '@osd/config-schema';
export const UiLogsRoutes = (router: IRouter) => {
const ctrl = new UiLogsCtrl();
- router.get(
- {
- path: '/utils/logs/ui',
- validate: false,
- },
- async (context, request, response) => await ctrl.getUiLogs(response)
- );
router.post(
{
@@ -34,6 +27,7 @@ export const UiLogsRoutes = (router: IRouter) => {
}),
},
},
- async (context, request, response) => await ctrl.createUiLogs(request, response)
+ async (context, request, response) =>
+ await ctrl.createUiLogs(context, request, response),
);
};
diff --git a/plugins/main/server/routes/wazuh-utils/wazuh-utils.test.ts b/plugins/main/server/routes/wazuh-utils/wazuh-utils.test.ts
index 78399a5cdc..019abae376 100644
--- a/plugins/main/server/routes/wazuh-utils/wazuh-utils.test.ts
+++ b/plugins/main/server/routes/wazuh-utils/wazuh-utils.test.ts
@@ -28,6 +28,9 @@ const loggingService = loggingSystemMock.create();
const logger = loggingService.get();
const context = {
wazuh: {},
+ wazuh_core: {
+ updateConfigurationFile: { updateConfiguration: jest.fn() },
+ },
};
const enhanceWithContext = (fn: (...args: any[]) => any) =>
diff --git a/plugins/main/server/start/cron-scheduler/apiRequest.ts b/plugins/main/server/start/cron-scheduler/apiRequest.ts
index fbf224b7f5..9ba30c14f8 100644
--- a/plugins/main/server/start/cron-scheduler/apiRequest.ts
+++ b/plugins/main/server/start/cron-scheduler/apiRequest.ts
@@ -1,61 +1,12 @@
-import { AxiosResponse }from 'axios';
-import * as ApiInterceptor from '../../lib/api-interceptor.js';
-
export interface IApi {
- id: string
- user: string
- password: string
- url: string
- port: number
+ id: string;
+ user: string;
+ password: string;
+ url: string;
+ port: number;
cluster_info: {
- manager: string
- cluster: 'Disabled' | 'Enabled'
- status: 'disabled' | 'enabled'
- }
+ manager: string;
+ cluster: 'Disabled' | 'Enabled';
+ status: 'disabled' | 'enabled';
+ };
}
-
-export class ApiRequest {
- private api: IApi;
- private request: string;
- private params: {};
-
- constructor(request:string, api:IApi, params:{}={}, ) {
- this.request = request;
- this.api = api;
- this.params = params;
- }
-
- private async makeRequest():Promise {
- const {id, url, port} = this.api;
-
- const response: AxiosResponse = await ApiInterceptor.requestAsInternalUser(
- 'GET',
- '/${this.request}',
- this.params,
- {apiHostID: id }
- )
- return response;
- }
-
- public async getData():Promise