Skip to content

Commit 5b7bc06

Browse files
kibanamachineKDKHD
andauthored
[8.18] [Security Solution] [AI Assistant] Replace polynomial regular expression with constant time string manipulation (#209314) (#210145)
# Backport This will backport the following commits from `main` to `8.18`: - [[Security Solution] [AI Assistant] Replace polynomial regular expression with constant time string manipulation (#209314)](#209314) <!--- Backport version: 9.4.3 --> ### Questions ? Please refer to the [Backport tool documentation](https://github.com/sqren/backport) <!--BACKPORT [{"author":{"name":"Kenneth Kreindler","email":"[email protected]"},"sourceCommit":{"committedDate":"2025-02-07T09:22:37Z","message":"[Security Solution] [AI Assistant] Replace polynomial regular expression with constant time string manipulation (#209314)\n\n## Summary\r\n\r\nFixes https://github.com/elastic/kibana-team/issues/1442\r\n\r\nThis PR replaces a poorly performing regular expression with a constant\r\ntime string manipulation approach.\r\n\r\nContext:\r\nThe regex is used to remove all references from a string when a user\r\ncopies a message from the assistant and when conversation history is\r\npassed to the LLM e.g.\r\n```\r\n\"The sky is blue{reference(1234)} and the grass is green{reference(4321)}\" -> \"The sky is blue and the grass is green\"\r\n```\r\n\r\nChanges:\r\n- Replace the regular expression inside of `removeContentReferences()`\r\n- Add tests to verify new logic is correct.\r\n- Fix a bug in the contentReference markdown parser that was found by\r\n@andrew-goldstein\r\n[here](https://github.com/elastic/kibana/pull/209314/files#r1943198510)\r\n- For alerts page citations, add a filter for open and acknowledge\r\nalerts within the last 24 hours\r\n[here](https://github.com/elastic/kibana/pull/209314/files#diff-f17fbe7edfe72943fecbe5ddd8dca6c024a48fe4f90bf4f66650cef16091b769R36)\r\n\r\n\r\n### How to test new regex:\r\nOne of the changes in this PR improves the performance of a regex. In\r\nreal life, no one has ever reached any performance issues with this\r\nregex's and I don't think it is realistically possible to reach that\r\nlimit without other things breaking (i.e. the message sent to/returned\r\nby the assistant would need to be so large that it would exceed the\r\ncontext window). Therefore, all we can test is that the functionality\r\nstill works as expected after this change.\r\n- Enable the feature flag\r\n```yaml\r\n# kibana.dev.yml\r\nxpack.securitySolution.enableExperimental: ['contentReferencesEnabled']\r\n```\r\n- Open the security assistant\r\n- Ask the assistant a question about your alerts or a document in your\r\nKB. The assistant response should contain citations.\r\n- Copy the response to the clipboard using the copy button.\r\n<img width=\"785\" alt=\"image\"\r\nsrc=\"https://github.com/user-attachments/assets/edded3a3-8cb9-40a8-918e-a9718e7afc22\"\r\n/>\r\n- Your clipboard should contain the response without any citations\r\n\r\n### How to test the alerts page filter\r\n- Ask a question about your open alerts and make sure a citation is\r\nreturned.\r\n- Click on the citation\r\n- Verify a new tab is opened and the alerts page is visible with a\r\nfilter for open and acknowledge alerts and there is a now-24h time\r\nwindow filter.\r\n\r\n### Checklist\r\n\r\nCheck the PR satisfies following conditions. \r\n\r\nReviewers should verify this PR satisfies this list as well.\r\n\r\n- [X] Any text added follows [EUI's writing\r\nguidelines](https://elastic.github.io/eui/#/guidelines/writing), uses\r\nsentence case text and includes [i18n\r\nsupport](https://github.com/elastic/kibana/blob/main/src/platform/packages/shared/kbn-i18n/README.md)\r\n- [X]\r\n[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)\r\nwas added for features that require explanation or tutorials\r\n- [X] [Unit or functional\r\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\r\nwere updated or added to match the most common scenarios\r\n- [X] If a plugin configuration key changed, check if it needs to be\r\nallowlisted in the cloud and added to the [docker\r\nlist](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)\r\n- [X] This was checked for breaking HTTP API changes, and any breaking\r\nchanges have been approved by the breaking-change committee. The\r\n`release_note:breaking` label should be applied in these situations.\r\n- [X] [Flaky Test\r\nRunner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was\r\nused on any tests changed\r\n- [X] The PR description includes the appropriate Release Notes section,\r\nand the correct `release_note:*` label is applied per the\r\n[guidelines](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)\r\n\r\n### Identify risks\r\n\r\nDoes this PR introduce any risks? For example, consider risks like hard\r\nto test bugs, performance regression, potential of data loss.\r\n\r\nDescribe the risk, its severity, and mitigation for each identified\r\nrisk. Invite stakeholders and evaluate how to proceed before merging.\r\n\r\n- [ ] [See some risk\r\nexamples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx)\r\n- [ ] ...\r\n\r\n---------\r\n\r\nCo-authored-by: kibanamachine <[email protected]>\r\nCo-authored-by: Elastic Machine <[email protected]>","sha":"2bf8a24c5cb56b2ccb16e6c38f18cc9c39d65fcd","branchLabelMapping":{"^v9.1.0$":"main","^v8.19.0$":"8.x","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["release_note:skip","v9.0.0","Team:Security Generative AI","backport:version","v8.18.0","v9.1.0"],"title":"[Security Solution] [AI Assistant] Replace polynomial regular expression with constant time string manipulation","number":209314,"url":"https://github.com/elastic/kibana/pull/209314","mergeCommit":{"message":"[Security Solution] [AI Assistant] Replace polynomial regular expression with constant time string manipulation (#209314)\n\n## Summary\r\n\r\nFixes https://github.com/elastic/kibana-team/issues/1442\r\n\r\nThis PR replaces a poorly performing regular expression with a constant\r\ntime string manipulation approach.\r\n\r\nContext:\r\nThe regex is used to remove all references from a string when a user\r\ncopies a message from the assistant and when conversation history is\r\npassed to the LLM e.g.\r\n```\r\n\"The sky is blue{reference(1234)} and the grass is green{reference(4321)}\" -> \"The sky is blue and the grass is green\"\r\n```\r\n\r\nChanges:\r\n- Replace the regular expression inside of `removeContentReferences()`\r\n- Add tests to verify new logic is correct.\r\n- Fix a bug in the contentReference markdown parser that was found by\r\n@andrew-goldstein\r\n[here](https://github.com/elastic/kibana/pull/209314/files#r1943198510)\r\n- For alerts page citations, add a filter for open and acknowledge\r\nalerts within the last 24 hours\r\n[here](https://github.com/elastic/kibana/pull/209314/files#diff-f17fbe7edfe72943fecbe5ddd8dca6c024a48fe4f90bf4f66650cef16091b769R36)\r\n\r\n\r\n### How to test new regex:\r\nOne of the changes in this PR improves the performance of a regex. In\r\nreal life, no one has ever reached any performance issues with this\r\nregex's and I don't think it is realistically possible to reach that\r\nlimit without other things breaking (i.e. the message sent to/returned\r\nby the assistant would need to be so large that it would exceed the\r\ncontext window). Therefore, all we can test is that the functionality\r\nstill works as expected after this change.\r\n- Enable the feature flag\r\n```yaml\r\n# kibana.dev.yml\r\nxpack.securitySolution.enableExperimental: ['contentReferencesEnabled']\r\n```\r\n- Open the security assistant\r\n- Ask the assistant a question about your alerts or a document in your\r\nKB. The assistant response should contain citations.\r\n- Copy the response to the clipboard using the copy button.\r\n<img width=\"785\" alt=\"image\"\r\nsrc=\"https://github.com/user-attachments/assets/edded3a3-8cb9-40a8-918e-a9718e7afc22\"\r\n/>\r\n- Your clipboard should contain the response without any citations\r\n\r\n### How to test the alerts page filter\r\n- Ask a question about your open alerts and make sure a citation is\r\nreturned.\r\n- Click on the citation\r\n- Verify a new tab is opened and the alerts page is visible with a\r\nfilter for open and acknowledge alerts and there is a now-24h time\r\nwindow filter.\r\n\r\n### Checklist\r\n\r\nCheck the PR satisfies following conditions. \r\n\r\nReviewers should verify this PR satisfies this list as well.\r\n\r\n- [X] Any text added follows [EUI's writing\r\nguidelines](https://elastic.github.io/eui/#/guidelines/writing), uses\r\nsentence case text and includes [i18n\r\nsupport](https://github.com/elastic/kibana/blob/main/src/platform/packages/shared/kbn-i18n/README.md)\r\n- [X]\r\n[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)\r\nwas added for features that require explanation or tutorials\r\n- [X] [Unit or functional\r\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\r\nwere updated or added to match the most common scenarios\r\n- [X] If a plugin configuration key changed, check if it needs to be\r\nallowlisted in the cloud and added to the [docker\r\nlist](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)\r\n- [X] This was checked for breaking HTTP API changes, and any breaking\r\nchanges have been approved by the breaking-change committee. The\r\n`release_note:breaking` label should be applied in these situations.\r\n- [X] [Flaky Test\r\nRunner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was\r\nused on any tests changed\r\n- [X] The PR description includes the appropriate Release Notes section,\r\nand the correct `release_note:*` label is applied per the\r\n[guidelines](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)\r\n\r\n### Identify risks\r\n\r\nDoes this PR introduce any risks? For example, consider risks like hard\r\nto test bugs, performance regression, potential of data loss.\r\n\r\nDescribe the risk, its severity, and mitigation for each identified\r\nrisk. Invite stakeholders and evaluate how to proceed before merging.\r\n\r\n- [ ] [See some risk\r\nexamples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx)\r\n- [ ] ...\r\n\r\n---------\r\n\r\nCo-authored-by: kibanamachine <[email protected]>\r\nCo-authored-by: Elastic Machine <[email protected]>","sha":"2bf8a24c5cb56b2ccb16e6c38f18cc9c39d65fcd"}},"sourceBranch":"main","suggestedTargetBranches":["9.0","8.18"],"targetPullRequestStates":[{"branch":"9.0","label":"v9.0.0","branchLabelMappingKey":"^v(\\d+).(\\d+).\\d+$","isSourceBranch":false,"state":"NOT_CREATED"},{"branch":"8.18","label":"v8.18.0","branchLabelMappingKey":"^v(\\d+).(\\d+).\\d+$","isSourceBranch":false,"state":"NOT_CREATED"},{"branch":"main","label":"v9.1.0","branchLabelMappingKey":"^v9.1.0$","isSourceBranch":true,"state":"MERGED","url":"https://github.com/elastic/kibana/pull/209314","number":209314,"mergeCommit":{"message":"[Security Solution] [AI Assistant] Replace polynomial regular expression with constant time string manipulation (#209314)\n\n## Summary\r\n\r\nFixes https://github.com/elastic/kibana-team/issues/1442\r\n\r\nThis PR replaces a poorly performing regular expression with a constant\r\ntime string manipulation approach.\r\n\r\nContext:\r\nThe regex is used to remove all references from a string when a user\r\ncopies a message from the assistant and when conversation history is\r\npassed to the LLM e.g.\r\n```\r\n\"The sky is blue{reference(1234)} and the grass is green{reference(4321)}\" -> \"The sky is blue and the grass is green\"\r\n```\r\n\r\nChanges:\r\n- Replace the regular expression inside of `removeContentReferences()`\r\n- Add tests to verify new logic is correct.\r\n- Fix a bug in the contentReference markdown parser that was found by\r\n@andrew-goldstein\r\n[here](https://github.com/elastic/kibana/pull/209314/files#r1943198510)\r\n- For alerts page citations, add a filter for open and acknowledge\r\nalerts within the last 24 hours\r\n[here](https://github.com/elastic/kibana/pull/209314/files#diff-f17fbe7edfe72943fecbe5ddd8dca6c024a48fe4f90bf4f66650cef16091b769R36)\r\n\r\n\r\n### How to test new regex:\r\nOne of the changes in this PR improves the performance of a regex. In\r\nreal life, no one has ever reached any performance issues with this\r\nregex's and I don't think it is realistically possible to reach that\r\nlimit without other things breaking (i.e. the message sent to/returned\r\nby the assistant would need to be so large that it would exceed the\r\ncontext window). Therefore, all we can test is that the functionality\r\nstill works as expected after this change.\r\n- Enable the feature flag\r\n```yaml\r\n# kibana.dev.yml\r\nxpack.securitySolution.enableExperimental: ['contentReferencesEnabled']\r\n```\r\n- Open the security assistant\r\n- Ask the assistant a question about your alerts or a document in your\r\nKB. The assistant response should contain citations.\r\n- Copy the response to the clipboard using the copy button.\r\n<img width=\"785\" alt=\"image\"\r\nsrc=\"https://github.com/user-attachments/assets/edded3a3-8cb9-40a8-918e-a9718e7afc22\"\r\n/>\r\n- Your clipboard should contain the response without any citations\r\n\r\n### How to test the alerts page filter\r\n- Ask a question about your open alerts and make sure a citation is\r\nreturned.\r\n- Click on the citation\r\n- Verify a new tab is opened and the alerts page is visible with a\r\nfilter for open and acknowledge alerts and there is a now-24h time\r\nwindow filter.\r\n\r\n### Checklist\r\n\r\nCheck the PR satisfies following conditions. \r\n\r\nReviewers should verify this PR satisfies this list as well.\r\n\r\n- [X] Any text added follows [EUI's writing\r\nguidelines](https://elastic.github.io/eui/#/guidelines/writing), uses\r\nsentence case text and includes [i18n\r\nsupport](https://github.com/elastic/kibana/blob/main/src/platform/packages/shared/kbn-i18n/README.md)\r\n- [X]\r\n[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)\r\nwas added for features that require explanation or tutorials\r\n- [X] [Unit or functional\r\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\r\nwere updated or added to match the most common scenarios\r\n- [X] If a plugin configuration key changed, check if it needs to be\r\nallowlisted in the cloud and added to the [docker\r\nlist](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)\r\n- [X] This was checked for breaking HTTP API changes, and any breaking\r\nchanges have been approved by the breaking-change committee. The\r\n`release_note:breaking` label should be applied in these situations.\r\n- [X] [Flaky Test\r\nRunner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was\r\nused on any tests changed\r\n- [X] The PR description includes the appropriate Release Notes section,\r\nand the correct `release_note:*` label is applied per the\r\n[guidelines](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)\r\n\r\n### Identify risks\r\n\r\nDoes this PR introduce any risks? For example, consider risks like hard\r\nto test bugs, performance regression, potential of data loss.\r\n\r\nDescribe the risk, its severity, and mitigation for each identified\r\nrisk. Invite stakeholders and evaluate how to proceed before merging.\r\n\r\n- [ ] [See some risk\r\nexamples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx)\r\n- [ ] ...\r\n\r\n---------\r\n\r\nCo-authored-by: kibanamachine <[email protected]>\r\nCo-authored-by: Elastic Machine <[email protected]>","sha":"2bf8a24c5cb56b2ccb16e6c38f18cc9c39d65fcd"}}]}] BACKPORT--> Co-authored-by: Kenneth Kreindler <[email protected]>
1 parent e08daa9 commit 5b7bc06

File tree

9 files changed

+212
-29
lines changed

9 files changed

+212
-29
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the Elastic License
4+
* 2.0; you may not use this file except in compliance with the Elastic License
5+
* 2.0.
6+
*/
7+
8+
import { removeContentReferences } from './utils';
9+
10+
describe('utils', () => {
11+
it.each([
12+
['this has no content references', 'this has no content references'],
13+
[
14+
'The sky is blue{reference(1234)} and the grass is green{reference(4321)}',
15+
'The sky is blue and the grass is green',
16+
],
17+
['', ''],
18+
['{reference(1234)}', ''],
19+
[' {reference(1234)} ', ' '],
20+
['{reference(1234', '{reference(1234'],
21+
['{reference(1234)', '{reference(1234)'],
22+
['{reference(1234)}{reference(1234)}{reference(1234)}', ''],
23+
['{reference(1234)}reference(1234)}{reference(1234)}', 'reference(1234)}'],
24+
])('removesContentReferences from "%s"', (input: string, expected: string) => {
25+
const result = removeContentReferences(input);
26+
27+
expect(result).toEqual(expected);
28+
});
29+
30+
// https://github.com/elastic/kibana/security/code-scanning/539
31+
it('removesContentReferences does not run in polynomial time', () => {
32+
const input = `${'{reference('.repeat(100000)}x${')'.repeat(100000)}`;
33+
const startTime = performance.now(); // Start timing
34+
35+
removeContentReferences(input);
36+
37+
const endTime = performance.now(); // End timing
38+
const executionTime = endTime - startTime; // Time in milliseconds
39+
40+
expect(executionTime).toBeLessThan(1000); // Assert under 1 second
41+
});
42+
});

x-pack/platform/packages/shared/kbn-elastic-assistant-common/impl/content_references/references/utils.ts

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,5 +46,28 @@ export const contentReferenceString = (contentReference: ContentReference) => {
4646
* @returns content with content references replaced with ''
4747
*/
4848
export const removeContentReferences = (content: string) => {
49-
return content.replaceAll(/\{reference\(.*?\)\}/g, '');
49+
let result = '';
50+
let i = 0;
51+
52+
while (i < content.length) {
53+
const start = content.indexOf('{reference(', i);
54+
if (start === -1) {
55+
// No more "{reference(" → append the rest of the string
56+
result += content.slice(i);
57+
break;
58+
}
59+
60+
const end = content.indexOf(')}', start);
61+
if (end === -1) {
62+
// If no closing ")}" is found, treat the rest as normal text
63+
result += content.slice(i);
64+
break;
65+
}
66+
67+
// Append everything before "{reference(" and skip the matched part
68+
result += content.slice(i, start);
69+
i = end + 2; // Move index past ")}"
70+
}
71+
72+
return result;
5073
};
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the Elastic License
4+
* 2.0; you may not use this file except in compliance with the Elastic License
5+
* 2.0.
6+
*/
7+
8+
import {
9+
BEDROCK_SYSTEM_PROMPT,
10+
DEFAULT_SYSTEM_PROMPT,
11+
GEMINI_SYSTEM_PROMPT,
12+
STRUCTURED_SYSTEM_PROMPT,
13+
} from './prompts';
14+
15+
describe('prompts', () => {
16+
it.each([
17+
[DEFAULT_SYSTEM_PROMPT, '{include_citations_prompt_placeholder}', 1],
18+
[GEMINI_SYSTEM_PROMPT, '{include_citations_prompt_placeholder}', 1],
19+
[BEDROCK_SYSTEM_PROMPT, '{include_citations_prompt_placeholder}', 1],
20+
[STRUCTURED_SYSTEM_PROMPT, '{include_citations_prompt_placeholder}', 1],
21+
[DEFAULT_SYSTEM_PROMPT, 'You are a security analyst', 1],
22+
[GEMINI_SYSTEM_PROMPT, 'You are an assistant', 1],
23+
[BEDROCK_SYSTEM_PROMPT, 'You are a security analyst', 1],
24+
])(
25+
'"%s" contains "%s" %s times',
26+
(prompt: string, containedString: string, expectedCount: number) => {
27+
const regex = new RegExp(containedString, 'g');
28+
expect((prompt.match(regex) || []).length).toBe(expectedCount);
29+
}
30+
);
31+
});

x-pack/solutions/security/plugins/elastic_assistant/server/lib/prompt/prompts.ts

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,15 @@
77

88
export const KNOWLEDGE_HISTORY =
99
'If available, use the Knowledge History provided to try and answer the question. If not provided, you can try and query for additional knowledge via the KnowledgeBaseRetrievalTool.';
10-
export const INCLUDE_CITATIONS = `In your response, always include citations using the format: \`{reference(...)}\` when information returned by a tool is used. Only use the reference string provided by the tools and do not create reference strings using other information. The reference should be placed after the punctuation marks.
11-
Example citations:
12-
\`\`\`
13-
Your favourite food is pizza. {reference(HMCxq)}
14-
The document was published in 2025. {reference(prSit)}
15-
\`\`\``;
10+
export const INCLUDE_CITATIONS = `\n\nAnnotate your answer with relevant citations. For example: "The sky is blue. {reference(prSit)}"\n\n`;
1611
export const DEFAULT_SYSTEM_PROMPT = `You are a security analyst and expert in resolving security incidents. Your role is to assist by answering questions about Elastic Security. Do not answer questions unrelated to Elastic Security. ${KNOWLEDGE_HISTORY} {include_citations_prompt_placeholder}`;
1712
// system prompt from @afirstenberg
1813
const BASE_GEMINI_PROMPT =
1914
'You are an assistant that is an expert at using tools and Elastic Security, doing your best to use these tools to answer questions or follow instructions. It is very important to use tools to answer the question or follow the instructions rather than coming up with your own answer. Tool calls are good. Sometimes you may need to make several tool calls to accomplish the task or get an answer to the question that was asked. Use as many tool calls as necessary.';
2015
const KB_CATCH =
2116
'If the knowledge base tool gives empty results, do your best to answer the question from the perspective of an expert security analyst.';
22-
export const GEMINI_SYSTEM_PROMPT = `${BASE_GEMINI_PROMPT} ${KB_CATCH} {include_citations_prompt_placeholder}`;
23-
export const BEDROCK_SYSTEM_PROMPT = `Use tools as often as possible, as they have access to the latest data and syntax. Never return <thinking> tags in the response, but make sure to include <result> tags content in the response. Do not reflect on the quality of the returned search results in your response. ALWAYS return the exact response from NaturalLanguageESQLTool verbatim in the final response, without adding further description.`;
17+
export const GEMINI_SYSTEM_PROMPT = `${BASE_GEMINI_PROMPT} {include_citations_prompt_placeholder} ${KB_CATCH}`;
18+
export const BEDROCK_SYSTEM_PROMPT = `${DEFAULT_SYSTEM_PROMPT} Use tools as often as possible, as they have access to the latest data and syntax. Never return <thinking> tags in the response, but make sure to include <result> tags content in the response. Do not reflect on the quality of the returned search results in your response. ALWAYS return the exact response from NaturalLanguageESQLTool verbatim in the final response, without adding further description.`;
2419
export const GEMINI_USER_PROMPT = `Now, always using the tools at your disposal, step by step, come up with a response to this request:\n\n`;
2520

2621
export const STRUCTURED_SYSTEM_PROMPT = `Respond to the human as helpfully and accurately as possible. ${KNOWLEDGE_HISTORY} {include_citations_prompt_placeholder} You have access to the following tools:

x-pack/solutions/security/plugins/security_solution/public/assistant/get_comments/content_reference/components/content_reference_component_factory.test.tsx

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ import type { ContentReferenceNode } from '../content_reference_parser';
1414
const testContentReferenceNode = { contentReferenceId: '1' } as ContentReferenceNode;
1515

1616
jest.mock('../../../../common/lib/kibana', () => ({
17+
useNavigation: jest.fn().mockReturnValue({
18+
navigateTo: jest.fn(),
19+
}),
1720
useKibana: jest.fn().mockReturnValue({
1821
services: {
1922
discover: {
@@ -154,4 +157,26 @@ describe('contentReferenceComponentFactory', () => {
154157
expect(container).toBeEmptyDOMElement();
155158
expect(screen.queryByText('[1]')).not.toBeInTheDocument();
156159
});
160+
161+
it('renders nothing if contentReferenceId is empty string', async () => {
162+
const Component = contentReferenceComponentFactory({
163+
contentReferences: {
164+
'1': {
165+
id: '1',
166+
type: 'SecurityAlertsPage',
167+
},
168+
} as ContentReferences,
169+
contentReferencesVisible: true,
170+
loading: false,
171+
});
172+
173+
const { container } = render(
174+
<Component
175+
{...({ contentReferenceId: '', contentReferenceCount: -1 } as ContentReferenceNode)}
176+
/>
177+
);
178+
179+
expect(container).toBeEmptyDOMElement();
180+
expect(screen.queryByText('[-1]')).not.toBeInTheDocument();
181+
});
157182
});

x-pack/solutions/security/plugins/security_solution/public/assistant/get_comments/content_reference/components/content_reference_component_factory.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ export const contentReferenceComponentFactory = ({
3030
contentReferenceNode: ContentReferenceNode
3131
): React.ReactNode => {
3232
if (!contentReferencesVisible) return null;
33+
if (!contentReferenceNode.contentReferenceId) return null;
3334

3435
const defaultNode = (
3536
<ContentReferenceButton

x-pack/solutions/security/plugins/security_solution/public/assistant/get_comments/content_reference/components/security_alerts_page_reference.tsx

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@ import { EuiLink } from '@elastic/eui';
1111
import type { ContentReferenceNode } from '../content_reference_parser';
1212
import { PopoverReference } from './popover_reference';
1313
import { SECURITY_ALERTS_PAGE_REFERENCE_LABEL } from './translations';
14-
import { useKibana } from '../../../../common/lib/kibana';
14+
import { useNavigateToAlertsPageWithFilters } from '../../../../common/hooks/use_navigate_to_alerts_page_with_filters';
15+
import { FILTER_OPEN, FILTER_ACKNOWLEDGED } from '../../../../../common/types';
1516

1617
interface Props {
1718
contentReferenceNode: ContentReferenceNode;
@@ -22,17 +23,22 @@ export const SecurityAlertsPageReference: React.FC<Props> = ({
2223
contentReferenceNode,
2324
securityAlertsPageContentReference,
2425
}) => {
25-
const { navigateToApp } = useKibana().services.application;
26+
const openAlertsPageWithFilters = useNavigateToAlertsPageWithFilters();
2627

2728
const onClick = useCallback(
2829
(e: React.MouseEvent) => {
2930
e.preventDefault();
30-
navigateToApp('security', {
31-
path: `alerts`,
32-
openInNewTab: true,
33-
});
31+
openAlertsPageWithFilters(
32+
{
33+
selectedOptions: [FILTER_OPEN, FILTER_ACKNOWLEDGED],
34+
fieldName: 'kibana.alert.workflow_status',
35+
persist: false,
36+
},
37+
true,
38+
'(global:(timerange:(fromStr:now-24h,kind:relative,toStr:now)))'
39+
);
3440
},
35-
[navigateToApp]
41+
[openAlertsPageWithFilters]
3642
);
3743

3844
return (

x-pack/solutions/security/plugins/security_solution/public/assistant/get_comments/content_reference/content_reference_parser.test.ts

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,62 @@ import type { Parent } from 'mdast';
1111
import { ContentReferenceParser } from './content_reference_parser';
1212

1313
describe('ContentReferenceParser', () => {
14+
it('extracts references from poem', async () => {
15+
const file = unified().use([[markdown, {}], ContentReferenceParser])
16+
.parse(`With a wagging tail and a wet, cold nose,{reference(ccaSI)}
17+
A furry friend, from head to toes.{reference(ccaSI)}
18+
Loyal companion, always near,{reference(ccaSI)}
19+
Chasing squirrels, full of cheer.{reference(ccaSI)}
20+
A paw to hold, a gentle nudge,
21+
{reference(ccaSI)}
22+
A furry alarm, a playful judge.{reference(ccaSI)}
23+
From golden retrievers to tiny Chihuahuas,{reference(ccaSI)}
24+
Their love's a gift, that always conquers.{reference(ccaSI)}
25+
So cherish your dog, with all your might,{reference(ccaSI)}
26+
Their love's a beacon, shining bright.{reference(ccaSI)}`) as Parent;
27+
28+
expect(
29+
(file.children[0] as Parent).children.filter(
30+
(child) => (child.type as string) === 'contentReference'
31+
)
32+
).toHaveLength(10);
33+
expect(file.children[0].children).toEqual(
34+
expect.arrayContaining([
35+
expect.objectContaining({ type: 'text', value: '\nA paw to hold, a gentle nudge,\n' }),
36+
])
37+
);
38+
});
39+
40+
it('extracts reference after linebreak', async () => {
41+
const file = unified().use([[markdown, {}], ContentReferenceParser]).parse(`First line
42+
{reference(FTQJp)}
43+
`) as Parent;
44+
45+
expect(file.children[0].children).toEqual(
46+
expect.arrayContaining([
47+
expect.objectContaining({ type: 'text', value: 'First line\n' }),
48+
expect.objectContaining({ type: 'contentReference' }),
49+
])
50+
);
51+
});
52+
53+
it('eats empty content reference', async () => {
54+
const file = unified()
55+
.use([[markdown, {}], ContentReferenceParser])
56+
.parse('There is an empty content reference.{reference()}') as Parent;
57+
58+
expect(file.children[0].children).toEqual(
59+
expect.arrayContaining([
60+
expect.objectContaining({ type: 'text', value: 'There is an empty content reference.' }),
61+
expect.objectContaining({
62+
type: 'contentReference',
63+
contentReferenceCount: -1,
64+
contentReferenceId: '',
65+
}),
66+
])
67+
);
68+
});
69+
1470
it('eats space preceding content reference', async () => {
1571
const file = unified()
1672
.use([[markdown, {}], ContentReferenceParser])

x-pack/solutions/security/plugins/security_solution/public/assistant/get_comments/content_reference/content_reference_parser.ts

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@ export interface ContentReferenceNode extends Node {
1717
contentReferenceBlock: ContentReferenceBlock;
1818
}
1919

20-
/**
21-
* Parses `{reference(contentReferenceId)}` or ` {reference(contentReferenceId)}` (notice space prefix) into ContentReferenceNode
22-
*/
20+
/** Matches `{reference` and ` {reference(` */
21+
const REFERENCE_START_PATTERN = '\\u0020?\\{reference';
22+
2323
export const ContentReferenceParser: Plugin = function ContentReferenceParser() {
2424
const Parser = this.Parser;
2525
const tokenizers = Parser.prototype.inlineTokenizers;
@@ -33,10 +33,9 @@ export const ContentReferenceParser: Plugin = function ContentReferenceParser()
3333
value,
3434
silent
3535
) {
36-
const [match] = value.match(/^\s?{reference/) || [];
37-
if (!match) return false;
36+
const [match] = value.match(new RegExp(`^${REFERENCE_START_PATTERN}`)) || [];
3837

39-
if (value.includes('\n')) return false;
38+
if (!match) return false;
4039

4140
if (value[match.length] !== '(') return false;
4241

@@ -81,10 +80,6 @@ export const ContentReferenceParser: Plugin = function ContentReferenceParser()
8180
});
8281
}
8382

84-
if (!contentReferenceId) {
85-
return false;
86-
}
87-
8883
if (silent) {
8984
return true;
9085
}
@@ -95,6 +90,9 @@ export const ContentReferenceParser: Plugin = function ContentReferenceParser()
9590
const contentReferenceBlock: ContentReferenceBlock = `{reference(${contentReferenceId})}`;
9691

9792
const getContentReferenceCount = (id: string) => {
93+
if (!id) {
94+
return -1;
95+
}
9896
if (id in contentReferenceCounts) {
9997
return contentReferenceCounts[id];
10098
}
@@ -104,18 +102,24 @@ export const ContentReferenceParser: Plugin = function ContentReferenceParser()
104102

105103
const toEat = `${match.startsWith(' ') ? ' ' : ''}${contentReferenceBlock}`;
106104

107-
return eat(toEat)({
105+
const contentReferenceNode: ContentReferenceNode = {
108106
type: 'contentReference',
109107
contentReferenceId,
110108
contentReferenceCount: getContentReferenceCount(contentReferenceId),
111109
contentReferenceBlock,
112-
} as ContentReferenceNode);
110+
};
111+
112+
return eat(toEat)(contentReferenceNode);
113113
};
114114

115115
tokenizeCustomCitation.notInLink = true;
116116

117117
tokenizeCustomCitation.locator = (value, fromIndex) => {
118-
return 1 + (value.substring(fromIndex).match(/\s?{reference/)?.index ?? -2);
118+
const nextIndex = value.substring(fromIndex).match(new RegExp(REFERENCE_START_PATTERN))?.index;
119+
if (nextIndex === undefined) {
120+
return -1;
121+
}
122+
return nextIndex + 1;
119123
};
120124

121125
tokenizers.contentReference = tokenizeCustomCitation;

0 commit comments

Comments
 (0)