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

Deprecate csp rule #147878

Merged
merged 29 commits into from
Dec 26, 2022
Merged
Show file tree
Hide file tree
Changes from 26 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
509be27
Working version - before running tests
ofiriro3 Dec 6, 2022
d36ffc6
Fixing the benchmark tests
ofiriro3 Dec 6, 2022
92c248a
Remove posthook for creation of the csp rules
ofiriro3 Dec 6, 2022
4c53652
Revert benchmark in URL
ofiriro3 Dec 7, 2022
7b626e6
fixing tests
ofiriro3 Dec 7, 2022
ed194ff
After the first self review
ofiriro3 Dec 7, 2022
ff75c8e
Replacing isCspExist code by using fleet
ofiriro3 Dec 19, 2022
d2bc4bf
Working version
ofiriro3 Dec 19, 2022
122cd8a
Fixing tests
ofiriro3 Dec 19, 2022
997d53c
Fixing tests
ofiriro3 Dec 20, 2022
e6e42be
Updating test with test cases
ofiriro3 Dec 20, 2022
cc53b2d
Fixing type checks
ofiriro3 Dec 20, 2022
a394992
Adding tests + refactoring
ofiriro3 Dec 20, 2022
a558f94
adding tests + refactoring
ofiriro3 Dec 20, 2022
8890b16
chaning the schema
ofiriro3 Dec 20, 2022
d1aa7c3
Merge remote-tracking branch 'refs/remotes/origin/deprecate_csp_rule'…
ofiriro3 Dec 20, 2022
fbf501b
Merge branch 'elastic:main' into deprecate_csp_rule
ofiriro3 Dec 20, 2022
9064bec
Updating csp_finding.ts to use csp_rule_template
ofiriro3 Dec 21, 2022
3d41913
Merge remote-tracking branch 'origin/deprecate_csp_rule' into depreca…
ofiriro3 Dec 21, 2022
7f589d3
Revert csp_finding.ts was pushed accidentally
ofiriro3 Dec 22, 2022
005ba5b
Code review comments fixes
ofiriro3 Dec 26, 2022
8d84746
Correct it to import type
ofiriro3 Dec 26, 2022
1af5bdc
merging main
ofiriro3 Dec 26, 2022
baf4098
[CI] Auto-commit changed files from 'node scripts/ts_project_linter -…
kibanamachine Dec 26, 2022
ca37e64
Fixing test to use test cases rather than using string tagged templates
ofiriro3 Dec 26, 2022
ebe91a1
Merge remote-tracking branch 'origin/deprecate_csp_rule' into depreca…
ofiriro3 Dec 26, 2022
253767a
Merge branch 'main' into deprecate_csp_rule
ofiriro3 Dec 26, 2022
e696bb9
Merge main to mine
ofiriro3 Dec 26, 2022
0b3cd27
[CI] Auto-commit changed files from 'node scripts/ts_project_linter -…
kibanamachine Dec 26, 2022
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 @@ -79,7 +79,7 @@ describe('checking migration metadata changes on all registered SO types', () =>
"config-global": "b8f559884931609a349e129c717af73d23e7bc76",
"connector_token": "fa5301aa5a2914795d3b1b82d0a49939444009da",
"core-usage-stats": "f40a213da2c597b0de94e364a4326a5a1baa4ca9",
"csp-rule-template": "3679c5f2431da8153878db79c78a4e695357fb61",
"csp-rule-template": "d7e403244d466ee0daaf75e1616b9c5d5fd8c1cb",
"csp_rule": "d2bb53ea5d2bdfba1a835ad8956dfcd2b2c32e19",
"dashboard": "7e37790f802b39c852f905c010e13674e893105a",
"endpoint:user-artifact": "f94c250a52b30d0a2d32635f8b4c5bdabd1e25c0",
Expand Down
8 changes: 1 addition & 7 deletions x-pack/plugins/cloud_security_posture/common/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,18 +90,12 @@ interface CspSetupInstalledStatus extends BaseCspSetupStatus {

export type CspSetupStatus = CspSetupInstalledStatus | CspSetupNotInstalledStatus;

export interface CspRulesStatus {
all: number;
enabled: number;
disabled: number;
}

export type AgentPolicyStatus = Pick<AgentPolicy, 'id' | 'name'> & { agents: number };

export interface Benchmark {
package_policy: PackagePolicy;
agent_policy: AgentPolicyStatus;
rules: CspRulesStatus;
rules_count: number;
}

export type BenchmarkId = CspRuleMetadata['benchmark']['id'];
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { createPackagePolicyMock } from '@kbn/fleet-plugin/common/mocks';
import { getBenchmarkFromPackagePolicy, getBenchmarkTypeFilter } from './helpers';

describe('test helper methods', () => {
it('get default integration type from inputs with multiple enabled types', () => {
orouz marked this conversation as resolved.
Show resolved Hide resolved
const mockPackagePolicy = createPackagePolicyMock();

// Both enabled falls back to default
mockPackagePolicy.inputs = [
{ type: 'cloudbeat/cis_k8s', enabled: true, streams: [] },
{ type: 'cloudbeat/cis_eks', enabled: true, streams: [] },
];
const type = getBenchmarkFromPackagePolicy(mockPackagePolicy.inputs);
expect(type).toMatch('cis_k8s');
});

it('get default integration type from inputs without any enabled types', () => {
const mockPackagePolicy = createPackagePolicyMock();

// None enabled falls back to default
mockPackagePolicy.inputs = [
{ type: 'cloudbeat/cis_k8s', enabled: false, streams: [] },
{ type: 'cloudbeat/cis_eks', enabled: false, streams: [] },
];
const type = getBenchmarkFromPackagePolicy(mockPackagePolicy.inputs);
expect(type).toMatch('cis_k8s');
});

it('get EKS integration type', () => {
const mockPackagePolicy = createPackagePolicyMock();

// Single EKS selected
mockPackagePolicy.inputs = [
{ type: 'cloudbeat/cis_eks', enabled: true, streams: [] },
{ type: 'cloudbeat/cis_k8s', enabled: false, streams: [] },
];
const typeEks = getBenchmarkFromPackagePolicy(mockPackagePolicy.inputs);
expect(typeEks).toMatch('cis_eks');
});

it('get Vanilla K8S integration type', () => {
const mockPackagePolicy = createPackagePolicyMock();

// Single k8s selected
mockPackagePolicy.inputs = [
{ type: 'cloudbeat/cis_eks', enabled: false, streams: [] },
{ type: 'cloudbeat/cis_k8s', enabled: true, streams: [] },
];
const typeK8s = getBenchmarkFromPackagePolicy(mockPackagePolicy.inputs);
expect(typeK8s).toMatch('cis_k8s');
});
it('get benchmark type filter based on a benchmark id', () => {
const typeFilter = getBenchmarkTypeFilter('cis_eks');
expect(typeFilter).toMatch('csp-rule-template.attributes.metadata.benchmark.id: "cis_eks"');
});
});
52 changes: 41 additions & 11 deletions x-pack/plugins/cloud_security_posture/common/utils/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,19 @@
*/

import { Truthy } from 'lodash';
import { CSP_RULE_SAVED_OBJECT_TYPE } from '../constants';
import {
NewPackagePolicy,
NewPackagePolicyInput,
PACKAGE_POLICY_SAVED_OBJECT_TYPE,
PackagePolicy,
PackagePolicyInput,
} from '@kbn/fleet-plugin/common';
import {
CLOUD_SECURITY_POSTURE_PACKAGE_NAME,
CLOUDBEAT_VANILLA,
CSP_RULE_TEMPLATE_SAVED_OBJECT_TYPE,
} from '../constants';
import { BenchmarkId } from '../types';

/**
* @example
Expand All @@ -25,16 +37,34 @@ export const extractErrorMessage = (e: unknown, defaultMessage = 'Unknown Error'
return defaultMessage; // TODO: i18n
};

export const createCspRuleSearchFilterByPackagePolicy = ({
packagePolicyId,
policyId,
}: {
packagePolicyId: string;
policyId?: string;
}): string =>
`${CSP_RULE_SAVED_OBJECT_TYPE}.attributes.package_policy_id: "${packagePolicyId}"${
policyId ? ` AND ${CSP_RULE_SAVED_OBJECT_TYPE}.attributes.policy_id: "${policyId}"` : ''
}`;
export const getBenchmarkTypeFilter = (type: BenchmarkId): string =>
`${CSP_RULE_TEMPLATE_SAVED_OBJECT_TYPE}.attributes.metadata.benchmark.id: "${type}"`;

export const isEnabledBenchmarkInputType = (input: PackagePolicyInput | NewPackagePolicyInput) =>
input.enabled;

export const isCspPackage = (packageName?: string) =>
packageName === CLOUD_SECURITY_POSTURE_PACKAGE_NAME;

export const getBenchmarkFromPackagePolicy = (
inputs: PackagePolicy['inputs'] | NewPackagePolicy['inputs']
): BenchmarkId => {
const enabledInputs = inputs.filter(isEnabledBenchmarkInputType);

// Use the only enabled input
if (enabledInputs.length === 1) {
return getInputType(enabledInputs[0].type);
}

// Use the default benchmark id for multiple/none selected
return getInputType(CLOUDBEAT_VANILLA);
};
orouz marked this conversation as resolved.
Show resolved Hide resolved

const getInputType = (inputType: string): string => {
// Get the last part of the input type, input type structure: cloudbeat/<benchmark_id>
return inputType.split('/')[1];
};
export const getCSPKuery = `${PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name:${CLOUD_SECURITY_POSTURE_PACKAGE_NAME}`;

export function assert(condition: any, msg?: string): asserts condition {
if (!condition) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ const IntegrationButtonLink = ({
policyId: string;
}) => {
const { application } = useKibana().services;

return (
<EuiLink
href={application.getUrlForApp('security', {
Expand Down Expand Up @@ -83,7 +82,7 @@ const BENCHMARKS_TABLE_COLUMNS: Array<EuiBasicTableColumn<Benchmark>> = [
'data-test-subj': TEST_SUBJ.BENCHMARKS_TABLE_COLUMNS.INTEGRATION_NAME,
},
{
field: 'rules.enabled',
field: 'rules_count',
name: i18n.translate('xpack.csp.benchmarks.benchmarksTable.rulesColumnTitle', {
defaultMessage: 'Rules',
}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,9 @@ const getWrapper =
};

const getRuleMock = ({
packagePolicyId = chance.guid(),
policyId = chance.guid(),
savedObjectId = chance.guid(),
id = chance.guid(),
enabled,
}: {
packagePolicyId?: string;
policyId?: string;
savedObjectId?: string;
id?: string;
enabled: boolean;
Expand All @@ -73,6 +68,7 @@ const getRuleMock = ({
benchmark: {
name: chance.word(),
version: chance.sentence(),
id: chance.word(),
},
default_value: chance.sentence(),
description: chance.sentence(),
Expand All @@ -88,15 +84,11 @@ const getRuleMock = ({
tags: [chance.word(), chance.word()],
version: chance.sentence(),
},
package_policy_id: packagePolicyId,
policy_id: policyId,
enabled,
muted: false,
},
} as RuleSavedObject);

const params = {
policyId: chance.guid(),
packagePolicyId: chance.guid(),
};

Expand All @@ -118,6 +110,7 @@ describe('<RulesContainer />', () => {
total: 1,
savedObjects: [rule1],
},
policyId: params.packagePolicyId,
});

render(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,7 @@
import React, { useState, useMemo } from 'react';
import { EuiPanel, EuiSpacer } from '@elastic/eui';
import { useParams } from 'react-router-dom';
import {
extractErrorMessage,
createCspRuleSearchFilterByPackagePolicy,
isNonNullable,
} from '../../../common/utils/helpers';
import { extractErrorMessage, isNonNullable } from '../../../common/utils/helpers';
import { RulesTable } from './rules_table';
import { RulesTableHeader } from './rules_table_header';
import {
Expand Down Expand Up @@ -72,21 +68,21 @@ export const RulesContainer = () => {
const [selectedRuleId, setSelectedRuleId] = useState<string | null>(null);
const { pageSize, setPageSize } = usePageSize(LOCAL_STORAGE_PAGE_SIZE_RULES_KEY);
const [rulesQuery, setRulesQuery] = useState<RulesQuery>({
filter: createCspRuleSearchFilterByPackagePolicy({
packagePolicyId: params.packagePolicyId,
policyId: params.policyId,
}),
filter: '',
search: '',
page: 0,
perPage: pageSize || 10,
});

const { data, status, error } = useFindCspRules({
filter: rulesQuery.filter,
search: rulesQuery.search,
page: 1,
perPage: MAX_ITEMS_PER_PAGE,
});
const { data, status, error } = useFindCspRules(
{
filter: rulesQuery.filter,
search: rulesQuery.search,
page: 1,
perPage: MAX_ITEMS_PER_PAGE,
},
params.packagePolicyId
);

const rulesPageData = useMemo(
() => getRulesPageData({ data, error, status }, rulesQuery),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,29 +7,46 @@
import { useQuery } from '@tanstack/react-query';
import { FunctionKeys } from 'utility-types';
import type { SavedObjectsFindOptions, SimpleSavedObject } from '@kbn/core/public';
import { CSP_RULE_SAVED_OBJECT_TYPE } from '../../../common/constants';
import type { CspRule } from '../../../common/schemas';
import { NewPackagePolicy, PACKAGE_POLICY_SAVED_OBJECT_TYPE } from '@kbn/fleet-plugin/common';
import {
getBenchmarkFromPackagePolicy,
getBenchmarkTypeFilter,
} from '../../../common/utils/helpers';
import { CSP_RULE_TEMPLATE_SAVED_OBJECT_TYPE } from '../../../common/constants';
import { CspRuleTemplate } from '../../../common/schemas';
import { useKibana } from '../../common/hooks/use_kibana';

export type RuleSavedObject = Omit<SimpleSavedObject<CspRule>, FunctionKeys<SimpleSavedObject>>;
export type RuleSavedObject = Omit<
SimpleSavedObject<CspRuleTemplate>,
FunctionKeys<SimpleSavedObject>
>;

export type RulesQuery = Required<
Pick<SavedObjectsFindOptions, 'search' | 'page' | 'perPage' | 'filter'>
>;
export type RulesQueryResult = ReturnType<typeof useFindCspRules>;

export const useFindCspRules = ({ search, page, perPage, filter }: RulesQuery) => {
export const useFindCspRules = (
{ search, page, perPage, filter }: RulesQuery,
packagePolicyId: string
) => {
const { savedObjects } = useKibana().services;

return useQuery([CSP_RULE_SAVED_OBJECT_TYPE, { search, page, perPage }], () =>
savedObjects.client.find<CspRule>({
type: CSP_RULE_SAVED_OBJECT_TYPE,
search: search ? `"${search}"*` : '',
searchFields: ['metadata.name.text'],
page: 1,
sortField: 'metadata.name',
perPage,
filter,
})
return useQuery([CSP_RULE_TEMPLATE_SAVED_OBJECT_TYPE, { search, page, perPage }], () =>
savedObjects.client
.get<NewPackagePolicy>(PACKAGE_POLICY_SAVED_OBJECT_TYPE, packagePolicyId)
.then((res) => {
const benchmarkId = getBenchmarkFromPackagePolicy(res.attributes.inputs);

return savedObjects.client.find<CspRuleTemplate>({
type: CSP_RULE_TEMPLATE_SAVED_OBJECT_TYPE,
search: search ? `"${search}"*` : '',
searchFields: ['metadata.name.text'],
page: 1,
sortField: 'metadata.name',
perPage,
filter: getBenchmarkTypeFilter(benchmarkId),
});
})
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,9 @@ export const createCspBenchmarkIntegrationFixture = ({
name: chance.sentence(),
agents: chance.integer({ min: 0 }),
},
rules = {
all: chance.integer(),
enabled: chance.integer(),
disabled: chance.integer(),
},
rules_count = chance.integer({ min: 0, max: 10 }),
}: CreateCspBenchmarkIntegrationFixtureInput = {}): Benchmark => ({
package_policy,
agent_policy,
rules,
rules_count,
});
Loading