Skip to content

Commit

Permalink
Merge branch 'main' into screenshotting/fix-potential-race-condition-…
Browse files Browse the repository at this point in the history
…when-screenshotting
  • Loading branch information
kibanamachine authored Feb 3, 2022
2 parents f5f8fbe + d90ac68 commit 4c293fa
Show file tree
Hide file tree
Showing 10 changed files with 183 additions and 78 deletions.
4 changes: 2 additions & 2 deletions x-pack/plugins/osquery/cypress/tasks/integrations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ import {
DATA_COLLECTION_SETUP_STEP,
} from '../screens/integrations';

export const addIntegration = (agent = 'Default fleet') => {
export const addIntegration = (agentPolicy = 'Default Fleet Server policy') => {
cy.getBySel(ADD_POLICY_BTN).click();
cy.getBySel(DATA_COLLECTION_SETUP_STEP).find('.euiLoadingSpinner').should('not.exist');
cy.getBySel('comboBoxInput').click().type(`${agent} {downArrow} {enter}`);
cy.getBySel('agentPolicySelect').select(agentPolicy);
cy.getBySel(CREATE_PACKAGE_POLICY_SAVE_BTN).click();
// sometimes agent is assigned to default policy, sometimes not
closeModalIfVisible();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,51 @@ describe('<RemoteClusterList />', () => {
});
});

describe('can search', () => {
let table;
let component;
let form;

const remoteClusters = [
{
name: 'simple_remote_cluster',
seeds: ['127.0.0.1:2000', '127.0.0.2:3000'],
},
{
name: 'remote_cluster_with_proxy',
proxyAddress: '192.168.0.1:80',
mode: PROXY_MODE,
},
];

beforeEach(async () => {
httpRequestsMockHelpers.setLoadRemoteClustersResponse(remoteClusters);

await act(async () => {
({ table, component, form } = setup());
});

component.update();
});

test('without any search params it should show all clusters', () => {
const { tableCellsValues } = table.getMetaData('remoteClusterListTable');
expect(tableCellsValues.length).toBe(2);
});

test('search by seed works', () => {
form.setInputValue('remoteClusterSearch', 'simple');
const { tableCellsValues } = table.getMetaData('remoteClusterListTable');
expect(tableCellsValues.length).toBe(1);
});

test('search by proxyAddress works', () => {
form.setInputValue('remoteClusterSearch', 'proxy');
const { tableCellsValues } = table.getMetaData('remoteClusterListTable');
expect(tableCellsValues.length).toBe(1);
});
});

