Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Backport 4.5-7.10] Added new global error treatment (client-side) #5382

Merged
merged 1 commit into from
Apr 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ All notable changes to the Wazuh app project will be documented in this file.

- Added rel="noopener noreferrer" in documentation links. [#5197](https://github.com/wazuh/wazuh-kibana-app/pull/5197) [#5274](https://github.com/wazuh/wazuh-kibana-app/pull/5274) [#5298](https://github.com/wazuh/wazuh-kibana-app/pull/5298)
- Added `ignore` and `restrict` options to Syslog configuration. [#5203](https://github.com/wazuh/wazuh-kibana-app/pull/5203)
- Added new global error treatment (client-side) [#4163](https://github.com/wazuh/wazuh-kibana-app/pull/4163)

### Changed

Expand All @@ -21,6 +22,7 @@ All notable changes to the Wazuh app project will be documented in this file.
- Fixed the display of more than one protocol in the Global configuration section [#4917](https://github.com/wazuh/wazuh-kibana-app/pull/4917)
- Handling endpoint response was done when there is no data to show [#4918]https://github.com/wazuh/wazuh-kibana-app/pull/4918
- Fixed the 2 errors that appeared in console in Settings>Configuration section. [#5135](https://github.com/wazuh/wazuh-kibana-app/pull/5135)
- Fixed TypeError in FIM Inventory using new error handler [#5364](https://github.com/wazuh/wazuh-kibana-app/pull/5364)

## Wazuh v4.4.1 - Kibana 7.10.2, 7.16.x, 7.17.x - Revision 01

Expand Down
40 changes: 23 additions & 17 deletions public/components/agents/fim/inventory/fileDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import { getDataPlugin, getUiSettings } from '../../../../kibana-services';
import { RegistryValues } from './registryValues';
import { formatUIDate } from '../../../../react-services/time-service';
import { FilterManager } from '../../../../../../../src/plugins/data/public/';
import { ErrorHandler } from '../../../../react-services/error-management';

export class FileDetails extends Component {
props!: {
Expand Down Expand Up @@ -228,23 +229,28 @@ export class FileDetails extends Component {
}

async checkFilterManager(filters) {
const { filterManager } = getDataPlugin().query;
const _filters = filterManager.getFilters();
if (_filters && _filters.length) {
const syscheckPathFilters = _filters.filter((x) => {
return x.meta.key === 'syscheck.path';
});
syscheckPathFilters.map((x) => {
filterManager.removeFilter(x);
});
filterManager.addFilters([filters]);
const scope = await ModulesHelper.getDiscoverScope();
scope.updateQueryAndFetch({ query: null });
} else {
setTimeout(() => {
this.checkFilterManager(filters);
}, 200);
try {
const { filterManager } = getDataPlugin().query;
const _filters = filterManager.getFilters();
if (_filters && _filters.length) {
const syscheckPathFilters = _filters.filter((x) => {
return x.meta.key === 'syscheck.path';
});
syscheckPathFilters.map((x) => {
filterManager.removeFilter(x);
});
filterManager.addFilters([filters]);
const scope = await ModulesHelper.getDiscoverScope();
scope.updateQueryAndFetch && scope.updateQueryAndFetch({ query: null });
} else {
setTimeout(() => {
this.checkFilterManager(filters);
}, 200);
}
}catch(error){
ErrorHandler.handleError(error as Error);
}

}

addFilter(field, value) {
Expand Down Expand Up @@ -501,4 +507,4 @@ export class FileDetails extends Component {
</Fragment>
);
}
}
}
4 changes: 2 additions & 2 deletions public/components/agents/sca/inventory.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -636,5 +636,5 @@ export class Inventory extends Component<InventoryProps, InventoryState> {
}

Inventory.defaultProps = {
onClickRow: undefined,
};
onClickRow: undefined
}
121 changes: 121 additions & 0 deletions public/components/health-check/services/check-api.service.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import * as service from './check-api.service';
import { CheckLogger } from '../types/check_logger';
import { ApiCheck, AppState } from '../../../react-services';
import axios, { AxiosResponse } from 'axios';

jest.mock('axios');
// app state
jest.mock('../../../react-services/app-state');
jest.mock('../../../kibana-services', () => ({
...(jest.requireActual('../../../kibana-services') as object),
getHttp: jest.fn().mockReturnValue({
basePath: {
get: () => {
return 'http://localhost:5601';
},
prepend: (url) => {
return `http://localhost:5601${url}`;
},
},
}),
getCookies: jest.fn().mockReturnValue({
set: (name, value, options) => {
return true;
},
get: () => {
return '{}';
},
remove: () => {
return;
},
}),
}));

const hostData = {
id: 'api',
url: 'url-mocked',
port: 9000,
username: 'username',
password: 'password',
run_as: false,
};
const getApiHostsResponse: AxiosResponse = {
data: [hostData],
status: 200,
statusText: 'OK',
headers: {},
config: {},
request: {},
};

const checkStoredErrorResponse: AxiosResponse = {
data: {
statusCode: 500,
error: 'Internal Server Error',
message: '3099 - ERROR3099 - Wazuh not ready yet',
},
status: 500,
statusText: 'Internal Server Error',
headers: {},
config: {},
request: {},
};

// checkLogger mocked
const checkLoggerMocked: CheckLogger = {
info: jest.fn(),
error: jest.fn(),
action: jest.fn(),
};

describe.skip('CheckApi Service', () => {
it('Should show logs info when api check pass successfully and have cluster_info ', async () => {
const currentApi = { id: 'api-mocked' };
AppState.getCurrentAPI = jest.fn().mockReturnValue(JSON.stringify(currentApi));
AppState.setClusterInfo = jest.fn();
const checkStoredResponse = {
data: {
data: {
url: 'url-mocked',
port: 9000,
username: 'username',
password: 'password',
run_as: false,
cluster_info: {
status: 'enabled',
node: 'master',
manager: 'manager-mocked',
cluster: 'cluster-mocked',
},
},
},
};
ApiCheck.checkStored = jest.fn().mockResolvedValue(Promise.resolve(checkStoredResponse));
await service.checkApiService({})(checkLoggerMocked);
expect(checkLoggerMocked.info).toBeCalledWith(`Current API id [${currentApi.id}]`);
expect(checkLoggerMocked.info).toBeCalledWith(`Checking current API id [${currentApi.id}]...`);
expect(checkLoggerMocked.info).toBeCalledWith(`Set cluster info in cookie`);
expect(checkLoggerMocked.info).toBeCalledTimes(3);
});

it('Should return ERROR and show logs info when api check fails on checkApi', async () => {
const currentApi = { id: 'api-mocked' };
AppState.getCurrentAPI = jest.fn().mockReturnValue(JSON.stringify(currentApi));
AppState.setClusterInfo = jest.fn();
ApiCheck.checkStored = jest.fn().mockResolvedValue(Promise.reject(checkStoredErrorResponse));
(axios as jest.MockedFunction<typeof axios>).mockResolvedValue(
Promise.resolve(getApiHostsResponse)
);

ApiCheck.checkApi = jest.fn().mockResolvedValue(Promise.reject(checkStoredErrorResponse));

try {
await service.checkApiService({})(checkLoggerMocked);
} catch (error) {
expect(error).toBeDefined();
expect(typeof error).not.toBe('string');
expect(error.message).toContain('No API available to connect');
expect(error).toBeInstanceOf(Error);
}
});
});
6 changes: 3 additions & 3 deletions public/components/health-check/services/check-api.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,13 @@ const trySetDefault = async (checkLogger: CheckLogger) => {
);
}
}
return Promise.reject('No API available to connect');
return Promise.reject(new Error('No API available to connect'));
}
}
return Promise.reject('No API configuration found');
return Promise.reject(new Error('No API configuration found'));
} catch (error) {
checkLogger.error(`Error connecting to API: ${error}`);
return Promise.reject(`Error connecting to API: ${error}`);
return Promise.reject(new Error(`Error connecting to API: ${error}`));
}
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,53 +5,47 @@ import { Provider } from 'react-redux';
import configureMockStore from 'redux-mock-store';

jest.mock('../../../../../../kibana-services', () => ({
getUiSettings:() => ({
get:() => {
return false
}
}),
getAngularModule: jest.fn(),
getUiSettings: () => ({
get: () => {
return false;
},
}),
}));

const mockProps = {
"clusterNodeSelected":"master-node",
"agent":{
"id":"000"
clusterNodeSelected: 'master-node',
agent: {
id: '000',
},
refreshTime: false,
currentConfig: {
'analysis-alerts': {
alerts: {
email_alert_level: 12,
log_alert_level: 3,
},
},
"refreshTime":false,
"currentConfig":{
"analysis-alerts":{
"alerts":{
"email_alert_level":12,
"log_alert_level":3
}
},
"analysis-labels":{
"labels":[

]
},
"mail-alerts":"Fetch configuration. 3013 - Error connecting with socket",
"monitor-reports":{

},
"csyslog-csyslog":"Fetch configuration. 3013 - Error connecting with socket"
'analysis-labels': {
labels: [],
},
"wazuhNotReadyYet":""
}

'mail-alerts': 'Fetch configuration. 3013 - Error connecting with socket',
'monitor-reports': {},
'csyslog-csyslog': 'Fetch configuration. 3013 - Error connecting with socket',
},
wazuhNotReadyYet: '',
};

const mockStore = configureMockStore();
const store = mockStore({});

describe('WzConfigurationAlerts component mount OK', () => {

it('renders correctly to match the snapshot', () => {
const wrapper = shallow(
<Provider store={store}>
<WzConfigurationAlerts {...mockProps} />
</Provider>
);
<Provider store={store}>
<WzConfigurationAlerts {...mockProps} />
</Provider>
);
expect(wrapper).toMatchSnapshot();
});

});
});
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,14 @@ import { Provider } from 'react-redux';
import configureMockStore from 'redux-mock-store';

jest.mock('../../../../../../kibana-services', () => ({
getAngularModule: jest.fn(),
getUiSettings: () => ({
get: (uiSetting: string) => {
if (uiSetting === 'theme:darkMode') {
return false
return false;
}
}
})
},
}),
}));

const mockStore = configureMockStore();
Expand Down
Loading