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][Detections][Tech Debt] - Move to using common io-ts types #75009

Merged
merged 12 commits into from
Sep 4, 2020

Conversation

yctercero
Copy link
Contributor

@yctercero yctercero commented Aug 13, 2020

Summary

Part of the DE tech debt includes moving to use the common io-ts types in the UI. Currently, we are using some of them in some places and other times we're using the front end defined typescript types. This means that changes often have to be done on both ends, validation isn't being done at the UI boundary on request or response. Using the common types could help us avoid bugs moving forward. Obviously, there's a lot of code to touch so trying to just do it piece by piece. This PR addresses the following:

  • Replaced uses of NewRule with common type CreateRuleSchema and UpdateRuleSchema. These were being combined a bit
  • Split usePersistRule which was used for both POST and PUT into two hooks - useCreateRule and useUpdateRule.
    • The logic for combining these two relied on checking for the existence of an id - if present it would PUT, otherwise it would POST.
    • However, id is not a required property for either of these, so it's not reliable
  • Updated the rule edit flow to use useUpdateRule
  • Updated the rule creation flow to use useCreateRule
  • Added request and response validation for rule PUT, POST, and PATCH Edit: decided not to do this to move this PR forward, may need more discussion as to the pros/cons of added io-ts validation in the front

Testing

  • test creating a rule with just required fields
  • test creating a rule with all fields filled
  • test updating a rule
  • test adding an exception to an item for the first time (it uses patch to associate the exception list with the rule)

Checklist

