Skip to content

Commit 7e5faf6

Browse files
authored
[Automatic Migrations] Sanitize lookup names for index creation (elastic#240228)
## Summary - Fixes: elastic/security-team#14348 This PR fixes the issue with lookup names which could not be uploaded because it violated index naming conventions. See below demo to see the error. ### Before https://github.com/user-attachments/assets/ea940699-9878-42ef-9876-55e927e0b3be ### After https://github.com/user-attachments/assets/adb06e22-b0a5-4c16-b15e-7cfa308966eb ### Checklist Check the PR satisfies following conditions. Reviewers should verify this PR satisfies this list as well. - [ ] Any text added follows [EUI's writing guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses sentence case text and includes [i18n support](https://github.com/elastic/kibana/blob/main/src/platform/packages/shared/kbn-i18n/README.md) - [ ] [Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html) was added for features that require explanation or tutorials - [ ] [Unit or functional tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html) were updated or added to match the most common scenarios - [ ] If a plugin configuration key changed, check if it needs to be allowlisted in the cloud and added to the [docker list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker) - [ ] This was checked for breaking HTTP API changes, and any breaking changes have been approved by the breaking-change committee. The `release_note:breaking` label should be applied in these situations. - [ ] [Flaky Test Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was used on any tests changed - [ ] The PR description includes the appropriate Release Notes section, and the correct `release_note:*` label is applied per the [guidelines](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process) - [ ] Review the [backport guidelines](https://docs.google.com/document/d/1VyN5k91e5OVumlc0Gb9RPa3h1ewuPE705nRtioPiTvY/edit?usp=sharing) and apply applicable `backport:*` labels. ### Identify risks Does this PR introduce any risks? For example, consider risks like hard to test bugs, performance regression, potential of data loss. Describe the risk, its severity, and mitigation for each identified risk. Invite stakeholders and evaluate how to proceed before merging. - [ ] [See some risk examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) - [ ] ...
1 parent f8984ec commit 7e5faf6

File tree

8 files changed

+402
-47
lines changed

8 files changed

+402
-47
lines changed

src/platform/packages/shared/kbn-utils/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,4 @@
1010
export * from './src/json';
1111
export * from './src/path';
1212
export * from './src/streams';
13+
export * from './src/index/index';
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
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", the "GNU Affero General Public License v3.0 only", and the "Server Side
5+
* Public License v 1"; you may not use this file except in compliance with, at
6+
* your election, the "Elastic License 2.0", the "GNU Affero General Public
7+
* License v3.0 only", or the "Server Side Public License, v 1".
8+
*/
9+
10+
export * from './to_valid_index_name';
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
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", the "GNU Affero General Public License v3.0 only", and the "Server Side
5+
* Public License v 1"; you may not use this file except in compliance with, at
6+
* your election, the "Elastic License 2.0", the "GNU Affero General Public
7+
* License v3.0 only", or the "Server Side Public License, v 1".
8+
*/
9+
10+
import { toValidIndexName } from './to_valid_index_name';
11+
12+
describe('toValidIndexName', () => {
13+
it('should convert camelCase to kebab-case', () => {
14+
expect(toValidIndexName('camelCaseInput')).toBe('camel-case-input');
15+
});
16+
17+
it('should replace forbidden characters', () => {
18+
expect(toValidIndexName('foo/bar*baz?qux"quux<quuz>corge|grault,garply#waldo:fred')).toBe(
19+
'foo-bar-baz-qux-quux-quuz-corge-grault-garply-waldo-fred'
20+
);
21+
});
22+
23+
it('should remove leading -, _, +', () => {
24+
expect(toValidIndexName('-foo')).toBe('foo');
25+
expect(toValidIndexName('_foo')).toBe('foo');
26+
expect(toValidIndexName('+foo')).toBe('foo');
27+
});
28+
29+
it('should remove trailing hyphens', () => {
30+
expect(toValidIndexName('foo-')).toBe('foo');
31+
expect(toValidIndexName('foo--')).toBe('foo');
32+
});
33+
34+
it('should handle multiple forbidden characters together', () => {
35+
expect(toValidIndexName('foo*?bar')).toBe('foo-bar');
36+
});
37+
38+
it('should handle spaces and mixed casing', () => {
39+
expect(toValidIndexName(' Foo BarBaz ')).toBe('foo-bar-baz');
40+
});
41+
42+
it('should handle numbers and symbols', () => {
43+
expect(toValidIndexName('foo123')).toBe('foo-123');
44+
expect(toValidIndexName('foo#123')).toBe('foo-123');
45+
});
46+
47+
it('should not remove valid underscores in the middle', () => {
48+
expect(toValidIndexName('foo_bar')).toBe('foo-bar');
49+
});
50+
51+
it('should handle already valid index names', () => {
52+
expect(toValidIndexName('valid-index-name')).toBe('valid-index-name');
53+
});
54+
55+
it('should handle valid single character input', () => {
56+
expect(toValidIndexName('a')).toBe('a');
57+
});
58+
59+
describe('error scenarios', () => {
60+
it('should throw on empty string', () => {
61+
expect(() => toValidIndexName('')).toThrow('Input string must be non-empty');
62+
expect(() => toValidIndexName(' ')).toThrow('Input string must be non-empty');
63+
});
64+
65+
it('should throw on single whitespace or forbidden character input', () => {
66+
expect(() => toValidIndexName(' ')).toThrow('Input string must be non-empty');
67+
expect(() => toValidIndexName('-')).toThrow('No valid characters in input string');
68+
});
69+
70+
it('should throw on input with only forbidden characters', () => {
71+
expect(() => toValidIndexName('*/?"<>|,#:')).toThrow('No valid characters in input string');
72+
});
73+
});
74+
});
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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", the "GNU Affero General Public License v3.0 only", and the "Server Side
5+
* Public License v 1"; you may not use this file except in compliance with, at
6+
* your election, the "Elastic License 2.0", the "GNU Affero General Public
7+
* License v3.0 only", or the "Server Side Public License, v 1".
8+
*/
9+
10+
import { kebabCase } from 'lodash';
11+
12+
/** Converts a given string into a valid Elasticsearch index name. */
13+
export const toValidIndexName = (str: string): string => {
14+
if (!str || str.trim() === '') {
15+
throw new Error('Input string must be non-empty');
16+
}
17+
18+
// Start with kebabCase to handle most transformations
19+
let result = kebabCase(str);
20+
21+
// Additional processing for ES index name requirements
22+
result = result
23+
// ES doesn't allow \, /, *, ?, ", <, >, |, comma, #, :
24+
.replace(/[\\/*?"<>|,#:]/g, '-')
25+
// Cannot start with -, _, +
26+
.replace(/^[-_+]/, '');
27+
28+
// Remove trailing hyphens
29+
while (result.endsWith('-')) {
30+
result = result.slice(0, -1);
31+
}
32+
33+
if (result.length === 0) {
34+
throw new Error('No valid characters in input string');
35+
}
36+
37+
return result;
38+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
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 { SiemMigrationsDataLookupsClient } from './siem_migrations_data_lookups_client';
9+
import { loggingSystemMock, elasticsearchServiceMock } from '@kbn/core/server/mocks';
10+
import { LOOKUPS_INDEX_PREFIX } from '../../../../../common/siem_migrations/constants';
11+
import type { AuthenticatedUser } from '@kbn/security-plugin-types-common';
12+
import type { IScopedClusterClient } from '@kbn/core/server';
13+
14+
describe('SiemMigrationsDataLookupsClient', () => {
15+
const esClient =
16+
elasticsearchServiceMock.createScopedClusterClient() as unknown as IScopedClusterClient;
17+
18+
const logger = loggingSystemMock.createLogger();
19+
const currentUser = {
20+
userName: 'testUser',
21+
profile_uid: 'testProfileUid',
22+
} as unknown as AuthenticatedUser;
23+
24+
const spaceId = 'default';
25+
26+
let client: SiemMigrationsDataLookupsClient;
27+
28+
beforeEach(() => {
29+
jest.clearAllMocks();
30+
client = new SiemMigrationsDataLookupsClient(currentUser, esClient, logger, spaceId);
31+
});
32+
33+
describe('create', () => {
34+
it('should create index and index data for valid lookup name', async () => {
35+
esClient.asCurrentUser.indices.create = jest.fn().mockResolvedValue({});
36+
esClient.asCurrentUser.bulk = jest.fn().mockResolvedValue({});
37+
const data = [{ foo: 'bar' }];
38+
const indexName = `${LOOKUPS_INDEX_PREFIX}${spaceId}_mitre-event-names`;
39+
40+
const result = await client.create('mitre-eventNames', data);
41+
42+
expect(esClient.asCurrentUser.indices.create).toHaveBeenCalledWith(
43+
expect.objectContaining({ index: indexName })
44+
);
45+
expect(esClient.asCurrentUser.bulk).toHaveBeenCalled();
46+
expect(result).toBe(indexName);
47+
});
48+
49+
it('should throw and log error for invalid lookup name', async () => {
50+
await expect(client.create('/', [])).rejects.toThrow(
51+
/does not conform to index naming rules/
52+
);
53+
expect(logger.error).toHaveBeenCalledWith(
54+
expect.stringContaining('does not conform to index naming rules')
55+
);
56+
});
57+
58+
it('should not throw if index already exists', async () => {
59+
esClient.asCurrentUser.indices.create = jest.fn().mockRejectedValue({
60+
meta: { body: { error: { type: 'resource_already_exists_exception' } } },
61+
});
62+
esClient.asCurrentUser.bulk = jest.fn().mockResolvedValue({});
63+
await expect(client.create('test-lookup', [{ foo: 1 }])).resolves.toBeDefined();
64+
});
65+
66+
it('should throw and logs error for other index creation errors', async () => {
67+
esClient.asCurrentUser.indices.create = jest.fn().mockRejectedValue(new Error('ES error'));
68+
await expect(client.create('test-lookup', [])).rejects.toThrow('ES error');
69+
expect(logger.error).toHaveBeenCalledWith(
70+
expect.stringContaining('Error creating lookup index')
71+
);
72+
});
73+
74+
it('should throw and logs error for bulk indexing errors except 404', async () => {
75+
esClient.asCurrentUser.indices.create = jest.fn().mockResolvedValue({});
76+
esClient.asCurrentUser.bulk = jest
77+
.fn()
78+
.mockRejectedValue({ statusCode: 500, message: 'Bulk error' });
79+
await expect(client.create('test-lookup', [{ foo: 1 }])).rejects.toEqual(
80+
expect.objectContaining({ statusCode: 500 })
81+
);
82+
expect(logger.error).toHaveBeenCalledWith(
83+
expect.stringContaining('Error indexing data for lookup index')
84+
);
85+
});
86+
87+
it('should ignore bulk indexing 404 errors', async () => {
88+
esClient.asCurrentUser.indices.create = jest.fn().mockResolvedValue({});
89+
esClient.asCurrentUser.bulk = jest.fn().mockRejectedValue({ statusCode: 404 });
90+
await expect(client.create('test-lookup', [{ foo: 1 }])).resolves.toBeDefined();
91+
});
92+
93+
it('should skip bulk indexing if data is empty', async () => {
94+
esClient.asCurrentUser.indices.create = jest.fn().mockResolvedValue({});
95+
esClient.asCurrentUser.bulk = jest.fn();
96+
await client.create('test-lookup', []);
97+
expect(esClient.asCurrentUser.bulk).not.toHaveBeenCalled();
98+
});
99+
});
100+
101+
describe('indexData', () => {
102+
it('should call bulk API with correct body', async () => {
103+
esClient.asCurrentUser.bulk = jest.fn().mockResolvedValue({});
104+
const indexName = 'test-index';
105+
const data = [{ a: 1 }, { b: 2 }];
106+
await client.indexData(indexName, data);
107+
expect(esClient.asCurrentUser.bulk).toHaveBeenCalledWith(
108+
expect.objectContaining({ index: indexName, body: expect.any(Array) })
109+
);
110+
});
111+
112+
it('should throw and log error for bulk errors except 404', async () => {
113+
esClient.asCurrentUser.bulk = jest
114+
.fn()
115+
.mockRejectedValue({ statusCode: 500, message: 'Bulk error' });
116+
await expect(client.indexData('test-index', [{ foo: 1 }])).rejects.toEqual(
117+
expect.objectContaining({ statusCode: 500 })
118+
);
119+
expect(logger.error).toHaveBeenCalledWith(
120+
expect.stringContaining('Error indexing data for lookup index')
121+
);
122+
});
123+
124+
it('should ignore 404 errors', async () => {
125+
esClient.asCurrentUser.bulk = jest.fn().mockRejectedValue({ statusCode: 404 });
126+
await expect(client.indexData('test-index', [{ foo: 1 }])).resolves.toBeUndefined();
127+
});
128+
});
129+
});

x-pack/solutions/security/plugins/security_solution/server/lib/siem_migrations/common/data/siem_migrations_data_lookups_client.ts

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import { sha256 } from 'js-sha256';
99
import type { AuthenticatedUser, IScopedClusterClient, Logger } from '@kbn/core/server';
1010
import { retryTransientEsErrors } from '@kbn/index-adapter';
11+
import { toValidIndexName } from '@kbn/utils';
1112
import { LOOKUPS_INDEX_PREFIX } from '../../../../../common/siem_migrations/constants';
1213

1314
export type LookupData = object[];
@@ -21,7 +22,8 @@ export class SiemMigrationsDataLookupsClient {
2122
) {}
2223

2324
async create(lookupName: string, data: LookupData): Promise<string> {
24-
const indexName = `${LOOKUPS_INDEX_PREFIX}${this.spaceId}_${lookupName}`;
25+
const sanitizedLookupName = this.getSanitizedLookupName(lookupName);
26+
const indexName = `${LOOKUPS_INDEX_PREFIX}${this.spaceId}_${sanitizedLookupName}`;
2527
try {
2628
await this.executeEs(() =>
2729
this.esScopedClient.asCurrentUser.indices.create({
@@ -68,4 +70,14 @@ export class SiemMigrationsDataLookupsClient {
6870
private generateDocumentHash(document: object): string {
6971
return sha256.create().update(JSON.stringify(document)).hex(); // document need to be created in a deterministic way
7072
}
73+
74+
private getSanitizedLookupName(lookupName: string): string {
75+
try {
76+
return toValidIndexName(lookupName);
77+
} catch (error) {
78+
const message = `Error creating lookup index from lookup: ${lookupName}. It does not conform to index naming rules. ${error.message}`;
79+
this.logger.error(message);
80+
throw new Error(message);
81+
}
82+
}
7183
}

0 commit comments

Comments
 (0)