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

[Security Solution][Endpoint] several refactors of CLI tooling and associated common services #169987

Merged
merged 83 commits into from
Nov 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
83 commits
Select commit Hold shift + click to select a range
89e2425
Added `getMultipassVmCountNotice()` and `generateVmName()` to VM serv…
paul-tavares Oct 25, 2023
d3ad8ff
Create VM and enroll it with Fleet for the agentless integrations
paul-tavares Oct 25, 2023
0a58c61
General improvements + added `setDefaultLogLevelFromCliFlags()` to `c…
paul-tavares Oct 26, 2023
dbd1e2d
Refactor Run Endpoint Agent to use common fleet server service
paul-tavares Oct 26, 2023
a713078
Added support for Vagrant VMs to `createVm()`
paul-tavares Oct 26, 2023
2922b32
Refactor to use `createVm()` and its "client" creators for all types …
paul-tavares Oct 26, 2023
94a9e95
Make the fleet-server updated entry in fleet the default
paul-tavares Oct 26, 2023
2b48205
Enhanced Agent download service to auto-cleanup after each download
paul-tavares Oct 26, 2023
b7b75db
Refactor endpoint host services to use common utilities and remove du…
paul-tavares Oct 26, 2023
9d9a585
use common `startFleetServer()` from endpoint cypress suite
paul-tavares Oct 26, 2023
c12b0ec
Fix bug in vagrant VM creation
paul-tavares Oct 26, 2023
95a3a01
Fix download/extract of agent package for Vagrant VMs
paul-tavares Oct 27, 2023
6d7a4e6
add `getHostVmClient()` to endpoint host services
paul-tavares Oct 27, 2023
0d1bfea
fix `exec()` for Vagrant vms
paul-tavares Oct 27, 2023
6af9982
fix vagrant commands to execute from the vagrantfile directory
paul-tavares Oct 27, 2023
25624ff
more output of vagrant comments for debug
paul-tavares Oct 27, 2023
9ffef2d
add host name to the virutalbox provider
paul-tavares Oct 28, 2023
90ca9f2
revert change to `Vagrantfile`
paul-tavares Oct 30, 2023
4dfc4ae
adjust createVagrantHOstVmClient()
paul-tavares Oct 30, 2023
0103ecd
Merge remote-tracking branch 'upstream/main' into task/olm-scripts-cl…
paul-tavares Oct 30, 2023
09000cb
Merge remote-tracking branch 'upstream/main' into task/olm-scripts-cl…
paul-tavares Nov 1, 2023
be11402
changes mainly for vagrant
paul-tavares Nov 1, 2023
d9cabe8
fix missingg var
paul-tavares Nov 1, 2023
e2c0b11
still trying vagrant command to be successful
paul-tavares Nov 1, 2023
4df5c38
Fix error when checking fleet-server standalone is registered with ES
paul-tavares Nov 1, 2023
722e473
change cypress setup to ensure fleet server is setup and running
paul-tavares Nov 2, 2023
42da572
Merge remote-tracking branch 'upstream/main' into task/olm-scripts-cl…
paul-tavares Nov 2, 2023
96e5e1e
Add setup of fleet to cypress parallel runner based on env. variable
paul-tavares Nov 2, 2023
aa1d3bd
add log entry to start of fleet server
paul-tavares Nov 2, 2023
d39a3a9
set cypress logging level to debug
paul-tavares Nov 2, 2023
277d4cc
add log statements
paul-tavares Nov 2, 2023
8676d1b
ensure fleet server is started on the port defined in the FTR config
paul-tavares Nov 2, 2023
41a2dfc
more debug messages
paul-tavares Nov 2, 2023
5bf5de9
fix log var not being defined
paul-tavares Nov 2, 2023
af18f09
ensure fleet setup api is called prior to creating fleet server
paul-tavares Nov 2, 2023
e1f475b
fix cy task - ensure `null` is returned
paul-tavares Nov 3, 2023
c4371b2
Remove usages that check for `CI` env. and use `getHostVmClient()` in…
paul-tavares Nov 4, 2023
409759c
Merge remote-tracking branch 'upstream/main' into task/olm-scripts-cl…
paul-tavares Nov 6, 2023
343568f
Add ability for `cy.waitUntil()` to also accept a message for logging
paul-tavares Nov 6, 2023
4bffb1c
some additional logging for debug
paul-tavares Nov 6, 2023
0829eef
correct log text
paul-tavares Nov 6, 2023
e1d3f99
adjustments to `waitUntil()`
paul-tavares Nov 7, 2023
ce991fd
added `logger` task ++ remove fleet server setup cy support file
paul-tavares Nov 7, 2023
7eb7126
update tests for tamper protection
paul-tavares Nov 7, 2023
03d99c3
add log of existing agent policies to
paul-tavares Nov 7, 2023
a7dd5d5
more debug changes for osquery
paul-tavares Nov 7, 2023
f0048a6
osquery - again
paul-tavares Nov 7, 2023
d0a1a95
osquery - again
paul-tavares Nov 7, 2023
04098a8
adjust osquery debug data
paul-tavares Nov 7, 2023
4a38d1c
osquery - capture stack of call to create policy
paul-tavares Nov 7, 2023
03dd9b8
osquery: ensure policy names are unique
paul-tavares Nov 7, 2023
a8aa44d
Merge remote-tracking branch 'upstream/main' into task/olm-scripts-cl…
paul-tavares Nov 7, 2023
4d6f50d
Merge branch 'main' into task/olm-scripts-cleanup
paul-tavares Nov 7, 2023
2570cac
Merge branch 'main' into task/olm-scripts-cleanup
paul-tavares Nov 8, 2023
870dba7
Merge remote-tracking branch 'upstream/main' into task/olm-scripts-cl…
paul-tavares Nov 8, 2023
a2c7402
add `stopNow()` to StartedServer type
paul-tavares Nov 8, 2023
355c07d
Change OSQuery to use common methods for starting fleet-server
paul-tavares Nov 8, 2023
a804ddc
removed `fleet_server` from `endpoint_agent_runner` script
paul-tavares Nov 8, 2023
aa28313
remove fleet server cli options from script
paul-tavares Nov 8, 2023
67e6200
remove poc code
paul-tavares Nov 8, 2023
3df1000
increase timeout for waiting on agents to show up in fleet
paul-tavares Nov 9, 2023
2ae9bfd
capture docker container output after start
paul-tavares Nov 9, 2023
7c3f409
run all fleet serer containers flavors with network `elastic`
paul-tavares Nov 9, 2023
2e575fb
add more debug output
paul-tavares Nov 9, 2023
c62087f
fix bug in retrieving fleet server agent version + log where startFle…
paul-tavares Nov 9, 2023
7eafcb2
Osquery: fetch fleet-server URL from stack for enrolling agents via d…
paul-tavares Nov 9, 2023
666100a
add logging to `waitForHostToEnroll()`
paul-tavares Nov 9, 2023
b5d8b7a
OSQuery: revert back policy names
paul-tavares Nov 9, 2023
31ab9d8
Merge remote-tracking branch 'upstream/main' into task/olm-scripts-cl…
paul-tavares Nov 9, 2023
de52d2e
add prefixes to certain ToolingLog instances
paul-tavares Nov 9, 2023
54fe3d0
osquery: reuse policy if it already exists`
paul-tavares Nov 9, 2023
2582027
fix var name
paul-tavares Nov 9, 2023
e50de72
OsQuery: make policy names unique ++ revert changes to creatAgentPoli…
paul-tavares Nov 9, 2023
7e3c7ac
osquery: fix failing tests
paul-tavares Nov 10, 2023
a9c6861
Fix check of fleet server version when running serverless
paul-tavares Nov 10, 2023
894a32a
osQuery: only attempt to cleanup agent policy if we have ID
paul-tavares Nov 10, 2023
d5902da
osquery: ensure fleet server is setup with correct port
paul-tavares Nov 10, 2023
a3da549
Use fleet port number when starting fleet-server
paul-tavares Nov 10, 2023
ffff6d8
set tooling log level back to `info`
paul-tavares Nov 10, 2023
72c4ca6
Merge remote-tracking branch 'upstream/main' into task/olm-scripts-cl…
paul-tavares Nov 10, 2023
ae2e8f6
osQuery: try backout of unique policy name
paul-tavares Nov 12, 2023
790eee9
Merge remote-tracking branch 'upstream/main' into task/olm-scripts-cl…
paul-tavares Nov 12, 2023
20e7851
OSQuery: Revert changes to tests
paul-tavares Nov 12, 2023
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: 1 addition & 1 deletion src/dev/precommit_hook/casing_check_config.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export const IGNORE_FILE_GLOBS = [
'packages/kbn-test/jest-preset.js',
'packages/kbn-test/*/jest-preset.js',
'test/package/Vagrantfile',
'x-pack/plugins/security_solution/scripts/endpoint/endpoint_agent_runner/Vagrantfile',
'x-pack/plugins/security_solution/scripts/endpoint/common/vagrant/Vagrantfile',
'**/test/**/fixtures/**/*',

// Required to match the name in the docs.elastic.dev repo.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import { mergeWith } from 'lodash';
import type { ToolingLogTextWriterConfig } from '@kbn/tooling-log';
import { ToolingLog } from '@kbn/tooling-log';
import type { Flags } from '@kbn/dev-cli-runner';

export const RETRYABLE_TRANSIENT_ERRORS: Readonly<Array<string | RegExp>> = [
'no_shard_available_action_exception',
Expand Down Expand Up @@ -117,12 +118,20 @@ interface CreateLoggerInterface {
* on input.
*/
defaultLogLevel: ToolingLogTextWriterConfig['level'];

/**
* Set the default logging level based on the flag arguments provide to a CLI script that runs
* via `@kbn/dev-cli-runner`
* @param flags
*/
setDefaultLogLevelFromCliFlags: (flags: Flags) => void;
}

/**
* Creates an instance of `ToolingLog` that outputs to `stdout`.
* The default log `level` for all instances can be set by setting the function's `defaultLogLevel`.
* Log level can also be explicitly set on input.
* The default log `level` for all instances can be set by setting the function's `defaultLogLevel`
* property. Default logging level can also be set from CLI scripts that use the `@kbn/dev-cli-runner`
* by calling the `setDefaultLogLevelFromCliFlags(flags)` and passing in the `flags` property.
*
* @param level
*
Expand All @@ -137,3 +146,14 @@ export const createToolingLogger: CreateLoggerInterface = (level): ToolingLog =>
});
};
createToolingLogger.defaultLogLevel = 'info';
createToolingLogger.setDefaultLogLevelFromCliFlags = (flags) => {
createToolingLogger.defaultLogLevel = flags.verbose
? 'verbose'
: flags.debug
? 'debug'
: flags.silent
? 'silent'
: flags.quiet
? 'error'
: 'info';
};
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import type {
CreateUserAndRoleCyTaskOptions,
UninstallAgentFromHostTaskOptions,
IsAgentAndEndpointUninstalledFromHostTaskOptions,
LogItTaskOptions,
} from './types';
import type {
DeleteIndexedFleetEndpointPoliciesResponse,
Expand Down Expand Up @@ -86,13 +87,15 @@ declare global {
* or fail if `timeout` is reached.
* @param fn
* @param options
* @param message
*/
waitUntil(
fn: (subject?: any) => boolean | Promise<boolean> | Chainable<boolean>,
options?: Partial<{
interval: number;
timeout: number;
}>
}>,
message?: string
): Chainable<Subject>;

task(
Expand Down Expand Up @@ -217,6 +220,12 @@ declare global {
arg: IsAgentAndEndpointUninstalledFromHostTaskOptions,
options?: Partial<Loggable & Timeoutable>
): Chainable<boolean>;

task(
name: 'logIt',
arg: LogItTaskOptions,
options?: Partial<Loggable & Timeoutable>
): Chainable<null>;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,11 @@ export const getCypressBaseConfig = (
// to `debug` or `verbose` when wanting to debug tooling used by tests (ex. data indexer functions).
TOOLING_LOG_LEVEL: 'info',

// Variable works in conjunction with the Cypress parallel runner. When set to true, fleet server
// will be setup right after the Kibana stack, so that by the time cypress tests `.run()`/`.open()`,
// the env. will be all setup and we don't have to explicitly setup fleet from a test file
WITH_FLEET_SERVER: true,

// grep related configs
grepFilterSpecs: true,
grepOmitFiltered: true,
Expand All @@ -69,11 +74,12 @@ export const getCypressBaseConfig = (
experimentalRunAllSpecs: true,
experimentalMemoryManagement: true,
experimentalInteractiveRunEvents: true,
setupNodeEvents: (on: Cypress.PluginEvents, config: Cypress.PluginConfigOptions) => {
setupNodeEvents: async (on: Cypress.PluginEvents, config: Cypress.PluginConfigOptions) => {
// IMPORTANT: setting the log level should happen before any tooling is called
setupToolingLogLevel(config);

dataLoaders(on, config);

// Data loaders specific to "real" Endpoint testing
dataLoadersForRealEndpoints(on, config);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
createAgentPolicyTask,
enableAgentTamperProtectionFeatureFlagInPolicy,
unenrollAgent,
changeAgentPolicy,
reAssignFleetAgentToPolicy,
} from '../../../tasks/fleet';

import { login } from '../../../tasks/login';
Expand Down Expand Up @@ -80,10 +80,9 @@ describe.skip(
it('should unenroll from fleet without issues', () => {
waitForEndpointListPageToBeLoaded(createdHost.hostname);
// Change agent policy and wait for action to be completed
changeAgentPolicy(
reAssignFleetAgentToPolicy(
createdHost.agentId,
policyWithAgentTamperProtectionEnabled.policy_id,
3
policyWithAgentTamperProtectionEnabled.policy_id
).then((hasChanged) => {
expect(hasChanged).to.eql(true);
unenrollAgent(createdHost.agentId).then((isUnenrolled) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
createAgentPolicyTask,
enableAgentTamperProtectionFeatureFlagInPolicy,
unenrollAgent,
changeAgentPolicy,
reAssignFleetAgentToPolicy,
} from '../../../tasks/fleet';

import { login } from '../../../tasks/login';
Expand Down Expand Up @@ -79,7 +79,7 @@ describe(
it('should unenroll from fleet without issues', () => {
waitForEndpointListPageToBeLoaded(createdHost.hostname);
// Change agent policy and wait for action to be completed
changeAgentPolicy(createdHost.agentId, policy.policy_id, 3).then((hasChanged) => {
reAssignFleetAgentToPolicy(createdHost.agentId, policy.policy_id).then((hasChanged) => {
expect(hasChanged).to.eql(true);
unenrollAgent(createdHost.agentId).then((isUnenrolled) => {
expect(isUnenrolled).to.eql(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
createAgentPolicyTask,
enableAgentTamperProtectionFeatureFlagInPolicy,
unenrollAgent,
changeAgentPolicy,
reAssignFleetAgentToPolicy,
} from '../../../tasks/fleet';

import { login } from '../../../tasks/login';
Expand Down Expand Up @@ -81,10 +81,9 @@ describe(
it('should unenroll from fleet without issues', () => {
waitForEndpointListPageToBeLoaded(createdHost.hostname);
// Change agent policy and wait for action to be completed
changeAgentPolicy(
reAssignFleetAgentToPolicy(
createdHost.agentId,
secondPolicyWithAgentTamperProtectionEnabled.policy_id,
3
secondPolicyWithAgentTamperProtectionEnabled.policy_id
).then((hasChanged) => {
expect(hasChanged).to.eql(true);
unenrollAgent(createdHost.agentId).then((isUnenrolled) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
createAgentPolicyTask,
enableAgentTamperProtectionFeatureFlagInPolicy,
getUninstallToken,
changeAgentPolicy,
reAssignFleetAgentToPolicy,
isAgentAndEndpointUninstalledFromHost,
uninstallAgentFromHost,
} from '../../../tasks/fleet';
Expand Down Expand Up @@ -83,10 +83,9 @@ describe.skip(
waitForEndpointListPageToBeLoaded(createdHost.hostname);

// Change agent policy and wait for action to be completed
changeAgentPolicy(
reAssignFleetAgentToPolicy(
createdHost.agentId,
policyWithAgentTamperProtectionEnabled.policy_id,
3
policyWithAgentTamperProtectionEnabled.policy_id
).then((hasChanged) => {
expect(hasChanged).to.eql(true);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
getEndpointIntegrationVersion,
createAgentPolicyTask,
enableAgentTamperProtectionFeatureFlagInPolicy,
changeAgentPolicy,
reAssignFleetAgentToPolicy,
isAgentAndEndpointUninstalledFromHost,
uninstallAgentFromHost,
} from '../../../tasks/fleet';
Expand Down Expand Up @@ -81,7 +81,7 @@ describe.skip(
it('should uninstall from host without issues', () => {
waitForEndpointListPageToBeLoaded(createdHost.hostname);

changeAgentPolicy(createdHost.agentId, policy.policy_id, 3).then((hasChanged) => {
reAssignFleetAgentToPolicy(createdHost.agentId, policy.policy_id).then((hasChanged) => {
expect(hasChanged).to.eql(true);
uninstallAgentFromHost(createdHost.hostname).then((responseWithoutToken) => {
expect(responseWithoutToken).to.not.match(/(.*)Invalid uninstall token(.*)/);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
createAgentPolicyTask,
enableAgentTamperProtectionFeatureFlagInPolicy,
getUninstallToken,
changeAgentPolicy,
reAssignFleetAgentToPolicy,
isAgentAndEndpointUninstalledFromHost,
uninstallAgentFromHost,
} from '../../../tasks/fleet';
Expand Down Expand Up @@ -86,10 +86,9 @@ describe.skip(
waitForEndpointListPageToBeLoaded(createdHost.hostname);

// Change agent policy and wait for action to be completed
changeAgentPolicy(
reAssignFleetAgentToPolicy(
createdHost.agentId,
secondPolicyWithAgentTamperProtectionEnabled.policy_id,
3
secondPolicyWithAgentTamperProtectionEnabled.policy_id
).then((hasChanged) => {
expect(hasChanged).to.eql(true);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,8 @@
*/

// / <reference types="cypress" />
import type { ExecaReturnValue } from 'execa';
import execa from 'execa';

import { VAGRANT_CWD } from '../../../../scripts/endpoint/common/endpoint_host_services';
import { getHostVmClient } from '../../../../scripts/endpoint/common/vm_services';

export const agentActions = (on: Cypress.PluginEvents): void => {
on('task', {
Expand All @@ -20,40 +18,19 @@ export const agentActions = (on: Cypress.PluginEvents): void => {
hostname: string;
uninstallToken?: string;
}): Promise<string> => {
let result;
const hostVmClient = getHostVmClient(hostname);

try {
if (process.env.CI) {
result = await execa(
'vagrant',
[
'ssh',
'--',
`sudo elastic-agent uninstall -f ${
uninstallToken ? `--uninstall-token ${uninstallToken}` : ''
}`,
],
{
env: {
VAGRANT_CWD,
},
}
);
} else {
result = await execa(`multipass`, [
'exec',
hostname,
'--',
'sh',
'-c',
return (
await hostVmClient.exec(
`sudo elastic-agent uninstall -f ${
uninstallToken ? `--uninstall-token ${uninstallToken}` : ''
}`,
]);
}
}`
)
).stdout;
} catch (err) {
return err.stderr;
}
return result.stdout;
},

isAgentAndEndpointUninstalledFromHost: async ({
Expand All @@ -62,25 +39,10 @@ export const agentActions = (on: Cypress.PluginEvents): void => {
hostname: string;
uninstallToken?: string;
}): Promise<boolean> => {
let execaReturnValue: ExecaReturnValue<string>;
if (process.env.CI) {
execaReturnValue = await execa('vagrant', ['ssh', '--', `ls /opt/Elastic`], {
env: {
VAGRANT_CWD,
},
});
} else {
execaReturnValue = await execa(`multipass`, [
'exec',
hostname,
'--',
'sh',
'-c',
`ls /opt/Elastic`,
]);
}
const hostVmClient = getHostVmClient(hostname);
const lsOutput = await hostVmClient.exec('ls /opt/Elastic');

if (execaReturnValue.stdout === '') {
if (lsOutput.stdout === '') {
return true;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* 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 { prefixedOutputLogger } from '../../../../scripts/endpoint/common/utils';
import type { RuntimeServices } from '../../../../scripts/endpoint/common/stack_services';
import { createRuntimeServices } from '../../../../scripts/endpoint/common/stack_services';

const RUNTIME_SERVICES_CACHE = new WeakMap<Cypress.PluginConfigOptions, RuntimeServices>();

export const setupStackServicesUsingCypressConfig = async (config: Cypress.PluginConfigOptions) => {
if (RUNTIME_SERVICES_CACHE.has(config)) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return RUNTIME_SERVICES_CACHE.get(config)!;
}

const stackServices = await createRuntimeServices({
kibanaUrl: config.env.KIBANA_URL,
elasticsearchUrl: config.env.ELASTICSEARCH_URL,
fleetServerUrl: config.env.FLEET_SERVER_URL,
username: config.env.KIBANA_USERNAME,
password: config.env.KIBANA_PASSWORD,
esUsername: config.env.ELASTICSEARCH_USERNAME,
esPassword: config.env.ELASTICSEARCH_PASSWORD,
asSuperuser: true,
}).then(({ log, ...others }) => {
return {
...others,
log: prefixedOutputLogger('cy.dfw', log),
};
});

RUNTIME_SERVICES_CACHE.set(config, stackServices);

return stackServices;
};
Loading
Loading