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

Fix readonly user cannot read statistics #7001

Merged
merged 19 commits into from
Sep 20, 2024
Merged
Show file tree
Hide file tree
Changes from 15 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
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
} from '../../../../../../../src/plugins/data/public';
import { search } from '../../search-bar/search-bar-service';
import { PatternDataSourceFilterManager } from './pattern-data-source-filter-manager';
import { useSelector } from 'react-redux';

export class PatternDataSource implements tDataSource {
id: string;
Expand Down Expand Up @@ -52,7 +53,9 @@ export class PatternDataSource implements tDataSource {
);
const scripted = pattern.getScriptedFields().map(field => field.spec);
pattern.fields.replaceAll([...fields, ...scripted]);
await this.patternService.updateSavedObject(pattern);
try {
await this.patternService.updateSavedObject(pattern);
} catch {}
} else {
throw new Error('Error selecting index pattern: pattern not found');
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ import React from 'react';
import { compose } from 'redux';
import { connect } from 'react-redux';
import { withGuardAsync } from '../../../../common/hocs';
import { getSavedObjects } from '../../../../../kibana-services';
import { SavedObject } from '../../../../../react-services';
import { NOT_TIME_FIELD_NAME_INDEX_PATTERN } from '../../../../../../common/constants';
import {
verifyExistenceIndices,
verifyExistenceIndexPattern,
createIndexPattern,
} from '../../../../../react-services';
import { EuiButton, EuiEmptyPrompt, EuiLink } from '@elastic/eui';
import { webDocumentationLink } from '../../../../../../common/services/web_documentation';
import { vulnerabilityDetection } from '../../../../../utils/applications';
Expand All @@ -13,50 +15,18 @@ import NavigationService from '../../../../../react-services/navigation-service'

const INDEX_PATTERN_CREATION_NO_INDEX = 'INDEX_PATTERN_CREATION_NO_INDEX';

async function checkExistenceIndexPattern(indexPatternID: string) {
return await getSavedObjects().client.get('index-pattern', indexPatternID);
}

async function checkExistenceIndices(indexPatternId: string) {
try {
const fields = await SavedObject.getIndicesFields(indexPatternId);
return { exist: true, fields };
} catch (error) {
return { exist: false };
}
}

async function createIndexPattern(indexPattern, fields: any) {
try {
await SavedObject.createSavedObject(
'index-pattern',
indexPattern,
{
attributes: {
title: indexPattern,
timeFieldName: NOT_TIME_FIELD_NAME_INDEX_PATTERN,
},
},
fields,
);
await SavedObject.validateIndexPatternSavedObjectCanBeFound([indexPattern]);
} catch (error) {
return { error: error.message };
}
}

export async function validateVulnerabilitiesStateDataSources({
vulnerabilitiesStatesindexPatternID: indexPatternID,
}) {
try {
// Check the existence of related index pattern
const existIndexPattern = await checkExistenceIndexPattern(indexPatternID);
let indexPattern = existIndexPattern;
const existIndexPattern = await verifyExistenceIndexPattern(indexPatternID);
const indexPattern = existIndexPattern;

// If the idnex pattern does not exist, then check the existence of index
if (existIndexPattern?.error?.statusCode === 404) {
// Check the existence of indices
const { exist, fields } = await checkExistenceIndices(indexPatternID);
const { exist, fields } = await verifyExistenceIndices(indexPatternID);

if (!exist) {
return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,22 @@
* Find more information about this on the LICENSE file.
*/

import React, { useState, useEffect } from 'react';
import React from 'react';
import { EuiEmptyPrompt } from '@elastic/eui';
import { StatisticsDataSource } from '../../../../../components/common/data-source/pattern/statistics';

export const PromptStatisticsNoIndices = () => {
const [indexName, setIndexName] = useState('');

useEffect(() => {
const STATISTICS_PATTERN_IDENTIFIER =
StatisticsDataSource.getIdentifierDataSourcePattern();
setIndexName(STATISTICS_PATTERN_IDENTIFIER);
}, []);

return (
export const PromptStatisticsNoIndices = ({
indexPatternID,
existIndexPattern,
}) => {
return existIndexPattern ? (
<EuiEmptyPrompt
iconType='securitySignalDetected'
title={<h2>{indexPatternID} indices were not found.</h2>}
/>
) : (
<EuiEmptyPrompt
iconType='securitySignalDetected'
title={<h2>{indexName} indices were not found.</h2>}
title={<h2>There was a problem creating the index pattern.</h2>}
/>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ import {
} from '../../../../../components/common/hocs';
import { PromptStatisticsDisabled } from './prompt-statistics-disabled';
import { PromptStatisticsNoIndices } from './prompt-statistics-no-indices';
import { WzRequest } from '../../../../../react-services/wz-request';
import { UI_ERROR_SEVERITIES } from '../../../../../react-services/error-orchestrator/types';
import { UI_LOGGER_LEVELS } from '../../../../../../common/constants';
import { getErrorOrchestrator } from '../../../../../react-services/common-services';
Expand All @@ -43,6 +42,12 @@ import { RedirectAppLinks } from '../../../../../../../../src/plugins/opensearch
import { DashboardTabsPanels } from '../../../../../components/overview/server-management-statistics/dashboards/dashboardTabsPanels';
import { connect } from 'react-redux';
import NavigationService from '../../../../../react-services/navigation-service';
import {
verifyExistenceIndices,
verifyExistenceIndexPattern,
createIndexPattern,
} from '../../../../../react-services';
import { StatisticsDataSource } from '../../../../../components/common/data-source/pattern/statistics';

export class WzStatisticsOverview extends Component {
_isMounted = false;
Expand Down Expand Up @@ -222,6 +227,7 @@ const mapStateToProps = state => ({
statisticsEnabled: state.appConfig.data?.['cron.statistics.status'],
configurationUIEditable:
state.appConfig.data?.['configuration.ui_api_editable'],
statisticsIndexPatternID: `${state.appConfig.data['cron.prefix']}-${state.appConfig.data['cron.statistics.index.name']}*`,
});

export default compose(
Expand All @@ -237,12 +243,41 @@ export default compose(
)(props => {
const [loading, setLoading] = useState(false);
const [existStatisticsIndices, setExistStatisticsIndices] = useState(false);
const [existStatisticsIndexPattern, setExistStatisticsIndexPattern] =
useState(false);
const indexPatternID = StatisticsDataSource.getIdentifierDataSourcePattern();
useEffect(() => {
const fetchData = async () => {
try {
// Check the existence of related index pattern
const existIndexPattern = await verifyExistenceIndexPattern(
indexPatternID,
);
setLoading(true);
const data = await WzRequest.genericReq('GET', '/elastic/statistics');
setExistStatisticsIndices(data.data);

// If the index pattern does not exist, then check the existence of index
if (existIndexPattern?.error?.statusCode === 404) {
Tostti marked this conversation as resolved.
Show resolved Hide resolved
// Check the existence of indices
const { exist, fields } = await verifyExistenceIndices(
indexPatternID,
);
if (!exist) {
setLoading(false);
return;
}
setExistStatisticsIndices(true);
// If the some index match the index pattern, then create the index pattern
const resultCreateIndexPattern = await createIndexPattern(
indexPatternID,
fields,
);
if (resultCreateIndexPattern?.error) {
setLoading(false);
return;
}
}
setExistStatisticsIndexPattern(true);
setExistStatisticsIndices(true);
} catch (error) {
setLoading(false);
const options = {
Expand All @@ -265,9 +300,12 @@ export default compose(
if (loading) {
return <EuiProgress size='xs' color='primary' />;
}
return existStatisticsIndices ? (
return existStatisticsIndices && existStatisticsIndexPattern ? (
<WzStatisticsOverview {...props} />
) : (
<PromptStatisticsNoIndices {...props} />
<PromptStatisticsNoIndices
indexPatternID={indexPatternID}
existIndexPattern={existStatisticsIndexPattern}
/>
);
});
35 changes: 35 additions & 0 deletions plugins/main/public/react-services/check-index.ts
Tostti marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { SavedObject } from '.';
import { getSavedObjects } from '../kibana-services';
import { NOT_TIME_FIELD_NAME_INDEX_PATTERN } from '../../common/constants';

export async function verifyExistenceIndices(indexPatternId: string) {
try {
const fields = await SavedObject.getIndicesFields(indexPatternId);
return { exist: true, fields };
} catch (error) {
return { exist: false };
}
}

export async function verifyExistenceIndexPattern(indexPatternID: string) {
return await getSavedObjects().client.get('index-pattern', indexPatternID);
}

export async function createIndexPattern(indexPattern, fields: any) {
try {
await SavedObject.createSavedObject(
'index-pattern',
indexPattern,
{
attributes: {
title: indexPattern,
timeFieldName: NOT_TIME_FIELD_NAME_INDEX_PATTERN,
},
},
fields,
);
await SavedObject.validateIndexPatternSavedObjectCanBeFound([indexPattern]);
} catch (error) {
return { error: error.message };
}
}
1 change: 1 addition & 0 deletions plugins/main/public/react-services/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ export * from './wz-security-opensearch-dashboards-security';
export * from './wz-user-permissions';
export * from './query-config';
export * from './elastic_helpers';
export * from './check-index';
23 changes: 0 additions & 23 deletions plugins/main/server/controllers/wazuh-elastic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -681,29 +681,6 @@ export class WazuhElasticCtrl {
}
}

// Check if there are indices for Statistics
async existStatisticsIndices(
context: RequestHandlerContext,
request: OpenSearchDashboardsRequest,
response: OpenSearchDashboardsResponseFactory,
) {
try {
const config = await context.wazuh_core.configuration.get();
const statisticsPattern = `${config['cron.prefix']}-${config['cron.statistics.index.name']}*`;
const existIndex =
await context.core.opensearch.client.asCurrentUser.indices.exists({
index: statisticsPattern,
allow_no_indices: false,
});
return response.ok({
body: existIndex.body,
});
} catch (error) {
context.wazuh.logger.error(error.message || error);
return ErrorResponse(error.message || error, 1000, 500, response);
}
}

getErrorDetails(error) {
const statusCode = error?.meta?.statusCode || 500;
let errorMessage = error.message;
Expand Down
Loading
Loading