describe('when there are multiple pages of remote clusters', () => {
let table;
let actions;
Expand All @@ -91,10 +136,18 @@ describe('<RemoteClusterList />', () => {
];

for (let i = 0; i < 29; i++) {
remoteClusters.push({
name: `name${i}`,
seeds: [],
});
if (i % 2 === 0) {
remoteClusters.push({
name: `cluster-${i}`,
seeds: [],
});
} else {
remoteClusters.push({
name: `cluster_with_proxy-${i}`,
proxyAddress: `127.0.0.1:10${i}`,
mode: PROXY_MODE,
});
}
}

beforeEach(async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,22 @@ const getFilteredClusters = (clusters, queryText) => {
const normalizedSearchText = queryText.toLowerCase();

return clusters.filter((cluster) => {
const { name, seeds } = cluster;
const { name, seeds, proxyAddress } = cluster;
const normalizedName = name.toLowerCase();

if (normalizedName.toLowerCase().includes(normalizedSearchText)) {
return true;
}

return seeds.some((seed) => seed.includes(normalizedSearchText));
if (proxyAddress && proxyAddress.toLowerCase().includes(normalizedSearchText)) {
return true;
}

if (seeds) {
return seeds.some((seed) => seed.includes(normalizedSearchText));
}

return false;
});
} else {
return clusters;
Expand Down Expand Up @@ -81,6 +90,11 @@ export class RemoteClusterTable extends Component {
}

onSearch = ({ query }) => {
// There's no need to update the state if there arent any search params
if (!query) {
return;
}

const { clusters } = this.props;
const { text } = query;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,30 @@
import type { CreateExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types';
import { ENDPOINT_EVENT_FILTERS_LIST_ID } from '@kbn/securitysolution-list-constants';
import { BaseDataGenerator } from './base_data_generator';
import { getCreateExceptionListItemSchemaMock } from '../../../../lists/common/schemas/request/create_exception_list_item_schema.mock';
import { ExceptionsListItemGenerator } from './exceptions_list_item_generator';
import { BY_POLICY_ARTIFACT_TAG_PREFIX, GLOBAL_ARTIFACT_TAG } from '../service/artifacts';

const EFFECT_SCOPE_TYPES = ['policy:', 'policy:all'];
const EFFECT_SCOPE_TYPES = [BY_POLICY_ARTIFACT_TAG_PREFIX, GLOBAL_ARTIFACT_TAG];
export class EventFilterGenerator extends BaseDataGenerator<CreateExceptionListItemSchema> {
generate(): CreateExceptionListItemSchema {
const overrides: Partial<CreateExceptionListItemSchema> = {
name: `generator event ${this.randomString(5)}`,
list_id: ENDPOINT_EVENT_FILTERS_LIST_ID,
item_id: `generator_endpoint_event_filter_${this.randomUUID()}`,
os_types: [this.randomOSFamily()] as CreateExceptionListItemSchema['os_types'],
tags: [this.randomChoice(EFFECT_SCOPE_TYPES)],
namespace_type: 'agnostic',
meta: undefined,
};

return Object.assign<CreateExceptionListItemSchema, Partial<CreateExceptionListItemSchema>>(
getCreateExceptionListItemSchemaMock(),
overrides
const eventFilterGenerator = new ExceptionsListItemGenerator();
const eventFilterData: CreateExceptionListItemSchema = eventFilterGenerator.generateEventFilter(
{
name: `Generated event ${this.randomString(5)}`,
item_id: `generator_endpoint_event_filter_${this.randomUUID()}`,
list_id: ENDPOINT_EVENT_FILTERS_LIST_ID,
os_types: [this.randomOSFamily()] as CreateExceptionListItemSchema['os_types'],
tags: [this.randomChoice(EFFECT_SCOPE_TYPES)],
_version: undefined,
created_at: undefined,
created_by: undefined,
id: undefined,
tie_breaker_id: undefined,
updated_at: undefined,
updated_by: undefined,
}
);

return eventFilterData;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,21 @@ type HostIsolationExceptionPaginatedContent = PaginatedContentProps<
typeof ExceptionItem
>;

/* eslint-disable complexity */
const getPaginationObject = ({
total = 0,
perPage = MANAGEMENT_DEFAULT_PAGE_SIZE,
page = 1,
}: {
total?: number;
perPage?: number;
page?: number;
}) => ({
totalItemCount: total,
pageSize: perPage,
pageSizeOptions: [...MANAGEMENT_PAGE_SIZE_OPTIONS],
pageIndex: page - 1,
});

export const HostIsolationExceptionsList = () => {
const history = useHistory();
const privileges = useUserPrivileges().endpointPrivileges;
Expand Down Expand Up @@ -102,12 +116,11 @@ export const HostIsolationExceptionsList = () => {
},
});

const pagination = {
totalItemCount: data?.total ?? 0,
pageSize: data?.per_page ?? MANAGEMENT_DEFAULT_PAGE_SIZE,
pageSizeOptions: [...MANAGEMENT_PAGE_SIZE_OPTIONS],
pageIndex: (data?.page ?? 1) - 1,
};
const pagination = getPaginationObject({
total: data?.total,
perPage: data?.per_page,
page: data?.page,
});

const listItems = data?.data || [];
const allListItems = allData?.data || [];
Expand Down
15 changes: 4 additions & 11 deletions x-pack/test/osquery_cypress/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,31 +11,24 @@ import { ChildProcess, spawn } from 'child_process';
import { getLatestVersion } from './artifact_manager';
import { Manager } from './resource_manager';

interface AgentManagerParams {
export interface AgentManagerParams {
user: string;
password: string;
kibanaUrl: string;
esHost: string;
esPort: string;
}

export class AgentManager extends Manager {
private params: AgentManagerParams;
private log: ToolingLog;
private agentProcess?: ChildProcess;
private requestOptions: AxiosRequestConfig;
constructor(params: AgentManagerParams, log: ToolingLog) {
constructor(params: AgentManagerParams, log: ToolingLog, requestOptions: AxiosRequestConfig) {
super();
this.log = log;
this.params = params;
this.requestOptions = {
headers: {
'kbn-xsrf': 'kibana',
},
auth: {
username: this.params.user,
password: this.params.password,
},
};
this.requestOptions = requestOptions;
}

public async setup() {
Expand Down
9 changes: 5 additions & 4 deletions x-pack/test/osquery_cypress/artifact_manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
* 2.0.
*/

import axios from 'axios';
import { last } from 'lodash';
// import axios from 'axios';
// import { last } from 'lodash';

export async function getLatestVersion(): Promise<string> {
const response: any = await axios('https://artifacts-api.elastic.co/v1/versions');
return last(response.data.versions as string[]) || '8.1.0-SNAPSHOT';
return '8.0.0-SNAPSHOT';
// const response: any = await axios('https://artifacts-api.elastic.co/v1/versions');
// return last(response.data.versions as string[]) || '8.1.0-SNAPSHOT';
}
46 changes: 32 additions & 14 deletions x-pack/test/osquery_cypress/fleet_server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,34 +7,49 @@

import { ChildProcess, spawn } from 'child_process';
import { ToolingLog } from '@kbn/dev-utils';
import axios from 'axios';
import axios, { AxiosRequestConfig } from 'axios';
import { Manager } from './resource_manager';
import { getLatestVersion } from './artifact_manager';

export interface ElasticsearchConfig {
esHost: string;
user: string;
password: string;
port: string;
}
import { AgentManagerParams } from './agent';

export class FleetManager extends Manager {
private fleetProcess?: ChildProcess;
private esConfig: ElasticsearchConfig;
private config: AgentManagerParams;
private log: ToolingLog;
constructor(esConfig: ElasticsearchConfig, log: ToolingLog) {
private requestOptions: AxiosRequestConfig;
constructor(config: AgentManagerParams, log: ToolingLog, requestOptions: AxiosRequestConfig) {
super();
this.esConfig = esConfig;
this.config = config;
this.log = log;
this.requestOptions = requestOptions;
}
public async setup(): Promise<void> {
this.log.info('Setting fleet up');
return new Promise(async (res, rej) => {
try {
// default fleet server policy no longer created by default
const {
data: {
item: { id: policyId },
},
} = await axios.post(
`${this.config.kibanaUrl}/api/fleet/agent_policies`,
{
name: 'Default Fleet Server policy',
description: '',
namespace: 'default',
monitoring_enabled: ['logs', 'metrics'],
has_fleet_server: true,
},
this.requestOptions
);

const response = await axios.post(
`${this.esConfig.esHost}/_security/service/elastic/fleet-server/credential/token`
`${this.config.kibanaUrl}/api/fleet/service_tokens`,
{},
this.requestOptions
);
const serviceToken = response.data.token.value;
const serviceToken = response.data.value;
const artifact = `docker.elastic.co/beats/elastic-agent:${await getLatestVersion()}`;
this.log.info(artifact);

Expand All @@ -49,12 +64,15 @@ export class FleetManager extends Manager {
'--env',
'FLEET_SERVER_ENABLE=true',
'--env',
`FLEET_SERVER_ELASTICSEARCH_HOST=http://${host}:${this.esConfig.port}`,
`FLEET_SERVER_ELASTICSEARCH_HOST=http://${host}:${this.config.esPort}`,
'--env',
`FLEET_SERVER_SERVICE_TOKEN=${serviceToken}`,
'--env',
`FLEET_SERVER_POLICY=${policyId}`,
'--rm',
artifact,
];
this.log.info('docker ' + args.join(' '));
this.fleetProcess = spawn('docker', args, {
stdio: 'inherit',
});
Expand Down
Loading

0 comments on commit 4c293fa

Please sign in to comment.