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] Add hook for reading/writing resolver query params #70809

Merged
Show file tree
Hide file tree
Changes from 4 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 @@ -75,6 +75,7 @@ interface AppReceivedNewExternalProperties {
* the `_id` of an ES document. This defines the origin of the Resolver graph.
*/
databaseDocumentID?: string;
resolverComponentInstanceID: string;
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@ import { ResolverAction } from '../actions';
const initialState: DataState = {
relatedEvents: new Map(),
relatedEventsReady: new Map(),
resolverComponentInstanceID: undefined,
};

export const dataReducer: Reducer<DataState, ResolverAction> = (state = initialState, action) => {
if (action.type === 'appReceivedNewExternalProperties') {
const nextState: DataState = {
...state,
databaseDocumentID: action.payload.databaseDocumentID,
resolverComponentInstanceID: action.payload.resolverComponentInstanceID,
};
return nextState;
} else if (action.type === 'appRequestedResolverData') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,12 @@ describe('data state', () => {

describe('when there is a databaseDocumentID but no pending request', () => {
const databaseDocumentID = 'databaseDocumentID';
const resolverComponentInstanceID = 'resolverComponentInstanceID';
beforeEach(() => {
actions = [
{
type: 'appReceivedNewExternalProperties',
payload: { databaseDocumentID },
payload: { databaseDocumentID, resolverComponentInstanceID },
},
];
});
Expand Down Expand Up @@ -104,11 +105,12 @@ describe('data state', () => {
});
describe('when there is a pending request for the current databaseDocumentID', () => {
const databaseDocumentID = 'databaseDocumentID';
const resolverComponentInstanceID = 'resolverComponentInstanceID';
beforeEach(() => {
actions = [
{
type: 'appReceivedNewExternalProperties',
payload: { databaseDocumentID },
payload: { databaseDocumentID, resolverComponentInstanceID },
},
{
type: 'appRequestedResolverData',
Expand Down Expand Up @@ -160,12 +162,17 @@ describe('data state', () => {
describe('when there is a pending request for a different databaseDocumentID than the current one', () => {
const firstDatabaseDocumentID = 'first databaseDocumentID';
const secondDatabaseDocumentID = 'second databaseDocumentID';
const resolverComponentInstanceID1 = 'resolverComponentInstanceID1';
const resolverComponentInstanceID2 = 'resolverComponentInstanceID2';
beforeEach(() => {
actions = [
// receive the document ID, this would cause the middleware to starts the request
{
type: 'appReceivedNewExternalProperties',
payload: { databaseDocumentID: firstDatabaseDocumentID },
payload: {
databaseDocumentID: firstDatabaseDocumentID,
resolverComponentInstanceID: resolverComponentInstanceID1,
},
},
// this happens when the middleware starts the request
{
Expand All @@ -175,19 +182,28 @@ describe('data state', () => {
// receive a different databaseDocumentID. this should cause the middleware to abort the existing request and start a new one
{
type: 'appReceivedNewExternalProperties',
payload: { databaseDocumentID: secondDatabaseDocumentID },
payload: {
databaseDocumentID: secondDatabaseDocumentID,
resolverComponentInstanceID: resolverComponentInstanceID2,
},
},
];
});
it('should be loading', () => {
expect(selectors.isLoading(state())).toBe(true);
});
it('should need to fetch the second databaseDocumentID', () => {
expect(selectors.databaseDocumentIDToFetch(state())).toBe(secondDatabaseDocumentID);
expect(selectors.databaseDocumentIDToFetch(state())).toBe(firstDatabaseDocumentID);
});
it('should need to abort the request for the databaseDocumentID', () => {
expect(selectors.databaseDocumentIDToFetch(state())).toBe(secondDatabaseDocumentID);
});
it('should use the correct location for the first resolver', () => {
expect(selectors.resolverComponentInstanceID(state())).toBe(resolverComponentInstanceID1);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❔ How does this work? It looks like we expect different things back to back from the same selector...

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❔ If it's because of the aborted request, that's really hard to understand here.

Copy link
Contributor

@michaelolo24 michaelolo24 Jul 13, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It fetched the first resolver, and then this is it resolved. Technically the second one is in-progress at this point and resolves in the checks below. It's the way the actions resolve for the state() calls

});
it('should use the correct location for the second resolver', () => {
expect(selectors.resolverComponentInstanceID(state())).toBe(resolverComponentInstanceID2);
});
it('should not have an error, more children, or more ancestors.', () => {
expect(viewAsAString(state())).toMatchInlineSnapshot(`
"is loading: true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,13 @@ export function isLoading(state: DataState): boolean {
return state.pendingRequestDatabaseDocumentID !== undefined;
}

/**
* A string for uniquely identifying the instance of resolver within the app.
*/
export function resolverComponentInstanceID(state: DataState): string {
return state.resolverComponentInstanceID;
}

/**
* If a request was made and it threw an error or returned a failure response code.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ export const databaseDocumentIDToAbort = composeSelectors(
dataSelectors.databaseDocumentIDToAbort
);

export const resolverComponentInstanceID = composeSelectors(
dataStateSelector,
dataSelectors.resolverComponentInstanceID
);

export const processAdjacencies = composeSelectors(
dataStateSelector,
dataSelectors.processAdjacencies
Expand Down
1 change: 1 addition & 0 deletions x-pack/plugins/security_solution/public/resolver/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ export interface DataState {
* The id used for the pending request, if there is one.
*/
readonly pendingRequestDatabaseDocumentID?: string;
readonly resolverComponentInstanceID: string;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❔ A doc comment


/**
* The parameters and response from the last successful request.
Expand Down
12 changes: 11 additions & 1 deletion x-pack/plugins/security_solution/public/resolver/view/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { useKibana } from '../../../../../../src/plugins/kibana_react/public';
export const Resolver = React.memo(function ({
className,
databaseDocumentID,
resolverComponentInstanceID,
}: {
/**
* Used by `styled-components`.
Expand All @@ -28,6 +29,11 @@ export const Resolver = React.memo(function ({
* Used as the origin of the Resolver graph.
*/
databaseDocumentID?: string;
/**
* A string literal describing where in the app resolver is located,
* used to prevent collisions in things like query params
*/
resolverComponentInstanceID: string;
}) {
const context = useKibana<StartServices>();
const store = useMemo(() => {
Expand All @@ -40,7 +46,11 @@ export const Resolver = React.memo(function ({
*/
return (
<Provider store={store}>
<ResolverMap className={className} databaseDocumentID={databaseDocumentID} />
<ResolverMap
className={className}
databaseDocumentID={databaseDocumentID}
resolverComponentInstanceID={resolverComponentInstanceID}
/>
</Provider>
);
});
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { SideEffectContext } from './side_effect_context';
export const ResolverMap = React.memo(function ({
className,
databaseDocumentID,
resolverComponentInstanceID,
}: {
/**
* Used by `styled-components`.
Expand All @@ -39,12 +40,17 @@ export const ResolverMap = React.memo(function ({
* Used as the origin of the Resolver graph.
*/
databaseDocumentID?: string;
/**
* A string literal describing where in the app resolver is located,
* used to prevent collisions in things like query params
*/
resolverComponentInstanceID: string;
}) {
/**
* This is responsible for dispatching actions that include any external data.
* `databaseDocumentID`
*/
useStateSyncingActions({ databaseDocumentID });
useStateSyncingActions({ databaseDocumentID, resolverComponentInstanceID });

const { timestamp } = useContext(SideEffectContext);
const { processNodePositions, connectingEdgeLineSegments } = useSelector(
Expand Down
43 changes: 4 additions & 39 deletions x-pack/plugins/security_solution/public/resolver/view/panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,8 @@
* you may not use this file except in compliance with the Elastic License.
*/

import React, { memo, useCallback, useMemo, useContext, useLayoutEffect, useState } from 'react';
import React, { memo, useMemo, useContext, useLayoutEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { useHistory, useLocation } from 'react-router-dom';
// eslint-disable-next-line import/no-nodejs-modules
import querystring from 'querystring';
import { EuiPanel } from '@elastic/eui';
import { displayNameRecord } from './process_event_dot';
import * as selectors from '../store/selectors';
Expand All @@ -21,7 +18,7 @@ import { EventCountsForProcess } from './panels/panel_content_related_counts';
import { ProcessDetails } from './panels/panel_content_process_detail';
import { ProcessListWithCounts } from './panels/panel_content_process_list';
import { RelatedEventDetail } from './panels/panel_content_related_detail';
import { CrumbInfo } from './panels/panel_content_utilities';
import { useResolverQueryParams } from './use_resolver_query_params';

/**
* The team decided to use this table to determine which breadcrumbs/view to display:
Expand All @@ -39,14 +36,11 @@ import { CrumbInfo } from './panels/panel_content_utilities';
* @returns {JSX.Element} The "right" table content to show based on the query params as described above
*/
const PanelContent = memo(function PanelContent() {
const history = useHistory();
const urlSearch = useLocation().search;
const dispatch = useResolverDispatch();

const { timestamp } = useContext(SideEffectContext);
const queryParams: CrumbInfo = useMemo(() => {
return { crumbId: '', crumbEvent: '', ...querystring.parse(urlSearch.slice(1)) };
}, [urlSearch]);

const { pushToQueryParams, queryParams } = useResolverQueryParams();

const graphableProcesses = useSelector(selectors.graphableProcesses);
const graphableProcessEntityIds = useMemo(() => {
Expand Down Expand Up @@ -104,35 +98,6 @@ const PanelContent = memo(function PanelContent() {
}
}, [dispatch, uiSelectedEvent, paramsSelectedEvent, lastUpdatedProcess, timestamp]);

/**
* This updates the breadcrumb nav and the panel view. It's supplied to each
* panel content view to allow them to dispatch transitions to each other.
*/
const pushToQueryParams = useCallback(
(newCrumbs: CrumbInfo) => {
// Construct a new set of params from the current set (minus empty params)
// by assigning the new set of params provided in `newCrumbs`
const crumbsToPass = {
...querystring.parse(urlSearch.slice(1)),
...newCrumbs,
};

// If either was passed in as empty, remove it from the record
if (crumbsToPass.crumbId === '') {
delete crumbsToPass.crumbId;
}
if (crumbsToPass.crumbEvent === '') {
delete crumbsToPass.crumbEvent;
}

const relativeURL = { search: querystring.stringify(crumbsToPass) };
// We probably don't want to nuke the user's history with a huge
// trail of these, thus `.replace` instead of `.push`
return history.replace(relativeURL);
},
[history, urlSearch]
);

const relatedEventStats = useSelector(selectors.relatedEventsStats);
const { crumbId, crumbEvent } = queryParams;
const relatedStatsForIdFromParams: ResolverNodeStats | undefined =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ const BetaHeader = styled(`header`)`
* The two query parameters we read/write on to control which view the table presents:
*/
export interface CrumbInfo {
readonly crumbId: string;
readonly crumbEvent: string;
crumbId: string;
crumbEvent: string;
}

const ThemedBreadcrumbs = styled(EuiBreadcrumbs)<{ background: string; text: string }>`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,6 @@ import React, { useCallback, useMemo } from 'react';
import styled from 'styled-components';
import { i18n } from '@kbn/i18n';
import { htmlIdGenerator, EuiButton, EuiI18nNumber, EuiFlexGroup, EuiFlexItem } from '@elastic/eui';
import { useHistory } from 'react-router-dom';
// eslint-disable-next-line import/no-nodejs-modules
import querystring from 'querystring';
import { useSelector } from 'react-redux';
import { NodeSubMenu, subMenuAssets } from './submenu';
import { applyMatrix3 } from '../models/vector2';
Expand All @@ -22,7 +19,7 @@ import { ResolverEvent, ResolverNodeStats } from '../../../common/endpoint/types
import { useResolverDispatch } from './use_resolver_dispatch';
import * as eventModel from '../../../common/endpoint/models/event';
import * as selectors from '../store/selectors';
import { CrumbInfo } from './panels/panel_content_utilities';
import { useResolverQueryParams } from './use_resolver_query_params';

/**
* A record of all known event types (in schema format) to translations
Expand Down Expand Up @@ -403,35 +400,7 @@ const UnstyledProcessEventDot = React.memo(
});
}, [dispatch, selfId]);

const history = useHistory();
const urlSearch = history.location.search;

/**
* This updates the breadcrumb nav, the table view
*/
const pushToQueryParams = useCallback(
(newCrumbs: CrumbInfo) => {
// Construct a new set of params from the current set (minus empty params)
// by assigning the new set of params provided in `newCrumbs`
const crumbsToPass = {
...querystring.parse(urlSearch.slice(1)),
...newCrumbs,
};

// If either was passed in as empty, remove it from the record
if (crumbsToPass.crumbId === '') {
delete crumbsToPass.crumbId;
}
if (crumbsToPass.crumbEvent === '') {
delete crumbsToPass.crumbEvent;
}

const relativeURL = { search: querystring.stringify(crumbsToPass) };

return history.replace(relativeURL);
},
[history, urlSearch]
);
const { pushToQueryParams } = useResolverQueryParams();

const handleClick = useCallback(() => {
if (animationTarget.current !== null) {
Expand Down
Loading