* @param signal to cancel request
*
* @throws An error if response is not OK
*/
export const addRule = async ({ rule, signal }: AddRulesProps): Promise<NewRule> =>
KibanaServices.get().http.fetch<NewRule>(DETECTION_ENGINE_RULES_URL, {
method: rule.id != null ? 'PUT' : 'POST',
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Neither CreateRuleSchema or UpdateRuleSchema require the presence of an id so this check was no longer valid.

@@ -325,7 +325,7 @@ export const sortFieldOrUndefined = t.union([sort_field, t.undefined]);
export type SortFieldOrUndefined = t.TypeOf<typeof sortFieldOrUndefined>;

export const sort_order = t.keyof({ asc: null, desc: null });
export type sortOrder = t.TypeOf<typeof sort_order>;
export type SortOrder = t.TypeOf<typeof sort_order>;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think this was just a typo? Seems like all other typescript ones are uppercase.

@yctercero yctercero self-assigned this Aug 14, 2020
@yctercero yctercero added release_note:skip Skip the PR/issue when compiling release notes Team:SIEM v7.10.0 v8.0.0 Feature:Detection Rules Security Solution rules and Detection Engine labels Aug 14, 2020
@yctercero yctercero marked this pull request as ready for review August 14, 2020 00:19
@elasticmachine
Copy link
Contributor

Pinging @elastic/siem (Team:SIEM)

@yctercero yctercero requested review from a team as code owners August 14, 2020 14:35
/**
* Patch provided Rule
* Patch provided rule
Copy link
Contributor

Choose a reason for hiding this comment

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

If we're going to discourage usage of patch in a certain way, we should probably limit the schema so that we can only patch the fields that we're expecting to be patched.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

That's a good call. I think it's particular to the way we built the UI (need to double check that) so maybe creating a limited schema in the front end makes sense.

Copy link
Contributor

Choose a reason for hiding this comment

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

If I recall correctly, usage of patch was highly discouraged in general... so maybe worth discussing limiting on the backend too? Shouldn't block this PR, but if we could prevent someone from trying to use the API in ways that could be detrimental, I think that could be worthwhile.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Sorry, just circling back on this PR now. I think that's definitely a good point that we should discuss. I added it to our team discussion for next week.

signal,
});

const createRuleWithValidation = async ({ rule, signal }: CreateRulesProps): Promise<RulesSchema> =>
Copy link
Contributor

@madirey madirey Aug 14, 2020

Choose a reason for hiding this comment

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

Is the idea that we're validating on the FE and on the BE? Does that buy us anything to be able to validate from the UI?

Copy link
Contributor

Choose a reason for hiding this comment

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

@peluja1012 Any opinions on this? IMO it's simpler, more readable, and more maintainable if we only validate in one place (the backend APIs).

Copy link
Contributor

Choose a reason for hiding this comment

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

We still get the benefit of using common types on both API and UI code... that buys us a lot in terms of static type consistency. Once we start doing dynamic validation though, I feel like we're starting to hit the other side of the cost/benefit curve.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I decided to remove these here for now. I think you bring up a lot of valid points that can be addressed separately if we decide to go down that route.

@@ -4,36 +4,7 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { NewRule, FetchRulesResponse, Rule } from './types';

export const ruleMock: NewRule = {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Moving towards using the already created mocks next to the schema files.

fetchMock.mockResolvedValue(getRulesSchemaMock());
});

test('POSTs rule', async () => {
Copy link
Contributor

Choose a reason for hiding this comment

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

The test name here says POST, but the test is checking for PUT

Copy link
Contributor

@madirey madirey left a comment

Choose a reason for hiding this comment

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

I pulled this down and ran through several test cases... created rules, updated rules, sorted detection alerts in various configurations... everything looked good!

@yctercero
Copy link
Contributor Author

@elasticmachine merge upstream

@kibanamachine
Copy link
Contributor

💚 Build Succeeded

Build metrics

@kbn/optimizer bundle module count

id value diff baseline
securitySolution 1948 +1 1947

async chunks size

id value diff baseline
securitySolution 9.9MB +7.4KB 9.9MB

page load bundle size

id value diff baseline
securitySolution 812.9KB -89.0B 813.0KB

distributable file count

id value diff baseline
total 45464 +2 45462

History

To update your PR or re-run it, just comment with:
@elasticmachine merge upstream

@yctercero yctercero merged commit d2156b7 into elastic:master Sep 4, 2020
yctercero added a commit to yctercero/kibana that referenced this pull request Sep 4, 2020
…ts types (elastic#75009)

## Summary

Part of the DE tech debt includes moving to use the common io-ts types in the UI. Currently, we are using some of them in some places and other times we're using the front end defined typescript types. This means that changes often have to be done on both ends, validation isn't being done at the UI boundary on request or response. Using the common types could help us avoid bugs moving forward. Obviously, there's a lot of code to touch so trying to just do it piece by piece. This PR addresses the following:

- Replaced uses of `NewRule` with common type `CreateRuleSchema` and `UpdateRuleSchema`. These were being combined a bit
- Split `usePersistRule` which was used for both `POST` and `PUT` into two hooks - `useCreateRule` and `useUpdateRule`. 
  - The logic for combining these two relied on checking for the existence of an `id` - if present it would `PUT`, otherwise it would `POST`.
  - However, `id` is not a required property for either of these, so it's not reliable
- Updated the rule edit flow to use `useUpdateRule`
- Updated the rule creation flow to use `useCreateRule`
gmmorris added a commit to gmmorris/kibana that referenced this pull request Sep 4, 2020
* master: (47 commits)
  Do not require id & description when creating a logstash pipeline (elastic#76616)
  Remove commented src/core/tsconfig file (elastic#76792)
  Replaced whitelistedHosts with allowedHosts in actions ascii docs (elastic#76731)
  [Dashboard First] Genericize Attribute Service (elastic#76057)
  [ci-metrics] unify distributable file count metrics (elastic#76448)
  [Security Solution][Detections] Handle conflicts on alert status update (elastic#75492)
  [eslint] convert to @typescript-eslint/no-unused-expressions (elastic#76471)
  [DOCS] Add default time range filter to advanced settings (elastic#76414)
  [Security Solution] Refactor NetworkTopNFlow to use Search Strategy (elastic#76249)
  [Dashboard] Update Index Patterns when Child Index Patterns Change (elastic#76356)
  [ML] Add option to Advanced Settings to set default time range filter for AD jobs (elastic#76347)
  Add CSM app to CODEOWNERS (elastic#76793)
  [Security Solution][Exceptions] - Updates exception item find sort field (elastic#76685)
  [Security Solution][Detections][Tech Debt] - Move to using common io-ts types (elastic#75009)
  [Lens] Drag dimension to replace (elastic#75895)
  URI encode the index names we fetch in the fetchIndices lib function. (elastic#76584)
  [Security Solution] Resolver retrieve entity id of documents without field mapped (elastic#76562)
  [Ingest Manager] validate agent route using AJV instead kbn-config-schema (elastic#76546)
  Updated non-dev usages of node-forge (elastic#76699)
  [Ingest Pipelines] Processor forms for processors K-S (elastic#75638)
  ...
yctercero added a commit that referenced this pull request Sep 4, 2020
…ts types (#75009) (#76780)

## Summary

Part of the DE tech debt includes moving to use the common io-ts types in the UI. Currently, we are using some of them in some places and other times we're using the front end defined typescript types. This means that changes often have to be done on both ends, validation isn't being done at the UI boundary on request or response. Using the common types could help us avoid bugs moving forward. Obviously, there's a lot of code to touch so trying to just do it piece by piece. This PR addresses the following:

- Replaced uses of `NewRule` with common type `CreateRuleSchema` and `UpdateRuleSchema`. These were being combined a bit
- Split `usePersistRule` which was used for both `POST` and `PUT` into two hooks - `useCreateRule` and `useUpdateRule`. 
  - The logic for combining these two relied on checking for the existence of an `id` - if present it would `PUT`, otherwise it would `POST`.
  - However, `id` is not a required property for either of these, so it's not reliable
- Updated the rule edit flow to use `useUpdateRule`
- Updated the rule creation flow to use `useCreateRule`
@yctercero yctercero deleted the ui-types branch October 14, 2020 11:59
@MindyRS MindyRS added the Team: SecuritySolution Security Solutions Team working on SIEM, Endpoint, Timeline, Resolver, etc. label Sep 23, 2021
@elasticmachine
Copy link
Contributor

Pinging @elastic/security-solution (Team: SecuritySolution)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Feature:Detection Rules Security Solution rules and Detection Engine release_note:skip Skip the PR/issue when compiling release notes Team: SecuritySolution Security Solutions Team working on SIEM, Endpoint, Timeline, Resolver, etc. Team:SIEM v7.10.0 v8.0.0
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants