Skip to content

Commit

Permalink
Merge branch 'main' into 155110-inventory-views-client
Browse files Browse the repository at this point in the history
  • Loading branch information
tonyghiani authored Apr 24, 2023
2 parents efa4910 + 792c786 commit ec45b8d
Show file tree
Hide file tree
Showing 24 changed files with 595 additions and 65 deletions.
4 changes: 2 additions & 2 deletions src/plugins/newsfeed/public/components/flyout_list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,11 @@ import { NewsLoadingPrompt } from './loading_news';
export const NewsfeedFlyout = (props: Partial<EuiFlyoutProps> & { showPlainSpinner: boolean }) => {
const { newsFetchResult, setFlyoutVisible } = useContext(NewsfeedContext);
const closeFlyout = useCallback(() => setFlyoutVisible(false), [setFlyoutVisible]);

const { showPlainSpinner, ...rest } = props;
return (
<EuiPortal>
<EuiFlyout
{...props}
{...rest}
onClose={closeFlyout}
size="s"
aria-labelledby="flyoutSmallTitle"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export const createActionAttachmentUserActionBuilder = ({
// TODO: Fix this manually. Issue #123375
// eslint-disable-next-line react/display-name
build: () => {
const actionIconName = comment.actions.type === 'isolate' ? 'lock' : 'lockOpen';
return [
{
username: (
Expand All @@ -52,7 +53,8 @@ export const createActionAttachmentUserActionBuilder = ({
),
'data-test-subj': 'endpoint-action',
timestamp: <UserActionTimestamp createdAt={userAction.createdAt} />,
timelineAvatar: comment.actions.type === 'isolate' ? 'lock' : 'lockOpen',
timelineAvatar: actionIconName,
timelineAvatarAriaLabel: actionIconName,
actions: <UserActionCopyLink id={comment.id} />,
children: comment.comment.trim().length > 0 && (
<ContentWrapper data-test-subj="user-action-markdown">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,29 @@ export const GET_DEFAULT_TABLE_PROPERTIES = {
const HOST_TABLE_PROPERTIES_URL_STATE_KEY = 'hostFlyoutOpen';

type Action = rt.TypeOf<typeof ActionRT>;
type SetNewHostFlyoutOpen = (newProps: Action) => void;

export const useHostFlyoutOpen = (): [HostFlyoutOpen, SetNewHostFlyoutOpen] => {
const [urlState, setUrlState] = useUrlState<HostFlyoutOpen>({
defaultState: GET_DEFAULT_TABLE_PROPERTIES,
type SetNewHostFlyoutOpen = (newProp: Action) => void;
type SetNewHostFlyoutClose = () => void;

export const useHostFlyoutOpen = (): [
HostFlyoutOpen,
SetNewHostFlyoutOpen,
SetNewHostFlyoutClose
] => {
const [urlState, setUrlState] = useUrlState<HostFlyoutUrl>({
defaultState: '',
decodeUrlState,
encodeUrlState,
urlStateKey: HOST_TABLE_PROPERTIES_URL_STATE_KEY,
});

const setHostFlyoutOpen = (newProps: Action) => setUrlState({ ...urlState, ...newProps });
const setHostFlyoutOpen = (newProps: Action) =>
typeof urlState !== 'string'
? setUrlState({ ...urlState, ...newProps })
: setUrlState({ ...GET_DEFAULT_TABLE_PROPERTIES, ...newProps });

const setFlyoutClosed = () => setUrlState('');

return [urlState, setHostFlyoutOpen];
return [urlState as HostFlyoutOpen, setHostFlyoutOpen, setFlyoutClosed];
};

const FlyoutTabIdRT = rt.union([rt.literal('metadata'), rt.literal('processes')]);
Expand Down Expand Up @@ -74,9 +84,12 @@ const HostFlyoutOpenRT = rt.type({
metadataSearch: SearchFilterRT,
});

const HostFlyoutUrlRT = rt.union([HostFlyoutOpenRT, rt.string]);

type HostFlyoutUrl = rt.TypeOf<typeof HostFlyoutUrlRT>;
type HostFlyoutOpen = rt.TypeOf<typeof HostFlyoutOpenRT>;

const encodeUrlState = HostFlyoutOpenRT.encode;
const encodeUrlState = HostFlyoutUrlRT.encode;
const decodeUrlState = (value: unknown) => {
return pipe(HostFlyoutOpenRT.decode(value), fold(constant(undefined), identity));
return pipe(HostFlyoutUrlRT.decode(value), fold(constant('undefined'), identity));
};
Original file line number Diff line number Diff line change
Expand Up @@ -125,9 +125,9 @@ export const useHostsTable = (nodes: SnapshotNode[], { time }: HostTableParams)
services: { telemetry },
} = useKibanaContextForPlugin();

const [hostFlyoutOpen, setHostFlyoutOpen] = useHostFlyoutOpen();
const [hostFlyoutOpen, setHostFlyoutOpen, setFlyoutClosed] = useHostFlyoutOpen();

const closeFlyout = () => setHostFlyoutOpen({ clickedItemId: '' });
const closeFlyout = () => setFlyoutClosed();

const reportHostEntryClick = useCallback(
({ name, cloudProvider }: HostNodeRow['title']) => {
Expand Down Expand Up @@ -166,7 +166,7 @@ export const useHostsTable = (nodes: SnapshotNode[], { time }: HostTableParams)
clickedItemId: id,
});
if (id === hostFlyoutOpen.clickedItemId) {
setHostFlyoutOpen({ clickedItemId: '' });
setFlyoutClosed();
} else {
setHostFlyoutOpen({ clickedItemId: id });
}
Expand Down Expand Up @@ -244,7 +244,7 @@ export const useHostsTable = (nodes: SnapshotNode[], { time }: HostTableParams)
align: 'right',
},
],
[hostFlyoutOpen.clickedItemId, reportHostEntryClick, setHostFlyoutOpen, time]
[hostFlyoutOpen.clickedItemId, reportHostEntryClick, setFlyoutClosed, setHostFlyoutOpen, time]
);

return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export interface GetCustomEndpointMetadataGeneratorOptions {
version: string;
/** OS type for the generated endpoint hosts */
os: 'macOS' | 'windows' | 'linux';
isolation: boolean;
}

/**
Expand All @@ -33,6 +34,7 @@ export class EndpointMetadataGenerator extends BaseDataGenerator {
static custom({
version,
os,
isolation,
}: Partial<GetCustomEndpointMetadataGeneratorOptions> = {}): typeof EndpointMetadataGenerator {
return class extends EndpointMetadataGenerator {
generate(overrides: DeepPartial<HostMetadataInterface> = {}): HostMetadataInterface {
Expand All @@ -54,6 +56,9 @@ export class EndpointMetadataGenerator extends BaseDataGenerator {
set(overrides, 'host.os', EndpointMetadataGenerator.windowsOSFields);
}
}
if (isolation !== undefined) {
set(overrides, 'Endpoint.state.isolation', isolation);
}

return super.generate(overrides);
}
Expand Down Expand Up @@ -104,10 +109,10 @@ export class EndpointMetadataGenerator extends BaseDataGenerator {
/** Generate an Endpoint host metadata document */
generate(overrides: DeepPartial<HostMetadataInterface> = {}): HostMetadataInterface {
const ts = overrides['@timestamp'] ?? new Date().getTime();
const hostName = this.randomHostname();
const hostName = overrides?.host?.hostname ?? this.randomHostname();
const agentVersion = overrides?.agent?.version ?? this.randomVersion();
const agentId = this.seededUUIDv4();
const isIsolated = this.randomBoolean(0.3);
const isIsolated = overrides?.Endpoint?.state?.isolation ?? this.randomBoolean(0.3);
const capabilities: EndpointCapabilities[] = ['isolation'];

// v8.4 introduced additional endpoint capabilities
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ export class EndpointRuleAlertGenerator extends BaseDataGenerator {
const endpointMetadataGenerator = new EndpointMetadataGenerator();
const endpointMetadata = endpointMetadataGenerator.generate({
agent: { version: kibanaPackageJson.version },
host: { hostname: overrides?.host?.hostname },
Endpoint: { state: { isolation: overrides?.Endpoint?.state?.isolation } },
});
const now = overrides['@timestamp'] ?? new Date().toISOString();
const endpointAgentId = overrides?.agent?.id ?? this.seededUUIDv4();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ export interface IndexedHostsResponse
* @param policyResponseIndex
* @param enrollFleet
* @param generator
* @param disableEndpointActionsForHost
*/
export async function indexEndpointHostDocs({
numDocs,
Expand All @@ -86,6 +87,7 @@ export async function indexEndpointHostDocs({
policyResponseIndex,
enrollFleet,
generator,
withResponseActions = true,
}: {
numDocs: number;
client: Client;
Expand All @@ -96,6 +98,7 @@ export async function indexEndpointHostDocs({
policyResponseIndex: string;
enrollFleet: boolean;
generator: EndpointDocGenerator;
withResponseActions?: boolean;
}): Promise<IndexedHostsResponse> {
const timeBetweenDocs = 6 * 3600 * 1000; // 6 hours between metadata documents
const timestamp = new Date().getTime();
Expand Down Expand Up @@ -190,13 +193,15 @@ export async function indexEndpointHostDocs({
},
};

// Create some fleet endpoint actions and .logs-endpoint actions for this Host
const actionsResponse = await indexEndpointAndFleetActionsForHost(
client,
hostMetadata,
undefined
);
mergeAndAppendArrays(response, actionsResponse);
if (withResponseActions) {
// Create some fleet endpoint actions and .logs-endpoint actions for this Host
const actionsResponse = await indexEndpointAndFleetActionsForHost(
client,
hostMetadata,
undefined
);
mergeAndAppendArrays(response, actionsResponse);
}
}

await client
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import { EndpointRuleAlertGenerator } from '../data_generators/endpoint_rule_ale
export interface IndexEndpointRuleAlertsOptions {
esClient: Client;
endpointAgentId: string;
endpointHostname?: string;
endpointIsolated?: boolean;
count?: number;
log?: ToolingLog;
}
Expand All @@ -40,12 +42,16 @@ export interface DeletedIndexedEndpointRuleAlerts {
* written them to for a given endpoint
* @param esClient
* @param endpointAgentId
* @param endpointHostname
* @param endpointIsolated
* @param count
* @param log
*/
export const indexEndpointRuleAlerts = async ({
esClient,
endpointAgentId,
endpointHostname,
endpointIsolated,
count = 1,
log = new ToolingLog(),
}: IndexEndpointRuleAlertsOptions): Promise<IndexedEndpointRuleAlerts> => {
Expand All @@ -57,7 +63,11 @@ export const indexEndpointRuleAlerts = async ({
const indexedAlerts: estypes.IndexResponse[] = [];

for (let n = 0; n < count; n++) {
const alert = alertsGenerator.generate({ agent: { id: endpointAgentId } });
const alert = alertsGenerator.generate({
agent: { id: endpointAgentId },
host: { hostname: endpointHostname },
...(endpointIsolated ? { Endpoint: { state: { isolation: endpointIsolated } } } : {}),
});
const indexedAlert = await esClient.index({
index: `${DEFAULT_ALERTS_INDEX}-default`,
refresh: 'wait_for',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,9 @@ export class EndpointDocGenerator extends BaseDataGenerator {

private createHostData(): CommonHostInfo {
const { agent, elastic, host, Endpoint } = this.metadataGenerator.generate({
Endpoint: { policy: { applied: this.randomChoice(APPLIED_POLICIES) } },
Endpoint: {
policy: { applied: this.randomChoice(APPLIED_POLICIES) },
},
});

return { agent, elastic, host, Endpoint };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ export type IndexedHostsAndAlertsResponse = IndexedHostsResponse;
* @param fleet
* @param options
* @param DocGenerator
* @param withResponseActions
*/
export async function indexHostsAndAlerts(
client: Client,
Expand All @@ -62,7 +63,8 @@ export async function indexHostsAndAlerts(
alertsPerHost: number,
fleet: boolean,
options: TreeOptions = {},
DocGenerator: typeof EndpointDocGenerator = EndpointDocGenerator
DocGenerator: typeof EndpointDocGenerator = EndpointDocGenerator,
withResponseActions = true
): Promise<IndexedHostsAndAlertsResponse> {
const random = seedrandom(seed);
const epmEndpointPackage = await getEndpointPackageInfo(kbnClient);
Expand Down Expand Up @@ -114,6 +116,7 @@ export async function indexHostsAndAlerts(
policyResponseIndex,
enrollFleet: fleet,
generator,
withResponseActions,
});

mergeAndAppendArrays(response, indexedHosts);
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/

import { renderHook } from '@testing-library/react-hooks';
import type { XYState } from '@kbn/lens-plugin/public';
import { wrapper } from '../../../mocks';

import { useLensAttributes } from '../../../use_lens_attributes';
Expand Down Expand Up @@ -56,4 +57,42 @@ describe('getRiskScoreOverTimeAreaAttributes', () => {

expect(result?.current).toMatchSnapshot();
});

it('should render a Reference Line with an Alert icon', () => {
const { result } = renderHook(
() =>
useLensAttributes({
getLensAttributes: getRiskScoreOverTimeAreaAttributes,
stackByField: 'host',
extraOptions: {
spaceId: 'mockSpaceId',
},
}),
{ wrapper }
);

expect(
(result?.current?.state.visualization as XYState).layers.find(
(layer) => layer.layerType === 'referenceLine'
)
).toEqual(
expect.objectContaining({
layerId: '1dd5663b-f062-43f8-8688-fc8166c2ca8e',
layerType: 'referenceLine',
accessors: ['1dd5663b-f062-43f8-8688-fc8166c2ca8e'],
yConfig: [
{
forAccessor: '1dd5663b-f062-43f8-8688-fc8166c2ca8e',
axisMode: 'left',
lineWidth: 2,
color: '#aa6556',
icon: 'alert',
textVisibility: true,
fill: 'none',
iconPosition: 'left',
},
],
})
);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export const getRiskScoreOverTimeAreaAttributes: GetLensAttributes = (
axisMode: 'left',
lineWidth: 2,
color: '#aa6556',
icon: 'warning',
icon: 'alert',
textVisibility: true,
fill: 'none',
iconPosition: 'left',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,11 @@

import type { CasePostRequest } from '@kbn/cases-plugin/common/api';
import type { IndexedEndpointPolicyResponse } from '../../../common/endpoint/data_loaders/index_endpoint_policy_response';
import type { HostPolicyResponse } from '../../../common/endpoint/types';
import type { IndexEndpointHostsCyTaskOptions } from './types';
import type {
HostPolicyResponse,
LogsEndpointActionResponse,
} from '../../../common/endpoint/types';
import type { IndexEndpointHostsCyTaskOptions, HostActionResponse } from './types';
import type {
DeleteIndexedFleetEndpointPoliciesResponse,
IndexedFleetEndpointPolicyResponse,
Expand Down Expand Up @@ -115,6 +118,12 @@ declare global {
arg: IndexedEndpointPolicyResponse,
options?: Partial<Loggable & Timeoutable>
): Chainable<null>;

task(
name: 'sendHostActionResponse',
arg: HostActionResponse,
options?: Partial<Loggable & Timeoutable>
): Chainable<LogsEndpointActionResponse>;
}
}
}
Loading

0 comments on commit ec45b8d

Please sign in to comment.