From 28aa274f665b1aff891bf055a592851c8ec53d30 Mon Sep 17 00:00:00 2001 From: Elena Shostak <165678770+elena-shostak@users.noreply.github.com> Date: Thu, 19 Sep 2024 12:25:03 +0200 Subject: [PATCH] Updated js-yaml to v4 (#190678) ## Summary Updated `js-yaml` to `4.1.0`. This PR also introduces a type override for the `js-yaml` load function to maintain compatibility across the codebase. Specifically, updated type definition of the load function looks as follows: ```typescript function load(str: string, opts?: jsyaml.LoadOptions): T; ``` The original type definition of the load function in `js-yaml` changed from `any` to `unknown`. This change would require extensive type updates throughout the entire repository to accommodate the `unknown` type. To avoid widespread type changes and potential issues in the codebase, the type is overriden back to `any` for now. This is a temporary measure, we plan to address the necessary type changes in subsequent PRs, where teams will gradually update the codebase to work with the `unknown` type. ### Checklist - [x] [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 ## Release note Updated `js-yaml` to `4.1.0`. --------- Co-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com> Co-authored-by: Maxim Palenov --- .../scripts/fix-location-collection.ts | 2 - .buildkite/pipeline-utils/agent_images.ts | 1 - .buildkite/pipeline-utils/buildkite/client.ts | 1 - .../ci-stats/pick_test_group_run_order.ts | 1 - package.json | 4 +- .../src/utils/read_config.ts | 4 +- packages/kbn-config/src/raw/read_config.ts | 6 +- .../src/mdx/get_all_doc_file_ids.ts | 2 +- packages/kbn-docs-utils/tsconfig.json | 1 + .../src/utils/read_roles_from_resource.ts | 2 +- packages/kbn-eslint-config/.eslintrc.js | 1 - .../saml_auth/serverless/auth_provider.ts | 2 +- .../saml_auth/stateful/auth_provider.ts | 2 +- .../tsconfig.json | 1 + .../src/utils/extract_by_json_pointer.ts | 6 +- .../src/utils/read_document.ts | 35 ++++-- .../src/utils/write_yaml_document.ts | 6 +- .../tests/bundler/bundle_specs.ts | 6 +- ..._specs_with_multiple_modifications.test.ts | 4 +- .../tests/bundler/circular.test.ts | 5 +- .../tests/merger/merge_specs.ts | 6 +- packages/kbn-openapi-bundler/tsconfig.json | 2 +- packages/kbn-optimizer/src/limits.ts | 4 +- packages/kbn-optimizer/tsconfig.json | 3 +- ...eptions_api_2023_10_31.bundled.schema.yaml | 6 +- ...eptions_api_2023_10_31.bundled.schema.yaml | 6 +- ...eptions_api_2023_10_31.bundled.schema.yaml | 10 +- ...eptions_api_2023_10_31.bundled.schema.yaml | 10 +- ...n_lists_api_2023_10_31.bundled.schema.yaml | 12 +- ...n_lists_api_2023_10_31.bundled.schema.yaml | 12 +- .../lib/config/ftr_configs_manifest.ts | 4 +- scripts/enabled_ftr_configs.js | 2 +- .../reload_logging_config.test.ts | 4 +- src/cli_encryption_keys/encryption_config.js | 4 +- src/cli_encryption_keys/generate.js | 4 +- src/cli_encryption_keys/interactive.js | 6 +- src/dev/build/tasks/fleet/bundle_packages.ts | 6 +- .../create_os_package_kibana_yml.ts | 4 +- .../rewrite_buildkite_agent_rules.ts | 4 +- src/dev/precommit_hook/casing_check_config.js | 1 + src/dev/stylelint/lint_files.js | 4 +- src/dev/tsconfig.json | 1 + .../server/kibana_config_writer.test.ts | 10 +- .../server/kibana_config_writer.ts | 6 +- .../usage/telemetry_usage_collector.ts | 4 +- typings/@types/js-yaml/index.d.ts | 12 ++ .../kbn-data-forge/src/lib/create_config.ts | 2 +- ...sistant_api_2023_10_31.bundled.schema.yaml | 10 +- ...sistant_api_2023_10_31.bundled.schema.yaml | 10 +- .../cloud_defend/common/utils/helpers.ts | 4 +- .../control_general_view/index.test.tsx | 12 +- .../fleet/common/services/agent_cm_to_yaml.ts | 4 +- .../services/full_agent_policy_to_yaml.ts | 4 +- .../common/services/output_helpers.test.ts | 18 +-- .../services/validate_package_policy.test.ts | 64 +++++----- x-pack/plugins/fleet/cypress/tasks/login.ts | 4 +- x-pack/plugins/fleet/cypress/tsconfig.json | 3 +- .../components/agent_policy_yaml_flyout.tsx | 4 +- .../steps/step_configure_package.test.tsx | 4 +- .../components/page_steps/add_integration.tsx | 4 +- .../services/has_invalid_but_required_var.ts | 4 +- .../single_page_layout/hooks/form.tsx | 4 +- .../hooks/use_package_policy.tsx | 6 +- .../use_fleet_proxy_form.tsx | 9 +- .../components/edit_output_flyout/index.tsx | 8 +- .../output_form_validators.tsx | 4 +- .../edit_output_flyout/use_output_form.tsx | 6 +- .../screens/detail/utils/changelog_utils.ts | 4 +- .../agent_enrollment_flyout/hooks.tsx | 4 +- .../server/routes/agent_policy/handlers.ts | 4 +- .../agent_policies/full_agent_policy.ts | 6 +- .../fleet/server/services/agent_policy.ts | 4 +- .../fleet/server/services/epm/agent/agent.ts | 10 +- .../server/services/epm/archive/parse.ts | 10 +- .../elasticsearch/ingest_pipeline/helpers.ts | 6 +- .../server/services/epm/elasticsearch/meta.ts | 6 +- .../elasticsearch/template/template.test.ts | 110 +++++++++--------- .../epm/elasticsearch/transform/install.ts | 4 +- .../server/services/epm/fields/field.test.ts | 8 +- .../fleet/server/services/epm/fields/field.ts | 10 +- .../assets/dataset/ingest_pipeline.ts | 4 +- .../assets/dataset/manifest.ts | 4 +- .../custom_integrations/assets/manifest.ts | 4 +- .../fleet/server/services/epm/packages/get.ts | 4 +- .../epm/packages/get_template_inputs.ts | 4 +- .../services/epm/packages/utils.test.ts | 4 +- .../server/services/epm/packages/utils.ts | 4 +- .../plugins/fleet/server/services/output.ts | 16 +-- .../fleet/server/services/package_policy.ts | 6 +- .../services/preconfiguration/outputs.ts | 4 +- .../scripts/util/read_kibana_config.ts | 2 +- .../server/graphs/ecs/pipeline.ts | 4 +- .../build_integration.test.ts | 2 +- .../integration_builder/build_integration.ts | 4 +- .../server/integration_builder/pipeline.ts | 2 +- .../server/util/processors.ts | 8 +- .../server/util/samples.ts | 2 +- .../java_runtime_attachment.tsx | 4 +- .../apm/scripts/shared/read_kibana_config.ts | 2 +- .../get_apm_package_policy_definition.ts | 2 +- .../scripts/evaluation/read_kibana_config.ts | 2 +- .../generate_custom_logs_yml.test.ts.snap | 16 +-- .../generate_custom_logs_yml.test.ts | 4 +- .../custom_logs/generate_custom_logs_yml.ts | 6 +- .../generate_system_logs_yml.test.ts.snap | 4 +- .../system_logs/generate_system_logs_yml.ts | 4 +- .../server/routes/flow/route.ts | 8 +- .../observability_onboarding/tsconfig.json | 3 +- .../e2e/tasks/read_kibana_config.ts | 2 +- .../uptime/e2e/tasks/read_kibana_config.ts | 2 +- .../osquery/cypress/cypress_base.config.ts | 2 +- ...osquery_api_2023_10_31.bundled.schema.yaml | 14 +-- ...osquery_api_2023_10_31.bundled.schema.yaml | 14 +-- .../scripts/generate_ecs_fieldmap/index.js | 2 +- ...ections_api_2023_10_31.bundled.schema.yaml | 16 +-- ...agement_api_2023_10_31.bundled.schema.yaml | 18 +-- ...alytics_api_2023_10_31.bundled.schema.yaml | 14 +-- ...imeline_api_2023_10_31.bundled.schema.yaml | 48 ++++---- ...ections_api_2023_10_31.bundled.schema.yaml | 12 +- ...agement_api_2023_10_31.bundled.schema.yaml | 18 +-- ...alytics_api_2023_10_31.bundled.schema.yaml | 14 +-- ...imeline_api_2023_10_31.bundled.schema.yaml | 48 ++++---- .../scripts/beat_docs/build.js | 4 +- .../endpoint/common/elastic_agent_service.ts | 4 +- .../apis/epm/get_templates_inputs.ts | 2 +- .../apis/epm/install_by_upload.ts | 2 +- .../tests/elastic_agent/config.spec.ts | 8 +- .../api_utils/api_key.ts | 2 +- .../lib/security/kibana_roles/kibana_roles.ts | 2 +- yarn.lock | 10 +- 130 files changed, 514 insertions(+), 490 deletions(-) create mode 100644 typings/@types/js-yaml/index.d.ts diff --git a/.buildkite/pipeline-resource-definitions/scripts/fix-location-collection.ts b/.buildkite/pipeline-resource-definitions/scripts/fix-location-collection.ts index b58f2728a8706..6f751e86057f7 100755 --- a/.buildkite/pipeline-resource-definitions/scripts/fix-location-collection.ts +++ b/.buildkite/pipeline-resource-definitions/scripts/fix-location-collection.ts @@ -38,7 +38,6 @@ async function main() { const preamble = locationFileLines.slice(0, 1); - // eslint-disable-next-line @kbn/eslint/no_unsafe_js_yaml const locationObj = jsYaml.load( locationFileLines.slice(1).join('\n') ) as BackstageLocationResource; @@ -46,7 +45,6 @@ async function main() { (fileName) => `${resourceDefinitionsBaseUrl}/${fileName}` ); - // eslint-disable-next-line @kbn/eslint/no_unsafe_js_yaml const locationYaml = jsYaml.dump(locationObj, { lineWidth: 400 }); fs.writeFileSync(locationFile, `${preamble.join('\n')}\n${locationYaml}`); diff --git a/.buildkite/pipeline-utils/agent_images.ts b/.buildkite/pipeline-utils/agent_images.ts index cfe93ba67a1f4..a87ea8dca6234 100644 --- a/.buildkite/pipeline-utils/agent_images.ts +++ b/.buildkite/pipeline-utils/agent_images.ts @@ -7,7 +7,6 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -// eslint-disable-next-line @kbn/eslint/no_unsafe_js_yaml import { dump } from 'js-yaml'; import { BuildkiteClient, BuildkiteCommandStep } from './buildkite'; diff --git a/.buildkite/pipeline-utils/buildkite/client.ts b/.buildkite/pipeline-utils/buildkite/client.ts index ac5fa4756bdaf..f96f18c7ee6cc 100644 --- a/.buildkite/pipeline-utils/buildkite/client.ts +++ b/.buildkite/pipeline-utils/buildkite/client.ts @@ -10,7 +10,6 @@ import axios, { AxiosInstance } from 'axios'; import { execSync, ExecSyncOptions } from 'child_process'; -// eslint-disable-next-line @kbn/eslint/no_unsafe_js_yaml import { dump } from 'js-yaml'; import { parseLinkHeader } from './parse_link_header'; diff --git a/.buildkite/pipeline-utils/ci-stats/pick_test_group_run_order.ts b/.buildkite/pipeline-utils/ci-stats/pick_test_group_run_order.ts index 7379ab526321a..0ccc991c1def9 100644 --- a/.buildkite/pipeline-utils/ci-stats/pick_test_group_run_order.ts +++ b/.buildkite/pipeline-utils/ci-stats/pick_test_group_run_order.ts @@ -12,7 +12,6 @@ import * as Fs from 'fs'; import * as globby from 'globby'; import minimatch from 'minimatch'; -// eslint-disable-next-line @kbn/eslint/no_unsafe_js_yaml import { load as loadYaml } from 'js-yaml'; import { BuildkiteClient, BuildkiteStep } from '../buildkite'; diff --git a/package.json b/package.json index 33fd113603e7a..24bfc1f5fe2cc 100644 --- a/package.json +++ b/package.json @@ -1130,7 +1130,7 @@ "jquery": "^3.5.0", "js-search": "^1.4.3", "js-sha256": "^0.9.0", - "js-yaml": "^3.14.1", + "js-yaml": "^4.1.0", "json-schema-to-ts": "^2.9.1", "json-stable-stringify": "^1.0.1", "json-stringify-pretty-compact": "1.2.0", @@ -1560,7 +1560,7 @@ "@types/jest": "^29.5.3", "@types/jquery": "^3.3.31", "@types/js-search": "^1.4.0", - "@types/js-yaml": "^3.11.1", + "@types/js-yaml": "^4.0.9", "@types/jsdom": "^20.0.1", "@types/json-schema": "^7", "@types/json-stable-stringify": "^1.0.32", diff --git a/packages/kbn-apm-config-loader/src/utils/read_config.ts b/packages/kbn-apm-config-loader/src/utils/read_config.ts index f1aaf77951c65..a240197b47628 100644 --- a/packages/kbn-apm-config-loader/src/utils/read_config.ts +++ b/packages/kbn-apm-config-loader/src/utils/read_config.ts @@ -8,7 +8,7 @@ */ import { readFileSync } from 'fs'; -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import { set } from '@kbn/safer-lodash-set'; import { ensureDeepObject } from '@kbn/std'; @@ -16,7 +16,7 @@ import { isPlainObject } from 'lodash'; const readYaml = (path: string) => { try { - return safeLoad(readFileSync(path, 'utf8')); + return load(readFileSync(path, 'utf8')); } catch (e) { /* tslint:disable:no-empty */ } diff --git a/packages/kbn-config/src/raw/read_config.ts b/packages/kbn-config/src/raw/read_config.ts index 9d002a5181f56..4330d99160abe 100644 --- a/packages/kbn-config/src/raw/read_config.ts +++ b/packages/kbn-config/src/raw/read_config.ts @@ -8,13 +8,13 @@ */ import { readFileSync } from 'fs'; -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import { set } from '@kbn/safer-lodash-set'; import { isPlainObject } from 'lodash'; import { ensureValidObjectPath } from '@kbn/std'; import { splitKey, getUnsplittableKey, replaceEnvVarRefs } from './utils'; -const readYaml = (path: string) => safeLoad(readFileSync(path, 'utf8')); +const readYaml = (path: string) => load(readFileSync(path, 'utf8')); interface YamlEntry { path: string[]; @@ -76,7 +76,7 @@ export const getConfigFromFiles = (configFiles: readonly string[]) => { for (const configFile of configFiles) { const yaml = readYaml(configFile); - if (yaml !== null) { + if (yaml) { yamlEntries.push(...listEntries(yaml)); } } diff --git a/packages/kbn-docs-utils/src/mdx/get_all_doc_file_ids.ts b/packages/kbn-docs-utils/src/mdx/get_all_doc_file_ids.ts index 79ced0bde3bed..60b693dcd93b5 100644 --- a/packages/kbn-docs-utils/src/mdx/get_all_doc_file_ids.ts +++ b/packages/kbn-docs-utils/src/mdx/get_all_doc_file_ids.ts @@ -38,7 +38,7 @@ export async function getAllDocFileIds(outputDir: string) { let fm; try { - fm = Yaml.safeLoad(fmYaml.slice(0, fmEnd.index)); + fm = Yaml.load(fmYaml.slice(0, fmEnd.index)); if (typeof fm !== 'object' || fm === null) { throw new Error('expected yaml to produce an object'); } diff --git a/packages/kbn-docs-utils/tsconfig.json b/packages/kbn-docs-utils/tsconfig.json index 9116acc8dcbc5..bdb89aa9ddc87 100644 --- a/packages/kbn-docs-utils/tsconfig.json +++ b/packages/kbn-docs-utils/tsconfig.json @@ -9,6 +9,7 @@ }, "include": [ "**/*.ts", + "../../typings/**/*" ], "exclude": [ "**/__fixtures__/**", diff --git a/packages/kbn-es/src/utils/read_roles_from_resource.ts b/packages/kbn-es/src/utils/read_roles_from_resource.ts index dea880d38144f..f42b38894ff25 100644 --- a/packages/kbn-es/src/utils/read_roles_from_resource.ts +++ b/packages/kbn-es/src/utils/read_roles_from_resource.ts @@ -9,7 +9,7 @@ import fs from 'fs'; import { extname } from 'path'; -import { safeLoad as loadYaml } from 'js-yaml'; +import { load as loadYaml } from 'js-yaml'; export const readRolesFromResource = (resourcePath: string) => { if (!fs.existsSync(resourcePath) || extname(resourcePath) !== '.yml') { diff --git a/packages/kbn-eslint-config/.eslintrc.js b/packages/kbn-eslint-config/.eslintrc.js index de3bb8e313ccc..a68dc6ecd949e 100644 --- a/packages/kbn-eslint-config/.eslintrc.js +++ b/packages/kbn-eslint-config/.eslintrc.js @@ -314,7 +314,6 @@ module.exports = { '@kbn/eslint/no_constructor_args_in_property_initializers': 'error', '@kbn/eslint/no_this_in_property_initializers': 'error', '@kbn/eslint/no_unsafe_console': 'error', - '@kbn/eslint/no_unsafe_js_yaml': 'error', '@kbn/imports/no_unresolvable_imports': 'error', '@kbn/imports/uniform_imports': 'error', '@kbn/imports/no_unused_imports': 'error', diff --git a/packages/kbn-ftr-common-functional-services/services/saml_auth/serverless/auth_provider.ts b/packages/kbn-ftr-common-functional-services/services/saml_auth/serverless/auth_provider.ts index 148d14464bd74..35314050f82ca 100644 --- a/packages/kbn-ftr-common-functional-services/services/saml_auth/serverless/auth_provider.ts +++ b/packages/kbn-ftr-common-functional-services/services/saml_auth/serverless/auth_provider.ts @@ -51,7 +51,7 @@ export class ServerlessAuthProvider implements AuthProvider { } getSupportedRoleDescriptors(): Record { - return readRolesDescriptorsFromResource(this.rolesDefinitionPath); + return readRolesDescriptorsFromResource(this.rolesDefinitionPath) as Record; } getDefaultRole(): string { return getDefaultServerlessRole(this.projectType); diff --git a/packages/kbn-ftr-common-functional-services/services/saml_auth/stateful/auth_provider.ts b/packages/kbn-ftr-common-functional-services/services/saml_auth/stateful/auth_provider.ts index 10981afd5fac1..2f9dfc512d872 100644 --- a/packages/kbn-ftr-common-functional-services/services/saml_auth/stateful/auth_provider.ts +++ b/packages/kbn-ftr-common-functional-services/services/saml_auth/stateful/auth_provider.ts @@ -19,7 +19,7 @@ import { export class StatefulAuthProvider implements AuthProvider { private readonly rolesDefinitionPath = resolve(REPO_ROOT, STATEFUL_ROLES_ROOT_PATH, 'roles.yml'); getSupportedRoleDescriptors(): Record { - return readRolesDescriptorsFromResource(this.rolesDefinitionPath); + return readRolesDescriptorsFromResource(this.rolesDefinitionPath) as Record; } getDefaultRole() { return 'editor'; diff --git a/packages/kbn-ftr-common-functional-services/tsconfig.json b/packages/kbn-ftr-common-functional-services/tsconfig.json index 490eed5f7ac0e..2cad85eb14fb2 100644 --- a/packages/kbn-ftr-common-functional-services/tsconfig.json +++ b/packages/kbn-ftr-common-functional-services/tsconfig.json @@ -9,6 +9,7 @@ }, "include": [ "**/*.ts", + "../../typings/**/*" ], "kbn_references": [ "@kbn/core-saved-objects-server", diff --git a/packages/kbn-openapi-bundler/src/utils/extract_by_json_pointer.ts b/packages/kbn-openapi-bundler/src/utils/extract_by_json_pointer.ts index 16dc07dbc01b5..609bec7e785d9 100644 --- a/packages/kbn-openapi-bundler/src/utils/extract_by_json_pointer.ts +++ b/packages/kbn-openapi-bundler/src/utils/extract_by_json_pointer.ts @@ -8,7 +8,7 @@ */ import chalk from 'chalk'; -import { safeDump } from 'js-yaml'; +import { dump } from 'js-yaml'; import { isPlainObjectType } from './is_plain_object_type'; /** @@ -33,7 +33,7 @@ export function extractByJsonPointer(document: unknown, pointer: string): unknow throw new Error( `JSON Pointer ${chalk.bold(pointer)} resolution failure. Expected ${chalk.magenta( path.join('/') - )} to be a plain object but it has type "${typeof target}" in \n\n${safeDump(document, { + )} to be a plain object but it has type "${typeof target}" in \n\n${dump(document, { skipInvalid: true, })}` ); @@ -69,7 +69,7 @@ export function extractObjectByJsonPointer( throw new Error( `JSON Pointer resolution failure. Expected ${chalk.magenta( pointer - )} to be a plain object in \n\n${safeDump(document, { skipInvalid: true })}` + )} to be a plain object in \n\n${dump(document, { skipInvalid: true })}` ); } diff --git a/packages/kbn-openapi-bundler/src/utils/read_document.ts b/packages/kbn-openapi-bundler/src/utils/read_document.ts index b4fb20b1e6a2f..5c3f465e9ffd2 100644 --- a/packages/kbn-openapi-bundler/src/utils/read_document.ts +++ b/packages/kbn-openapi-bundler/src/utils/read_document.ts @@ -9,7 +9,7 @@ import fs from 'fs/promises'; import { basename, extname } from 'path'; -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import chalk from 'chalk'; import { logger } from '../logger'; import { isPlainObjectType } from './is_plain_object_type'; @@ -43,15 +43,32 @@ async function readFile(filePath: string): Promise { } async function readYamlFile(filePath: string): Promise> { - // Typing load's result to Record is optimistic as we can't be sure - // there is object inside a yaml file. We don't have this validation layer so far - // but using JSON Schemas here should mitigate this problem. - return safeLoad(await fs.readFile(filePath, { encoding: 'utf8' })); + const fileContent = await fs.readFile(filePath, { encoding: 'utf8' }); + const maybeObject = load(fileContent); + + if (!isPlainObjectType(maybeObject)) { + throw new Error( + `Expected ${chalk.bold(filePath)} to contain an object but got ${typeof maybeObject}` + ); + } + + return maybeObject; } async function readJsonFile(filePath: string): Promise> { - // Typing load's result to Record is optimistic as we can't be sure - // there is object inside a yaml file. We don't have this validation layer so far - // but using JSON Schemas here should mitigate this problem. - return await JSON.parse(await fs.readFile(filePath, { encoding: 'utf8' })); + const fileContent = await fs.readFile(filePath, { encoding: 'utf8' }); + + try { + const maybeObject = JSON.parse(fileContent); + + if (!isPlainObjectType(maybeObject)) { + throw new Error( + `Expected ${chalk.bold(filePath)} to contain an object but got ${typeof maybeObject}` + ); + } + + return maybeObject; + } catch { + throw new Error(`Unable to parse ${chalk.bold(filePath)}`); + } } diff --git a/packages/kbn-openapi-bundler/src/utils/write_yaml_document.ts b/packages/kbn-openapi-bundler/src/utils/write_yaml_document.ts index 07aee7f8f50a3..88886541836ff 100644 --- a/packages/kbn-openapi-bundler/src/utils/write_yaml_document.ts +++ b/packages/kbn-openapi-bundler/src/utils/write_yaml_document.ts @@ -8,7 +8,7 @@ */ import fs from 'fs/promises'; -import { safeDump } from 'js-yaml'; +import { dump } from 'js-yaml'; import { dirname } from 'path'; export async function writeYamlDocument(filePath: string, document: unknown): Promise { @@ -26,14 +26,14 @@ function stringifyToYaml(document: unknown): string { try { // Disable YAML Anchors https://yaml.org/spec/1.2.2/#3222-anchors-and-aliases // It makes YAML much more human readable - return safeDump(document, { + return dump(document, { noRefs: true, sortKeys: sortYamlKeys, skipInvalid: true, // Skip invalid types like `undefined` }); } catch (e) { // Try to stringify with YAML Anchors enabled - return safeDump(document, { noRefs: false, sortKeys: sortYamlKeys, skipInvalid: true }); + return dump(document, { noRefs: false, sortKeys: sortYamlKeys, skipInvalid: true }); } } diff --git a/packages/kbn-openapi-bundler/tests/bundler/bundle_specs.ts b/packages/kbn-openapi-bundler/tests/bundler/bundle_specs.ts index 7ea821e4fa9a4..b3093e00093a2 100644 --- a/packages/kbn-openapi-bundler/tests/bundler/bundle_specs.ts +++ b/packages/kbn-openapi-bundler/tests/bundler/bundle_specs.ts @@ -17,7 +17,7 @@ import { unlinkSync, writeFileSync, } from 'fs'; -import { safeDump, safeLoad } from 'js-yaml'; +import { dump, load } from 'js-yaml'; import { OpenAPIV3 } from 'openapi-types'; import { bundle, BundlerConfig } from '../../src/openapi_bundler'; @@ -59,7 +59,7 @@ function dumpSpecs(folderPath: string, oasSpecs: Record { const [bundledSpec] = Object.values(readBundledSpecs(outputFolderPath)); - const expected = safeLoad( + const expected = load( readFileSync(join(folderToBundlePath, 'expected.yaml'), { encoding: 'utf8' }) ); diff --git a/packages/kbn-openapi-bundler/tests/bundler/circular.test.ts b/packages/kbn-openapi-bundler/tests/bundler/circular.test.ts index ea88cd25b9424..08bcf79724e2f 100644 --- a/packages/kbn-openapi-bundler/tests/bundler/circular.test.ts +++ b/packages/kbn-openapi-bundler/tests/bundler/circular.test.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { safeDump } from 'js-yaml'; +import { dump } from 'js-yaml'; import { OpenAPIV3 } from 'openapi-types'; import { bundleSpecs } from './bundle_specs'; import { createOASDocument } from '../create_oas_document'; @@ -49,8 +49,7 @@ describe('OpenAPI Bundler - circular specs', () => { }) ); - expect(safeDump(bundledSpec.paths['/api/some_api']!.get!.responses['200'])) - .toMatchInlineSnapshot(` + expect(dump(bundledSpec.paths['/api/some_api']!.get!.responses['200'])).toMatchInlineSnapshot(` "content: application/json: schema: &ref_0 diff --git a/packages/kbn-openapi-bundler/tests/merger/merge_specs.ts b/packages/kbn-openapi-bundler/tests/merger/merge_specs.ts index ddce2136af781..7c9c805934c5f 100644 --- a/packages/kbn-openapi-bundler/tests/merger/merge_specs.ts +++ b/packages/kbn-openapi-bundler/tests/merger/merge_specs.ts @@ -17,7 +17,7 @@ import { unlinkSync, writeFileSync, } from 'fs'; -import { safeDump, safeLoad } from 'js-yaml'; +import { dump, load } from 'js-yaml'; import { OpenAPIV3 } from 'openapi-types'; import { merge, MergerConfig } from '../../src/openapi_merger'; @@ -59,7 +59,7 @@ function dumpSpecs(folderPath: string, oasSpecs: Record { const allFtrConfigs: string[] = []; for (const manifestRelPath of manifestPaths.all) { - const manifest: FtrConfigsManifest = JsYaml.safeLoad( + const manifest = JsYaml.load( Fs.readFileSync(Path.resolve(REPO_ROOT, manifestRelPath), 'utf8') - ); + ) as FtrConfigsManifest; const ftrConfigsInManifest = [ Object.values(manifest.enabled ?? []), diff --git a/scripts/enabled_ftr_configs.js b/scripts/enabled_ftr_configs.js index 96439e0499145..37e947948888f 100644 --- a/scripts/enabled_ftr_configs.js +++ b/scripts/enabled_ftr_configs.js @@ -20,7 +20,7 @@ var allManifestPaths = Object.values(manifestsSource).flat(); try { for (var manifestRelPath of allManifestPaths) { - var manifest = yaml.safeLoad(fs.readFileSync(manifestRelPath, 'utf8')); + var manifest = yaml.load(fs.readFileSync(manifestRelPath, 'utf8')); if (manifest.enabled) { manifest.enabled.forEach(function (x) { console.log(x); diff --git a/src/cli/serve/integration_tests/reload_logging_config.test.ts b/src/cli/serve/integration_tests/reload_logging_config.test.ts index 6a90aa8416eb6..aed9204be9077 100644 --- a/src/cli/serve/integration_tests/reload_logging_config.test.ts +++ b/src/cli/serve/integration_tests/reload_logging_config.test.ts @@ -15,7 +15,7 @@ import Del from 'del'; import * as Rx from 'rxjs'; import { map, filter, take } from 'rxjs'; -import { safeDump } from 'js-yaml'; +import { dump } from 'js-yaml'; import { getConfigFromFiles } from '@kbn/config'; const configFileLogConsole = follow( @@ -65,7 +65,7 @@ function createConfigManager(configPath: string) { return { modify(fn: (input: Record) => Record) { const oldContent = getConfigFromFiles([configPath]); - const yaml = safeDump(fn(oldContent)); + const yaml = dump(fn(oldContent)); Fs.writeFileSync(configPath, yaml); }, }; diff --git a/src/cli_encryption_keys/encryption_config.js b/src/cli_encryption_keys/encryption_config.js index 0e2f9bb419a9e..c255b3d72cf57 100644 --- a/src/cli_encryption_keys/encryption_config.js +++ b/src/cli_encryption_keys/encryption_config.js @@ -11,12 +11,12 @@ import crypto from 'crypto'; import { join } from 'path'; import { get } from 'lodash'; import { readFileSync } from 'fs'; -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import { getConfigDirectory } from '@kbn/utils'; export class EncryptionConfig { - #config = safeLoad(readFileSync(join(getConfigDirectory(), 'kibana.yml'))); + #config = load(readFileSync(join(getConfigDirectory(), 'kibana.yml'))); #encryptionKeyPaths = [ 'xpack.encryptedSavedObjects.encryptionKey', 'xpack.reporting.encryptionKey', diff --git a/src/cli_encryption_keys/generate.js b/src/cli_encryption_keys/generate.js index 162ee1fe101f1..e4830533b89cb 100644 --- a/src/cli_encryption_keys/generate.js +++ b/src/cli_encryption_keys/generate.js @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { safeDump } from 'js-yaml'; +import { dump } from 'js-yaml'; import { isEmpty } from 'lodash'; import { interactive } from './interactive'; import { Logger } from '../cli/logger'; @@ -33,7 +33,7 @@ export async function generate(encryptionConfig, command) { await interactive(keys, encryptionConfig.docs({ comment: true }), logger); } else { if (!command.quiet) logger.log('Settings:'); - logger.log(safeDump(keys)); + logger.log(dump(keys)); } } } diff --git a/src/cli_encryption_keys/interactive.js b/src/cli_encryption_keys/interactive.js index 3602978d688fd..676bafe6073f2 100644 --- a/src/cli_encryption_keys/interactive.js +++ b/src/cli_encryption_keys/interactive.js @@ -11,7 +11,7 @@ import { writeFileSync } from 'fs'; import { join } from 'path'; import { confirm, question } from '../cli/keystore/utils'; import { getConfigDirectory } from '@kbn/utils'; -import { safeDump } from 'js-yaml'; +import { dump } from 'js-yaml'; export async function interactive(keys, docs, logger) { const settings = Object.keys(keys); @@ -37,10 +37,10 @@ export async function interactive(keys, docs, logger) { `What filename should be used for the sample Kibana config file? [${defaultSaveLocation}])` ); const saveLocation = promptedSaveLocation || defaultSaveLocation; - writeFileSync(saveLocation, docs + safeDump(setKeys)); + writeFileSync(saveLocation, docs + dump(setKeys)); logger.log(`Wrote configuration to ${saveLocation}`); } else { logger.log('\nSettings:'); - logger.log(safeDump(setKeys)); + logger.log(dump(setKeys)); } } diff --git a/src/dev/build/tasks/fleet/bundle_packages.ts b/src/dev/build/tasks/fleet/bundle_packages.ts index f1f5f8dbfb78b..0d54703bd64f4 100644 --- a/src/dev/build/tasks/fleet/bundle_packages.ts +++ b/src/dev/build/tasks/fleet/bundle_packages.ts @@ -11,7 +11,7 @@ import Fsp from 'fs/promises'; import Path from 'path'; import JSON5 from 'json5'; -import { safeLoad, safeDump } from 'js-yaml'; +import { load, dump } from 'js-yaml'; import { asyncForEach } from '@kbn/std'; import { ToolingLog } from '@kbn/tooling-log'; @@ -88,10 +88,10 @@ export async function bundleFleetPackages(pkgDir: string, log: ToolingLog, confi return; } - const manifestYml = await safeLoad(manifestEntry.buffer.toString('utf8')); + const manifestYml = await load(manifestEntry.buffer.toString('utf8')); manifestYml.version = stackVersion; - const newManifestYml = safeDump(manifestYml); + const newManifestYml = dump(manifestYml); manifestEntry.buffer = Buffer.from(newManifestYml, 'utf8'); // Update all paths to use the new version diff --git a/src/dev/build/tasks/os_packages/create_os_package_kibana_yml.ts b/src/dev/build/tasks/os_packages/create_os_package_kibana_yml.ts index ac20298c225c6..5a56d556e640e 100644 --- a/src/dev/build/tasks/os_packages/create_os_package_kibana_yml.ts +++ b/src/dev/build/tasks/os_packages/create_os_package_kibana_yml.ts @@ -9,7 +9,7 @@ import { readFileSync, writeFileSync } from 'fs'; import { resolve } from 'path'; -import { safeDump } from 'js-yaml'; +import { dump } from 'js-yaml'; import { Build, Config, mkdirp } from '../../lib'; export async function createOSPackageKibanaYML(config: Config, build: Build) { @@ -25,7 +25,7 @@ export async function createOSPackageKibanaYML(config: Config, build: Build) { [/#pid.file:.*/g, 'pid.file: /run/kibana/kibana.pid'], [ /#logging.appenders.default:.*kibana\.log\n/gs, - safeDump({ + dump({ logging: { appenders: { file: { diff --git a/src/dev/buildkite_migration/rewrite_buildkite_agent_rules.ts b/src/dev/buildkite_migration/rewrite_buildkite_agent_rules.ts index 2c929e79a736c..f4c41faeea648 100644 --- a/src/dev/buildkite_migration/rewrite_buildkite_agent_rules.ts +++ b/src/dev/buildkite_migration/rewrite_buildkite_agent_rules.ts @@ -142,7 +142,7 @@ async function rewriteFile(ymlPath: string, log: ToolingLog) { let file = await readFile(resolve(REPO_ROOT, ymlPath), 'utf-8'); log.info('Loading: ' + ymlPath); - const doc = yaml.safeLoad(file); + const doc = yaml.load(file); if (!doc.steps) { log.info('No steps, skipping: ' + ymlPath); @@ -153,7 +153,7 @@ async function rewriteFile(ymlPath: string, log: ToolingLog) { if (isQueueTargetingRule(step) && !step.agents.queue.startsWith('kb-static')) { log.info('Rewriting: ' + ymlPath, step); file = editYmlInPlace(file, ['agents:', `queue: ${step.agents.queue}`], () => { - return yaml.safeDump({ agents: getFullAgentTargetingRule(step.agents.queue) }).split('\n'); + return yaml.dump({ agents: getFullAgentTargetingRule(step.agents.queue) }).split('\n'); }); } } diff --git a/src/dev/precommit_hook/casing_check_config.js b/src/dev/precommit_hook/casing_check_config.js index 37ef5ebe6c233..1ddf99b0a1d49 100644 --- a/src/dev/precommit_hook/casing_check_config.js +++ b/src/dev/precommit_hook/casing_check_config.js @@ -121,6 +121,7 @@ export const IGNORE_DIRECTORY_GLOBS = [ 'x-pack/dev-tools', 'packages/kbn-optimizer/src/__fixtures__/mock_repo/x-pack', 'typings/*', + 'typings/**/*', ]; /** diff --git a/src/dev/stylelint/lint_files.js b/src/dev/stylelint/lint_files.js index 567a2dfd1e1dd..23288212309b9 100644 --- a/src/dev/stylelint/lint_files.js +++ b/src/dev/stylelint/lint_files.js @@ -9,13 +9,13 @@ import stylelint from 'stylelint'; import path from 'path'; -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import fs from 'fs'; import { createFailError } from '@kbn/dev-cli-errors'; // load the include globs from .stylelintrc and convert them to regular expressions for filtering files const stylelintPath = path.resolve(__dirname, '..', '..', '..', '.stylelintrc'); -const styleLintConfig = safeLoad(fs.readFileSync(stylelintPath)); +const styleLintConfig = load(fs.readFileSync(stylelintPath)); /** * Lints a list of files with eslint. eslint reports are written to the log diff --git a/src/dev/tsconfig.json b/src/dev/tsconfig.json index e028b31a931f7..87473c1e79e82 100644 --- a/src/dev/tsconfig.json +++ b/src/dev/tsconfig.json @@ -6,6 +6,7 @@ "include": [ "**/*.js", "**/*.ts", + "../../typings/**/*" ], "exclude": [ "target/**/*", diff --git a/src/plugins/interactive_setup/server/kibana_config_writer.test.ts b/src/plugins/interactive_setup/server/kibana_config_writer.test.ts index 074793a9c7f19..de9de43782ca0 100644 --- a/src/plugins/interactive_setup/server/kibana_config_writer.test.ts +++ b/src/plugins/interactive_setup/server/kibana_config_writer.test.ts @@ -165,10 +165,12 @@ describe('KibanaConfigWriter', () => { serviceAccountToken: { name: 'some-token', value: 'some-value' }, }) ).rejects.toMatchInlineSnapshot(` - [YAMLException: duplicated mapping key at line 2, column 1: - foo: baz - ^] - `); + [YAMLException: duplicated mapping key (2:1) + + 1 | foo: bar + 2 | foo: baz + -----^] + `); expect(mockWriteFile).not.toHaveBeenCalled(); }); diff --git a/src/plugins/interactive_setup/server/kibana_config_writer.ts b/src/plugins/interactive_setup/server/kibana_config_writer.ts index abb874f81d8f0..68ec71f9a4a86 100644 --- a/src/plugins/interactive_setup/server/kibana_config_writer.ts +++ b/src/plugins/interactive_setup/server/kibana_config_writer.ts @@ -118,14 +118,14 @@ export class KibanaConfigWriter { ); const existingCommentedConfig = KibanaConfigWriter.commentOutKibanaConfig(existingConfig.raw); - configToWrite = `${existingCommentedConfig}\n\n# This section was automatically generated during setup.\n${yaml.safeDump( + configToWrite = `${existingCommentedConfig}\n\n# This section was automatically generated during setup.\n${yaml.dump( { ...existingConfig.parsed, ...config }, { flowLevel: 1 } )}\n`; } else { configToWrite = `${ existingConfig.raw - }\n\n# This section was automatically generated during setup.\n${yaml.safeDump(config, { + }\n\n# This section was automatically generated during setup.\n${yaml.dump(config, { flowLevel: 1, })}\n`; } @@ -172,7 +172,7 @@ export class KibanaConfigWriter { let parsedConfig: Record; try { - parsedConfig = getFlattenedObject(yaml.safeLoad(rawConfig) ?? {}); + parsedConfig = getFlattenedObject(yaml.load(rawConfig) ?? {}); } catch (err) { this.logger.error(`Failed to parse configuration file: ${getDetailedErrorMessage(err)}.`); throw err; diff --git a/src/plugins/telemetry/server/collectors/usage/telemetry_usage_collector.ts b/src/plugins/telemetry/server/collectors/usage/telemetry_usage_collector.ts index c0b26b8f5d2db..6ada0a0e90f69 100644 --- a/src/plugins/telemetry/server/collectors/usage/telemetry_usage_collector.ts +++ b/src/plugins/telemetry/server/collectors/usage/telemetry_usage_collector.ts @@ -8,7 +8,7 @@ */ import { accessSync, constants, readFileSync, statSync } from 'fs'; -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import { dirname, join } from 'path'; import { Observable, firstValueFrom } from 'rxjs'; import { ensureDeepObject } from '@kbn/std'; @@ -55,7 +55,7 @@ export async function readTelemetryFile( try { if (isFileReadable(configPath)) { const yaml = readFileSync(configPath); - const data = safeLoad(yaml.toString()); + const data = load(yaml.toString()); // don't bother returning empty objects if (Object.keys(data).length) { diff --git a/typings/@types/js-yaml/index.d.ts b/typings/@types/js-yaml/index.d.ts new file mode 100644 index 0000000000000..99825f6778378 --- /dev/null +++ b/typings/@types/js-yaml/index.d.ts @@ -0,0 +1,12 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the "Elastic License + * 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side + * Public License v 1"; you may not use this file except in compliance with, at + * your election, the "Elastic License 2.0", the "GNU Affero General Public + * License v3.0 only", or the "Server Side Public License, v 1". + */ + +declare namespace jsyaml { + function load(str: string, opts?: jsyaml.LoadOptions): T; +} diff --git a/x-pack/packages/kbn-data-forge/src/lib/create_config.ts b/x-pack/packages/kbn-data-forge/src/lib/create_config.ts index 1373f20a5dd1f..43e51b2c93438 100644 --- a/x-pack/packages/kbn-data-forge/src/lib/create_config.ts +++ b/x-pack/packages/kbn-data-forge/src/lib/create_config.ts @@ -14,7 +14,7 @@ import { DEFAULTS } from '../constants'; export async function readConfig(filePath: string): Promise { const data = await promises.readFile(filePath); - const decodedPartialConfig = PartialConfigRT.decode(yaml.safeLoad(data.toString())); + const decodedPartialConfig = PartialConfigRT.decode(yaml.load(data.toString())); if (isLeft(decodedPartialConfig)) { throw new Error( `Could not validate config: ${PathReporter.report(decodedPartialConfig).join('\n')}` diff --git a/x-pack/packages/kbn-elastic-assistant-common/docs/openapi/ess/elastic_assistant_api_2023_10_31.bundled.schema.yaml b/x-pack/packages/kbn-elastic-assistant-common/docs/openapi/ess/elastic_assistant_api_2023_10_31.bundled.schema.yaml index c97a55df0729c..dfd9be372b7f0 100644 --- a/x-pack/packages/kbn-elastic-assistant-common/docs/openapi/ess/elastic_assistant_api_2023_10_31.bundled.schema.yaml +++ b/x-pack/packages/kbn-elastic-assistant-common/docs/openapi/ess/elastic_assistant_api_2023_10_31.bundled.schema.yaml @@ -4,7 +4,7 @@ info: title: Security AI Assistant API (Elastic Cloud & self-hosted) version: '2023-10-31' servers: - - url: 'http://{kibana_host}:{port}' + - url: http://{kibana_host}:{port} variables: kibana_host: default: localhost @@ -309,7 +309,7 @@ paths: tags: - Security AI Assistant API - Conversations API - '/api/security_ai_assistant/current_user/conversations/{id}': + /api/security_ai_assistant/current_user/conversations/{id}: delete: description: Delete an existing conversation using the conversation ID. operationId: DeleteConversation @@ -1213,13 +1213,13 @@ components: type: object properties: traceId: - description: 'Could be any string, not necessarily a UUID' + description: Could be any string, not necessarily a UUID type: string transactionId: - description: 'Could be any string, not necessarily a UUID' + description: Could be any string, not necessarily a UUID type: string User: - description: 'Could be any string, not necessarily a UUID' + description: Could be any string, not necessarily a UUID type: object properties: id: diff --git a/x-pack/packages/kbn-elastic-assistant-common/docs/openapi/serverless/elastic_assistant_api_2023_10_31.bundled.schema.yaml b/x-pack/packages/kbn-elastic-assistant-common/docs/openapi/serverless/elastic_assistant_api_2023_10_31.bundled.schema.yaml index d9716189782d4..9c8cc4a8ca21d 100644 --- a/x-pack/packages/kbn-elastic-assistant-common/docs/openapi/serverless/elastic_assistant_api_2023_10_31.bundled.schema.yaml +++ b/x-pack/packages/kbn-elastic-assistant-common/docs/openapi/serverless/elastic_assistant_api_2023_10_31.bundled.schema.yaml @@ -4,7 +4,7 @@ info: title: Security AI Assistant API (Elastic Cloud Serverless) version: '2023-10-31' servers: - - url: 'http://{kibana_host}:{port}' + - url: http://{kibana_host}:{port} variables: kibana_host: default: localhost @@ -309,7 +309,7 @@ paths: tags: - Security AI Assistant API - Conversations API - '/api/security_ai_assistant/current_user/conversations/{id}': + /api/security_ai_assistant/current_user/conversations/{id}: delete: description: Delete an existing conversation using the conversation ID. operationId: DeleteConversation @@ -1213,13 +1213,13 @@ components: type: object properties: traceId: - description: 'Could be any string, not necessarily a UUID' + description: Could be any string, not necessarily a UUID type: string transactionId: - description: 'Could be any string, not necessarily a UUID' + description: Could be any string, not necessarily a UUID type: string User: - description: 'Could be any string, not necessarily a UUID' + description: Could be any string, not necessarily a UUID type: object properties: id: diff --git a/x-pack/plugins/cloud_defend/common/utils/helpers.ts b/x-pack/plugins/cloud_defend/common/utils/helpers.ts index c918c0fe5d9f2..ae1b3a4f3d00c 100644 --- a/x-pack/plugins/cloud_defend/common/utils/helpers.ts +++ b/x-pack/plugins/cloud_defend/common/utils/helpers.ts @@ -48,7 +48,7 @@ export function getSelectorsAndResponsesFromYaml(configuration: string): { let responses: Response[] = []; try { - const result = yaml.safeLoad(configuration); + const result = yaml.load(configuration); if (result) { // iterate selector/response types @@ -107,5 +107,5 @@ export function getYamlFromSelectorsAndResponses(selectors: Selector[], response return current; }, schema); - return yaml.safeDump(schema); + return yaml.dump(schema); } diff --git a/x-pack/plugins/cloud_defend/public/components/control_general_view/index.test.tsx b/x-pack/plugins/cloud_defend/public/components/control_general_view/index.test.tsx index 94cc5d72dcd8f..f0cb2147f450c 100644 --- a/x-pack/plugins/cloud_defend/public/components/control_general_view/index.test.tsx +++ b/x-pack/plugins/cloud_defend/public/components/control_general_view/index.test.tsx @@ -44,7 +44,7 @@ describe('', () => { const configuration = input?.vars?.configuration?.value; try { - const json = yaml.safeLoad(configuration); + const json = yaml.load(configuration); expect(json.file.selectors.length).toBe(getAllByTestId('cloud-defend-selector').length); expect(json.file.responses.length).toBe(getAllByTestId('cloud-defend-file-response').length); @@ -69,7 +69,7 @@ describe('', () => { const configuration = input?.vars?.configuration?.value; try { - const json = yaml.safeLoad(configuration); + const json = yaml.load(configuration); expect(json.file.selectors.length).toBe(getAllByTestId('cloud-defend-selector').length); } catch (err) { @@ -91,7 +91,7 @@ describe('', () => { const configuration = input?.vars?.configuration?.value; try { - const json = yaml.safeLoad(configuration); + const json = yaml.load(configuration); expect(json.file.responses.length).toBe(getAllByTestId('cloud-defend-file-response').length); } catch (err) { @@ -113,7 +113,7 @@ describe('', () => { const configuration = input?.vars?.configuration?.value; try { - const json = yaml.safeLoad(configuration); + const json = yaml.load(configuration); expect(json.process.responses.length).toBe( getAllByTestId('cloud-defend-process-response').length @@ -166,7 +166,7 @@ describe('', () => { const configuration = input?.vars?.configuration?.value; try { - const json = yaml.safeLoad(configuration); + const json = yaml.load(configuration); expect(json.file.responses[0].match).toHaveLength(1); } catch (err) { @@ -205,7 +205,7 @@ describe('', () => { const configuration = input?.vars?.configuration?.value; try { - const json = yaml.safeLoad(configuration); + const json = yaml.load(configuration); expect(json.file.selectors).toHaveLength(4); expect(json.file.selectors[3].name).toEqual(json.file.selectors[0].name + '1'); diff --git a/x-pack/plugins/fleet/common/services/agent_cm_to_yaml.ts b/x-pack/plugins/fleet/common/services/agent_cm_to_yaml.ts index 5987110d7752f..44d4a7b772082 100644 --- a/x-pack/plugins/fleet/common/services/agent_cm_to_yaml.ts +++ b/x-pack/plugins/fleet/common/services/agent_cm_to_yaml.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { safeDump } from 'js-yaml'; +import type { dump } from 'js-yaml'; import type { FullAgentConfigMap } from '../types/models/agent_cm'; @@ -13,7 +13,7 @@ const CM_KEYS_ORDER = ['apiVersion', 'kind', 'metadata', 'data']; export const fullAgentConfigMapToYaml = ( policy: FullAgentConfigMap, - toYaml: typeof safeDump + toYaml: typeof dump ): string => { return toYaml(policy, { skipInvalid: true, diff --git a/x-pack/plugins/fleet/common/services/full_agent_policy_to_yaml.ts b/x-pack/plugins/fleet/common/services/full_agent_policy_to_yaml.ts index 4d464427a998e..f0e21785d5c1e 100644 --- a/x-pack/plugins/fleet/common/services/full_agent_policy_to_yaml.ts +++ b/x-pack/plugins/fleet/common/services/full_agent_policy_to_yaml.ts @@ -5,7 +5,7 @@ * 2.0. */ -import type { safeDump } from 'js-yaml'; +import type { dump } from 'js-yaml'; import type { FullAgentPolicy } from '../types'; @@ -30,7 +30,7 @@ const POLICY_KEYS_ORDER = [ export const fullAgentPolicyToYaml = ( policy: FullAgentPolicy, - toYaml: typeof safeDump, + toYaml: typeof dump, apiKey?: string ): string => { const yaml = toYaml(policy, { diff --git a/x-pack/plugins/fleet/common/services/output_helpers.test.ts b/x-pack/plugins/fleet/common/services/output_helpers.test.ts index cba42f1b6c233..99778c761630e 100644 --- a/x-pack/plugins/fleet/common/services/output_helpers.test.ts +++ b/x-pack/plugins/fleet/common/services/output_helpers.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import { getAllowedOutputTypeForPolicy, @@ -56,13 +56,13 @@ describe('outputYmlIncludesReservedPerformanceKey', () => { it('returns true when reserved key is present', () => { const configYml = `queue.mem.events: 1000`; - expect(outputYmlIncludesReservedPerformanceKey(configYml, safeLoad)).toBe(true); + expect(outputYmlIncludesReservedPerformanceKey(configYml, load)).toBe(true); }); it('returns false when no reserved key is present', () => { const configYml = `some.random.key: 1000`; - expect(outputYmlIncludesReservedPerformanceKey(configYml, safeLoad)).toBe(false); + expect(outputYmlIncludesReservedPerformanceKey(configYml, load)).toBe(false); }); }); @@ -74,7 +74,7 @@ describe('outputYmlIncludesReservedPerformanceKey', () => { events: 1000 `; - expect(outputYmlIncludesReservedPerformanceKey(configYml, safeLoad)).toBe(true); + expect(outputYmlIncludesReservedPerformanceKey(configYml, load)).toBe(true); }); it('returns false when no reserved key is present', () => { @@ -84,7 +84,7 @@ describe('outputYmlIncludesReservedPerformanceKey', () => { key: 1000 `; - expect(outputYmlIncludesReservedPerformanceKey(configYml, safeLoad)).toBe(false); + expect(outputYmlIncludesReservedPerformanceKey(configYml, load)).toBe(false); }); }); @@ -92,13 +92,13 @@ describe('outputYmlIncludesReservedPerformanceKey', () => { it('returns true when reserved key is present', () => { const configYml = `bulk_max_size`; - expect(outputYmlIncludesReservedPerformanceKey(configYml, safeLoad)).toBe(true); + expect(outputYmlIncludesReservedPerformanceKey(configYml, load)).toBe(true); }); it('returns false when no reserved key is present', () => { const configYml = `just a string`; - expect(outputYmlIncludesReservedPerformanceKey(configYml, safeLoad)).toBe(false); + expect(outputYmlIncludesReservedPerformanceKey(configYml, load)).toBe(false); }); }); @@ -106,7 +106,7 @@ describe('outputYmlIncludesReservedPerformanceKey', () => { it('returns false when reserved key is present only in a comment', () => { const configYml = `true`; - expect(outputYmlIncludesReservedPerformanceKey(configYml, safeLoad)).toBe(false); + expect(outputYmlIncludesReservedPerformanceKey(configYml, load)).toBe(false); }); }); @@ -114,7 +114,7 @@ describe('outputYmlIncludesReservedPerformanceKey', () => { it('returns false when YML is empty', () => { const configYml = ``; - expect(outputYmlIncludesReservedPerformanceKey(configYml, safeLoad)).toBe(false); + expect(outputYmlIncludesReservedPerformanceKey(configYml, load)).toBe(false); }); }); }); diff --git a/x-pack/plugins/fleet/common/services/validate_package_policy.test.ts b/x-pack/plugins/fleet/common/services/validate_package_policy.test.ts index 90e20dbae362a..9c663ad577c91 100644 --- a/x-pack/plugins/fleet/common/services/validate_package_policy.test.ts +++ b/x-pack/plugins/fleet/common/services/validate_package_policy.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import { installationStatuses } from '../constants'; import type { PackageInfo, NewPackagePolicy, RegistryPolicyTemplate } from '../types'; @@ -380,13 +380,13 @@ describe('Fleet - validatePackagePolicy()', () => { }; it('returns no errors for valid package policy', () => { - expect(validatePackagePolicy(validPackagePolicy, mockPackage, safeLoad)).toEqual( + expect(validatePackagePolicy(validPackagePolicy, mockPackage, load)).toEqual( noErrorsValidationResults ); }); it('returns errors for invalid package policy', () => { - expect(validatePackagePolicy(invalidPackagePolicy, mockPackage, safeLoad)).toEqual({ + expect(validatePackagePolicy(invalidPackagePolicy, mockPackage, load)).toEqual({ name: ['Name is required'], description: null, namespace: null, @@ -433,11 +433,7 @@ describe('Fleet - validatePackagePolicy()', () => { enabled: false, })); expect( - validatePackagePolicy( - { ...validPackagePolicy, inputs: disabledInputs }, - mockPackage, - safeLoad - ) + validatePackagePolicy({ ...validPackagePolicy, inputs: disabledInputs }, mockPackage, load) ).toEqual(noErrorsValidationResults); }); @@ -454,7 +450,7 @@ describe('Fleet - validatePackagePolicy()', () => { validatePackagePolicy( { ...invalidPackagePolicy, inputs: inputsWithDisabledStreams }, mockPackage, - safeLoad + load ) ).toEqual({ name: ['Name is required'], @@ -507,7 +503,7 @@ describe('Fleet - validatePackagePolicy()', () => { ...mockPackage, policy_templates: undefined, }, - safeLoad + load ) ).toEqual({ name: null, @@ -523,7 +519,7 @@ describe('Fleet - validatePackagePolicy()', () => { ...mockPackage, policy_templates: [], }, - safeLoad + load ) ).toEqual({ name: null, @@ -542,7 +538,7 @@ describe('Fleet - validatePackagePolicy()', () => { ...mockPackage, policy_templates: [{} as RegistryPolicyTemplate], }, - safeLoad + load ) ).toEqual({ name: null, @@ -558,7 +554,7 @@ describe('Fleet - validatePackagePolicy()', () => { ...mockPackage, policy_templates: [{ inputs: [] } as unknown as RegistryPolicyTemplate], }, - safeLoad + load ) ).toEqual({ name: null, @@ -595,7 +591,7 @@ describe('Fleet - validatePackagePolicy()', () => { ], }, mockPackage, - safeLoad + load ) ).toEqual({ name: null, @@ -725,7 +721,7 @@ describe('Fleet - validatePackagePolicy()', () => { }, ], }, - safeLoad + load ) ).toEqual({ description: null, @@ -756,7 +752,7 @@ describe('Fleet - validatePackagePolicy()', () => { validatePackagePolicy( INVALID_AWS_POLICY as NewPackagePolicy, AWS_PACKAGE as unknown as PackageInfo, - safeLoad + load ) ).toMatchSnapshot(); }); @@ -767,7 +763,7 @@ describe('Fleet - validatePackagePolicy()', () => { validatePackagePolicy( VALID_AWS_POLICY as NewPackagePolicy, AWS_PACKAGE as unknown as PackageInfo, - safeLoad + load ) ) ).toBe(false); @@ -888,7 +884,7 @@ describe('Fleet - validatePackagePolicyConfig', () => { type: 'integer', }, 'myvariable', - safeLoad + load ); expect(res).toEqual(['Invalid integer']); @@ -905,7 +901,7 @@ describe('Fleet - validatePackagePolicyConfig', () => { type: 'integer', }, 'myvariable', - safeLoad + load ); expect(res).toBeNull(); @@ -923,7 +919,7 @@ describe('Fleet - validatePackagePolicyConfig', () => { multi: true, }, 'myvariable', - safeLoad + load ); expect(res).toEqual(['Invalid integer']); @@ -941,7 +937,7 @@ describe('Fleet - validatePackagePolicyConfig', () => { multi: true, }, 'myvariable', - safeLoad + load ); expect(res).toBeNull(); @@ -964,7 +960,7 @@ describe('Fleet - validatePackagePolicyConfig', () => { ], }, 'myvariable', - safeLoad + load ); expect(res).toEqual(['Invalid value for select type']); @@ -985,7 +981,7 @@ describe('Fleet - validatePackagePolicyConfig', () => { ], }, 'myvariable', - safeLoad + load ); expect(res).toEqual(['Invalid value for select type']); @@ -1006,7 +1002,7 @@ describe('Fleet - validatePackagePolicyConfig', () => { ], }, 'myvariable', - safeLoad + load ); expect(res).toBeNull(); @@ -1027,7 +1023,7 @@ describe('Fleet - validatePackagePolicyConfig', () => { ], }, 'myvariable', - safeLoad + load ); expect(res).toBeNull(); @@ -1043,7 +1039,7 @@ describe('Fleet - validatePackagePolicyConfig', () => { secret: true, }, 'secret_variable', - safeLoad + load ); expect(res).toBeNull(); @@ -1059,7 +1055,7 @@ describe('Fleet - validatePackagePolicyConfig', () => { secret: true, }, 'secret_variable', - safeLoad + load ); expect(res).toEqual(['Secret reference is invalid, id must be a string']); @@ -1075,7 +1071,7 @@ describe('Fleet - validatePackagePolicyConfig', () => { secret: true, }, 'secret_variable', - safeLoad + load ); expect(res).toEqual(['Secret reference is invalid, id must be a string']); @@ -1096,7 +1092,7 @@ describe('Fleet - validatePackagePolicyConfig', () => { type: 'text', }, 'data_stream.dataset', - safeLoad, + load, 'input' ); }; @@ -1142,7 +1138,7 @@ describe('Fleet - validatePackagePolicyConfig', () => { type: 'text', }, 'data_stream.dataset', - safeLoad, + load, 'input' ); @@ -1160,7 +1156,7 @@ describe('Fleet - validatePackagePolicyConfig', () => { type: 'text', }, 'data_stream.dataset', - safeLoad, + load, 'integration' ); @@ -1178,7 +1174,7 @@ describe('Fleet - validatePackagePolicyConfig', () => { type: 'text', }, 'test_field', - safeLoad, + load, 'input' ); @@ -1196,7 +1192,7 @@ describe('Fleet - validatePackagePolicyConfig', () => { type: 'text', }, 'data_stream.dataset', - safeLoad, + load, 'input' ); @@ -1214,7 +1210,7 @@ describe('Fleet - validatePackagePolicyConfig', () => { type: 'text', }, 'data_stream.dataset', - safeLoad, + load, 'input' ); diff --git a/x-pack/plugins/fleet/cypress/tasks/login.ts b/x-pack/plugins/fleet/cypress/tasks/login.ts index 1e50fff48bb90..0a1b20b186764 100644 --- a/x-pack/plugins/fleet/cypress/tasks/login.ts +++ b/x-pack/plugins/fleet/cypress/tasks/login.ts @@ -244,7 +244,7 @@ const loginViaConfig = () => { // read the login details from `kibana.dev.yaml` cy.readFile(KIBANA_DEV_YML_PATH).then((kibanaDevYml) => { - const config = yaml.safeLoad(kibanaDevYml); + const config = yaml.load(kibanaDevYml); // programmatically authenticate without interacting with the Kibana login page request({ @@ -278,7 +278,7 @@ export const getEnvAuth = (): User => { } else { let user: User = { username: '', password: '' }; cy.readFile(KIBANA_DEV_YML_PATH).then((devYml) => { - const config = yaml.safeLoad(devYml); + const config = yaml.load(devYml); user = { username: config.elasticsearch.username, password: config.elasticsearch.password }; }); diff --git a/x-pack/plugins/fleet/cypress/tsconfig.json b/x-pack/plugins/fleet/cypress/tsconfig.json index 28fe4b5114243..ee3dd7cd1e246 100644 --- a/x-pack/plugins/fleet/cypress/tsconfig.json +++ b/x-pack/plugins/fleet/cypress/tsconfig.json @@ -2,7 +2,8 @@ "extends": "../../../../tsconfig.base.json", "include": [ "**/*", - "../cypress.config.ts" + "../cypress.config.ts", + "../../../../typings/**/*" ], "exclude": [ "target/**/*" diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/components/agent_policy_yaml_flyout.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/components/agent_policy_yaml_flyout.tsx index 9a9bcc1de3cdd..4917ecf43e6a3 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/components/agent_policy_yaml_flyout.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/components/agent_policy_yaml_flyout.tsx @@ -8,7 +8,7 @@ import React, { memo } from 'react'; import styled from 'styled-components'; import { FormattedMessage } from '@kbn/i18n-react'; -import { safeDump } from 'js-yaml'; +import { dump } from 'js-yaml'; import { EuiCodeBlock, EuiFlexGroup, @@ -62,7 +62,7 @@ export const AgentPolicyYamlFlyout = memo<{ policyId: string; onClose: () => voi ) : ( <> - {fullAgentPolicyToYaml(yamlData!.item, safeDump)} + {fullAgentPolicyToYaml(yamlData!.item, dump)} ); diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/steps/step_configure_package.test.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/steps/step_configure_package.test.tsx index 19032a96f7c83..7ec72369f338e 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/steps/step_configure_package.test.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/components/steps/step_configure_package.test.tsx @@ -7,7 +7,7 @@ import React from 'react'; import { act, fireEvent, waitFor } from '@testing-library/react'; -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import type { TestRenderer } from '../../../../../../../mock'; import { createFleetTestRendererMock } from '../../../../../../../mock'; @@ -30,7 +30,7 @@ describe('StepConfigurePackage', () => { let testRenderer: TestRenderer; let renderResult: ReturnType; const render = () => { - const validationResults = validatePackagePolicy(packagePolicy, packageInfo, safeLoad); + const validationResults = validatePackagePolicy(packagePolicy, packageInfo, load); renderResult = testRenderer.render( = (props const newValidationResult = validatePackagePolicy( { ...packagePolicy, ...newPackagePolicy }, packageInfo, - safeLoad + load ); setValidationResults(newValidationResult); // eslint-disable-next-line no-console diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/services/has_invalid_but_required_var.ts b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/services/has_invalid_but_required_var.ts index 2d339013f5033..ac9a470a2d87e 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/services/has_invalid_but_required_var.ts +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/services/has_invalid_but_required_var.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import type { PackagePolicyConfigRecord, RegistryVarsEntry } from '../../../../types'; @@ -28,7 +28,7 @@ export const hasInvalidButRequiredVar = ( packagePolicyVars[registryVar.name], registryVar, registryVar.name, - safeLoad + load )?.length) ) ) diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/single_page_layout/hooks/form.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/single_page_layout/hooks/form.tsx index f624bd5c843af..ca96066facba3 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/single_page_layout/hooks/form.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/create_package_policy_page/single_page_layout/hooks/form.tsx @@ -7,7 +7,7 @@ import { useCallback, useEffect, useRef, useState } from 'react'; import { i18n } from '@kbn/i18n'; -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import { isEqual } from 'lodash'; @@ -205,7 +205,7 @@ export function useOnSubmit({ const newValidationResult = validatePackagePolicy( newPackagePolicy || packagePolicy, packageInfo, - safeLoad, + load, spaceSettings ); setValidationResults(newValidationResult); diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/edit_package_policy_page/hooks/use_package_policy.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/edit_package_policy_page/hooks/use_package_policy.tsx index ec2771df920cd..b97895e9fea55 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/edit_package_policy_page/hooks/use_package_policy.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/agent_policy/edit_package_policy_page/hooks/use_package_policy.tsx @@ -6,7 +6,7 @@ */ import { useCallback, useEffect, useState } from 'react'; -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import deepEqual from 'fast-deep-equal'; import { pick } from 'lodash'; @@ -115,7 +115,7 @@ export function usePackagePolicyWithRelatedData( const newValidationResult = validatePackagePolicy( newPackagePolicy || packagePolicy, packageInfo, - safeLoad + load ); setValidationResults(newValidationResult); // eslint-disable-next-line no-console @@ -314,7 +314,7 @@ export function usePackagePolicyWithRelatedData( const newValidationResults = validatePackagePolicy( newPackagePolicy, packageData.item, - safeLoad + load ); setValidationResults(newValidationResults); diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/settings/components/edit_fleet_proxy_flyout/use_fleet_proxy_form.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/settings/components/edit_fleet_proxy_flyout/use_fleet_proxy_form.tsx index 2d8a5b4aa1952..009b99de27a01 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/settings/components/edit_fleet_proxy_flyout/use_fleet_proxy_form.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/settings/components/edit_fleet_proxy_flyout/use_fleet_proxy_form.tsx @@ -8,7 +8,7 @@ import React, { useCallback, useState, useMemo } from 'react'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n-react'; -import { safeDump, safeLoad } from 'js-yaml'; +import { dump, load } from 'js-yaml'; import { sendPostFleetProxy, @@ -57,7 +57,7 @@ function validateUrl(value: string) { function validateProxyHeaders(value: string) { if (value && value !== '') { - const res = safeLoad(value); + const res = load(value); if ( typeof res !== 'object' || Object.values(res).some((val) => { @@ -94,7 +94,7 @@ export function useFleetProxyForm(fleetProxy: FleetProxy | undefined, onSuccess: const nameInput = useInput(fleetProxy?.name ?? '', validateName, isEditDisabled); const urlInput = useInput(fleetProxy?.url ?? '', validateUrl, isEditDisabled); const proxyHeadersInput = useInput( - fleetProxy?.proxy_headers ? safeDump(fleetProxy.proxy_headers) : '', + fleetProxy?.proxy_headers ? dump(fleetProxy.proxy_headers) : '', validateProxyHeaders, isEditDisabled ); @@ -143,8 +143,7 @@ export function useFleetProxyForm(fleetProxy: FleetProxy | undefined, onSuccess: const data = { name: nameInput.value, url: urlInput.value, - proxy_headers: - proxyHeadersInput.value === '' ? undefined : safeLoad(proxyHeadersInput.value), + proxy_headers: proxyHeadersInput.value === '' ? undefined : load(proxyHeadersInput.value), certificate_authorities: certificateAuthoritiesInput.value, certificate: certificateInput.value, certificate_key: certificateKeyInput.value, diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/settings/components/edit_output_flyout/index.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/settings/components/edit_output_flyout/index.tsx index d074454b0fe14..ee219efc0dae8 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/settings/components/edit_output_flyout/index.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/settings/components/edit_output_flyout/index.tsx @@ -7,7 +7,7 @@ import React, { useMemo, useState } from 'react'; import { FormattedMessage } from '@kbn/i18n-react'; -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import { EuiFlyout, @@ -440,7 +440,7 @@ export const EditOutputFlyout: React.FunctionComponent = inputs.presetInput.props.disabled || outputYmlIncludesReservedPerformanceKey( inputs.additionalYamlConfigInput.value, - safeLoad + load ) } options={[ @@ -457,7 +457,7 @@ export const EditOutputFlyout: React.FunctionComponent = {supportsPresets && outputYmlIncludesReservedPerformanceKey( inputs.additionalYamlConfigInput.value, - safeLoad + load ) && ( <> @@ -508,7 +508,7 @@ export const EditOutputFlyout: React.FunctionComponent = { - if (outputYmlIncludesReservedPerformanceKey(value, safeLoad)) { + if (outputYmlIncludesReservedPerformanceKey(value, load)) { inputs.presetInput.setValue('custom'); } diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/settings/components/edit_output_flyout/output_form_validators.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/settings/components/edit_output_flyout/output_form_validators.tsx index 3abd14373ece8..5e3bf5b3725e9 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/settings/components/edit_output_flyout/output_form_validators.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/settings/components/edit_output_flyout/output_form_validators.tsx @@ -6,8 +6,8 @@ */ import { i18n } from '@kbn/i18n'; -import { safeLoad } from 'js-yaml'; import type { EuiComboBoxOptionOption } from '@elastic/eui'; +import { load } from 'js-yaml'; const toSecretValidator = (validator: (value: string) => string[] | undefined) => @@ -219,7 +219,7 @@ export function validateLogstashHosts(value: string[]) { export function validateYamlConfig(value: string) { try { - safeLoad(value); + load(value); return; } catch (error) { return [ diff --git a/x-pack/plugins/fleet/public/applications/fleet/sections/settings/components/edit_output_flyout/use_output_form.tsx b/x-pack/plugins/fleet/public/applications/fleet/sections/settings/components/edit_output_flyout/use_output_form.tsx index 4e154212417dd..78aac64e12830 100644 --- a/x-pack/plugins/fleet/public/applications/fleet/sections/settings/components/edit_output_flyout/use_output_form.tsx +++ b/x-pack/plugins/fleet/public/applications/fleet/sections/settings/components/edit_output_flyout/use_output_form.tsx @@ -8,7 +8,7 @@ import { useCallback, useState } from 'react'; import { i18n } from '@kbn/i18n'; -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import type { EuiComboBoxOptionOption } from '@elastic/eui'; @@ -262,7 +262,7 @@ export function useOutputForm(onSucess: () => void, output?: Output, defaultOupu ); const presetInput = useInput( - output?.preset ?? getDefaultPresetForEsOutput(output?.config_yaml ?? '', safeLoad), + output?.preset ?? getDefaultPresetForEsOutput(output?.config_yaml ?? '', load), () => undefined, isDisabled('preset') ); @@ -297,7 +297,7 @@ export function useOutputForm(onSucess: () => void, output?: Output, defaultOupu shipper: enabled: false */ - const configJs = output?.config_yaml ? safeLoad(output?.config_yaml) : {}; + const configJs = output?.config_yaml ? load(output?.config_yaml) : {}; const isShipperDisabled = !configJs?.shipper || configJs?.shipper?.enabled === false; const diskQueueEnabledInput = useSwitchInput(output?.shipper?.disk_queue_enabled ?? false); diff --git a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/utils/changelog_utils.ts b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/utils/changelog_utils.ts index 7860704bb208a..70dcd48e3c6f6 100644 --- a/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/utils/changelog_utils.ts +++ b/x-pack/plugins/fleet/public/applications/integrations/sections/epm/screens/detail/utils/changelog_utils.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import semverGte from 'semver/functions/gte'; import semverLte from 'semver/functions/lte'; @@ -26,7 +26,7 @@ export const filterYamlChangelog = ( latestVersion: string, currentVersion?: string ) => { - const parsedChangelog: ChangeLogParams[] = changelogText ? safeLoad(changelogText) : []; + const parsedChangelog: ChangeLogParams[] = changelogText ? load(changelogText) : []; if (!currentVersion) return parsedChangelog.filter((e) => semverLte(e.version, latestVersion)); diff --git a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/hooks.tsx b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/hooks.tsx index e6ecfbdfbd944..ff2d9ed266a20 100644 --- a/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/hooks.tsx +++ b/x-pack/plugins/fleet/public/components/agent_enrollment_flyout/hooks.tsx @@ -9,7 +9,7 @@ import crypto from 'crypto'; import { useState, useEffect, useMemo, useCallback } from 'react'; import { i18n } from '@kbn/i18n'; -import { safeDump } from 'js-yaml'; +import { dump } from 'js-yaml'; import type { PackagePolicy, AgentPolicy } from '../../types'; import { @@ -289,7 +289,7 @@ export function useFetchFullPolicy(agentPolicy: AgentPolicy | undefined, isK8s?: if (typeof fullAgentPolicy === 'string') { return; } - setYaml(fullAgentPolicyToYaml(fullAgentPolicy, safeDump, apiKey)); + setYaml(fullAgentPolicyToYaml(fullAgentPolicy, dump, apiKey)); } }, [apiKey, fullAgentPolicy, isK8s]); diff --git a/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts b/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts index a86c627688207..73a635edf7699 100644 --- a/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts +++ b/x-pack/plugins/fleet/server/routes/agent_policy/handlers.ts @@ -8,7 +8,7 @@ import type { TypeOf } from '@kbn/config-schema'; import type { KibanaRequest, RequestHandler, ResponseHeaders } from '@kbn/core/server'; import pMap from 'p-map'; -import { safeDump } from 'js-yaml'; +import { dump } from 'js-yaml'; import { isEmpty } from 'lodash'; @@ -590,7 +590,7 @@ export const downloadFullAgentPolicy: FleetRequestHandler< standalone: request.query.standalone === true, }); if (fullAgentPolicy) { - const body = fullAgentPolicyToYaml(fullAgentPolicy, safeDump); + const body = fullAgentPolicyToYaml(fullAgentPolicy, dump); const headers: ResponseHeaders = { 'content-type': 'text/x-yaml', 'content-disposition': `attachment; filename="elastic-agent.yml"`, diff --git a/x-pack/plugins/fleet/server/services/agent_policies/full_agent_policy.ts b/x-pack/plugins/fleet/server/services/agent_policies/full_agent_policy.ts index d00721f08a3d9..d5216b28991c6 100644 --- a/x-pack/plugins/fleet/server/services/agent_policies/full_agent_policy.ts +++ b/x-pack/plugins/fleet/server/services/agent_policies/full_agent_policy.ts @@ -8,7 +8,7 @@ /* eslint-disable @typescript-eslint/naming-convention */ import type { SavedObjectsClientContract } from '@kbn/core/server'; -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import deepMerge from 'deepmerge'; import { set } from '@kbn/safer-lodash-set'; @@ -393,7 +393,7 @@ export function transformOutputToFullPolicyOutput( preset, } = output; - const configJs = config_yaml ? safeLoad(config_yaml) : {}; + const configJs = config_yaml ? load(config_yaml) : {}; // build logic to read config_yaml and transform it with the new shipper data const isShipperDisabled = !configJs?.shipper || configJs?.shipper?.enabled === false; @@ -544,7 +544,7 @@ export function transformOutputToFullPolicyOutput( } if (outputTypeSupportPresets(output.type)) { - newOutput.preset = preset ?? getDefaultPresetForEsOutput(config_yaml ?? '', safeLoad); + newOutput.preset = preset ?? getDefaultPresetForEsOutput(config_yaml ?? '', load); } return newOutput; diff --git a/x-pack/plugins/fleet/server/services/agent_policy.ts b/x-pack/plugins/fleet/server/services/agent_policy.ts index 999448f7cae47..c4fe6c4604a6e 100644 --- a/x-pack/plugins/fleet/server/services/agent_policy.ts +++ b/x-pack/plugins/fleet/server/services/agent_policy.ts @@ -7,7 +7,7 @@ import { chunk, groupBy, isEqual, keyBy, omit, pick } from 'lodash'; import { v5 as uuidv5 } from 'uuid'; -import { safeDump } from 'js-yaml'; +import { dump } from 'js-yaml'; import pMap from 'p-map'; import { lt } from 'semver'; import type { @@ -1427,7 +1427,7 @@ class AgentPolicyService { }, }; - const configMapYaml = fullAgentConfigMapToYaml(fullAgentConfigMap, safeDump); + const configMapYaml = fullAgentConfigMapToYaml(fullAgentConfigMap, dump); const updateManifestVersion = elasticAgentStandaloneManifest.replace('VERSION', agentVersion); const fixedAgentYML = configMapYaml.replace('agent.yml:', 'agent.yml: |-'); return [fixedAgentYML, updateManifestVersion].join('\n'); diff --git a/x-pack/plugins/fleet/server/services/epm/agent/agent.ts b/x-pack/plugins/fleet/server/services/epm/agent/agent.ts index f1187e3629c0b..29d6c3c18fc56 100644 --- a/x-pack/plugins/fleet/server/services/epm/agent/agent.ts +++ b/x-pack/plugins/fleet/server/services/epm/agent/agent.ts @@ -6,7 +6,7 @@ */ import Handlebars from 'handlebars'; -import { safeLoad, safeDump } from 'js-yaml'; +import { load, dump } from 'js-yaml'; import type { Logger } from '@kbn/core/server'; import type { PackagePolicyConfigRecord } from '../../../../common/types'; @@ -28,10 +28,10 @@ export function compileTemplate(variables: PackagePolicyConfigRecord, templateSt } compiledTemplate = replaceRootLevelYamlVariables(yamlValues, compiledTemplate); - const yamlFromCompiledTemplate = safeLoad(compiledTemplate, {}); + const yamlFromCompiledTemplate = load(compiledTemplate, {}); // Hack to keep empty string ('') values around in the end yaml because - // `safeLoad` replaces empty strings with null + // `load` replaces empty strings with null const patchedYamlFromCompiledTemplate = Object.entries(yamlFromCompiledTemplate).reduce( (acc, [key, value]) => { if (value === null && typeof vars[key] === 'string' && vars[key].trim() === '') { @@ -98,7 +98,7 @@ function buildTemplateVariables(logger: Logger, variables: PackagePolicyConfigRe if (recordEntry.type && recordEntry.type === 'yaml') { const yamlKeyPlaceholder = `##${key}##`; varPart[lastKeyPart] = recordEntry.value ? `"${yamlKeyPlaceholder}"` : null; - yamlValues[yamlKeyPlaceholder] = recordEntry.value ? safeLoad(recordEntry.value) : null; + yamlValues[yamlKeyPlaceholder] = recordEntry.value ? load(recordEntry.value) : null; } else if (recordEntry.value && recordEntry.value.isSecretRef) { varPart[lastKeyPart] = toCompiledSecretRef(recordEntry.value.id); } else { @@ -165,7 +165,7 @@ function replaceRootLevelYamlVariables(yamlVariables: { [k: string]: any }, yaml let patchedTemplate = yamlTemplate; Object.entries(yamlVariables).forEach(([key, val]) => { patchedTemplate = patchedTemplate.replace(new RegExp(`^"${key}"`, 'gm'), () => - val ? safeDump(val) : '' + val ? dump(val) : '' ); }); diff --git a/x-pack/plugins/fleet/server/services/epm/archive/parse.ts b/x-pack/plugins/fleet/server/services/epm/archive/parse.ts index 7baa071ed47f7..634169872f660 100644 --- a/x-pack/plugins/fleet/server/services/epm/archive/parse.ts +++ b/x-pack/plugins/fleet/server/services/epm/archive/parse.ts @@ -231,7 +231,7 @@ export function parseAndVerifyArchive( let manifest: ArchivePackage; try { logger.debug(`Verifying archive - loading yaml`); - manifest = yaml.safeLoad(manifestBuffer.toString()); + manifest = yaml.load(manifestBuffer.toString()); } catch (error) { throw new PackageInvalidArchiveError( `Could not parse top-level package manifest at top-level directory ${toplevelDir}: ${error}.` @@ -311,7 +311,7 @@ export function parseAndVerifyArchive( if (paths.includes(tagsFile) || tagsBuffer) { let tags: PackageSpecTags[]; try { - tags = yaml.safeLoad(tagsBuffer.toString()); + tags = yaml.load(tagsBuffer.toString()); logger.debug(`Parsing archive - parsing kibana/tags.yml file`); if (tags.length) { parsed.asset_tags = tags; @@ -369,7 +369,7 @@ export function parseAndVerifyDataStreams(opts: { let manifest; try { - manifest = yaml.safeLoad(manifestBuffer.toString()); + manifest = yaml.load(manifestBuffer.toString()); } catch (error) { throw new PackageInvalidArchiveError( `Could not parse package manifest for data stream '${dataStreamPath}': ${error}.` @@ -382,7 +382,7 @@ export function parseAndVerifyDataStreams(opts: { let dataStreamRoutingRules: RegistryDataStreamRoutingRules[] | undefined; if (routingRulesBuffer) { try { - dataStreamRoutingRules = yaml.safeLoad(routingRulesBuffer.toString()); + dataStreamRoutingRules = yaml.load(routingRulesBuffer.toString()); } catch (error) { throw new PackageInvalidArchiveError( `Could not parse routing rules for data stream '${dataStreamPath}': ${error}.` @@ -395,7 +395,7 @@ export function parseAndVerifyDataStreams(opts: { let dataStreamLifecyle: RegistryDataStreamLifecycle | undefined; if (lifecyleBuffer) { try { - dataStreamLifecyle = yaml.safeLoad(lifecyleBuffer.toString()); + dataStreamLifecyle = yaml.load(lifecyleBuffer.toString()); } catch (error) { throw new PackageInvalidArchiveError( `Could not parse lifecycle for data stream '${dataStreamPath}': ${error}.` diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/ingest_pipeline/helpers.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/ingest_pipeline/helpers.ts index 5ab17d690616e..8956f40d261fb 100644 --- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/ingest_pipeline/helpers.ts +++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/ingest_pipeline/helpers.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { safeDump, safeLoad } from 'js-yaml'; +import { dump, load } from 'js-yaml'; import { ElasticsearchAssetType } from '../../../../types'; import type { RegistryDataStream } from '../../../../types'; @@ -127,7 +127,7 @@ export function addCustomPipelineAndLocalRoutingRulesProcessor( })); if (pipeline.extension === 'yml') { - const parsedPipelineContent = safeLoad(pipeline.contentForInstallation); + const parsedPipelineContent = load(pipeline.contentForInstallation); customPipelineProcessors.forEach((processor) => mutatePipelineContentWithNewProcessor(parsedPipelineContent, processor) ); @@ -136,7 +136,7 @@ export function addCustomPipelineAndLocalRoutingRulesProcessor( ); return { ...pipeline, - contentForInstallation: `---\n${safeDump(parsedPipelineContent)}`, + contentForInstallation: `---\n${dump(parsedPipelineContent)}`, }; } diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/meta.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/meta.ts index 0801de321f2b3..6692c3637b62d 100644 --- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/meta.ts +++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/meta.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { safeLoad, safeDump } from 'js-yaml'; +import { load, dump } from 'js-yaml'; import type { ESAssetMetadata } from '../../../../common/types'; @@ -44,12 +44,12 @@ export function appendMetadataToIngestPipeline({ if (pipeline.extension === 'yml') { // Convert the YML content to JSON, append the `_meta` value, then convert it back to // YML and return the resulting YML - const parsedPipelineContent = safeLoad(pipeline.contentForInstallation); + const parsedPipelineContent = load(pipeline.contentForInstallation); parsedPipelineContent._meta = meta; return { ...pipeline, - contentForInstallation: `---\n${safeDump(parsedPipelineContent)}`, + contentForInstallation: `---\n${dump(parsedPipelineContent)}`, }; } diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/template.test.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/template.test.ts index 371ea4a470eaf..c7d2e4eacb32a 100644 --- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/template.test.ts +++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/template/template.test.ts @@ -8,7 +8,7 @@ import { readFileSync } from 'fs'; import path from 'path'; -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import { loggerMock } from '@kbn/logging-mocks'; import { elasticsearchServiceMock } from '@kbn/core/server/mocks'; @@ -265,7 +265,7 @@ describe('EPM template', () => { it('tests loading base.yml', () => { const ymlPath = path.join(__dirname, '../../fields/tests/base.yml'); const fieldsYML = readFileSync(ymlPath, 'utf-8'); - const fields: Field[] = safeLoad(fieldsYML); + const fields: Field[] = load(fieldsYML); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); @@ -276,7 +276,7 @@ describe('EPM template', () => { it('tests loading coredns.logs.yml', () => { const ymlPath = path.join(__dirname, '../../fields/tests/coredns.logs.yml'); const fieldsYML = readFileSync(ymlPath, 'utf-8'); - const fields: Field[] = safeLoad(fieldsYML); + const fields: Field[] = load(fieldsYML); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); @@ -287,7 +287,7 @@ describe('EPM template', () => { it('tests loading system.yml', () => { const ymlPath = path.join(__dirname, '../../fields/tests/system.yml'); const fieldsYML = readFileSync(ymlPath, 'utf-8'); - const fields: Field[] = safeLoad(fieldsYML); + const fields: Field[] = load(fieldsYML); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); @@ -298,7 +298,7 @@ describe('EPM template', () => { it('tests loading cockroachdb_dynamic_templates.yml', () => { const ymlPath = path.join(__dirname, '../../fields/tests/cockroachdb_dynamic_templates.yml'); const fieldsYML = readFileSync(ymlPath, 'utf-8'); - const fields: Field[] = safeLoad(fieldsYML); + const fields: Field[] = load(fieldsYML); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); @@ -320,7 +320,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(longWithIndexFalseYml); + const fields: Field[] = load(longWithIndexFalseYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(longWithIndexFalseMapping); @@ -340,7 +340,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(keywordWithIndexFalseYml); + const fields: Field[] = load(keywordWithIndexFalseYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(keywordWithIndexFalseMapping); @@ -360,7 +360,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(textWithStoreTrueYml); + const fields: Field[] = load(textWithStoreTrueYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(textWithStoreTrueMapping); @@ -392,7 +392,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(textWithMultiFieldsLiteralYml); + const fields: Field[] = load(textWithMultiFieldsLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(textWithMultiFieldsMapping); @@ -426,7 +426,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(keywordWithMultiFieldsLiteralYml); + const fields: Field[] = load(keywordWithMultiFieldsLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(keywordWithMultiFieldsMapping); @@ -458,7 +458,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(keywordWithAnalyzedMultiFieldsLiteralYml); + const fields: Field[] = load(keywordWithAnalyzedMultiFieldsLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(keywordWithAnalyzedMultiFieldsMapping); @@ -489,7 +489,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(keywordWithNormalizedMultiFieldsLiteralYml); + const fields: Field[] = load(keywordWithNormalizedMultiFieldsLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(keywordWithNormalizedMultiFieldsMapping); @@ -518,7 +518,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(keywordWithMultiFieldsLiteralYml); + const fields: Field[] = load(keywordWithMultiFieldsLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(keywordWithMultiFieldsMapping); @@ -547,7 +547,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(keywordWithMultiFieldsLiteralYml); + const fields: Field[] = load(keywordWithMultiFieldsLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(keywordWithMultiFieldsMapping); @@ -568,7 +568,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(dateWithFormatYml); + const fields: Field[] = load(dateWithFormatYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(dateWithMapping); @@ -602,7 +602,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(keywordWithMultiFieldsLiteralYml); + const fields: Field[] = load(keywordWithMultiFieldsLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(keywordWithMultiFieldsMapping); @@ -630,7 +630,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(wildcardWithMultiFieldsLiteralYml); + const fields: Field[] = load(wildcardWithMultiFieldsLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(wildcardWithMultiFieldsMapping); @@ -648,7 +648,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(objectFieldLiteralYml); + const fields: Field[] = load(objectFieldLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(objectFieldMapping); @@ -668,7 +668,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(objectFieldEnabledFalseLiteralYml); + const fields: Field[] = load(objectFieldEnabledFalseLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(objectFieldEnabledFalseMapping); @@ -688,7 +688,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(objectFieldDynamicFalseLiteralYml); + const fields: Field[] = load(objectFieldDynamicFalseLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(objectFieldDynamicFalseMapping); @@ -708,7 +708,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(objectFieldDynamicTrueLiteralYml); + const fields: Field[] = load(objectFieldDynamicTrueLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(objectFieldDynamicTrueMapping); @@ -728,7 +728,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(objectFieldDynamicStrictLiteralYml); + const fields: Field[] = load(objectFieldDynamicStrictLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(objectFieldDynamicStrictMapping); @@ -753,7 +753,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(objectFieldWithPropertyLiteralYml); + const fields: Field[] = load(objectFieldWithPropertyLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(objectFieldWithPropertyMapping); @@ -780,7 +780,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(objectFieldWithPropertyReversedLiteralYml); + const fields: Field[] = load(objectFieldWithPropertyReversedLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(objectFieldWithPropertyReversedMapping); @@ -819,7 +819,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(objectFieldWithPropertyReversedLiteralYml); + const fields: Field[] = load(objectFieldWithPropertyReversedLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(objectFieldWithPropertyReversedMapping); @@ -858,7 +858,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(objectFieldWithPropertyReversedLiteralYml); + const fields: Field[] = load(objectFieldWithPropertyReversedLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(objectFieldWithPropertyReversedMapping); @@ -886,7 +886,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(nestedYaml); + const fields: Field[] = load(nestedYaml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(expectedMapping); @@ -914,7 +914,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(nestedYaml); + const fields: Field[] = load(nestedYaml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(expectedMapping); @@ -949,7 +949,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(nestedYaml); + const fields: Field[] = load(nestedYaml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(expectedMapping); @@ -978,7 +978,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(nestedYaml); + const fields: Field[] = load(nestedYaml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(expectedMapping); @@ -1014,7 +1014,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(nestedYaml); + const fields: Field[] = load(nestedYaml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(expectedMapping); @@ -1042,7 +1042,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(nestedYaml); + const fields: Field[] = load(nestedYaml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(expectedMapping); @@ -1060,7 +1060,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(constantKeywordLiteralYaml); + const fields: Field[] = load(constantKeywordLiteralYaml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(JSON.stringify(mappings)).toEqual(JSON.stringify(constantKeywordMapping)); @@ -1080,7 +1080,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(constantKeywordLiteralYaml); + const fields: Field[] = load(constantKeywordLiteralYaml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(JSON.stringify(mappings)).toEqual(JSON.stringify(constantKeywordMapping)); @@ -1104,7 +1104,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(literalYml); + const fields: Field[] = load(literalYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields, true); expect(mappings).toEqual(expectedMapping); @@ -1127,7 +1127,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(literalYml); + const fields: Field[] = load(literalYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields, false); expect(mappings).toEqual(expectedMapping); @@ -1151,7 +1151,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(literalYml); + const fields: Field[] = load(literalYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields, true); expect(mappings).toEqual(expectedMapping); @@ -1185,7 +1185,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(literalYml); + const fields: Field[] = load(literalYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields, true); expect(mappings).toEqual(expectedMapping); @@ -1218,7 +1218,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(literalYml); + const fields: Field[] = load(literalYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields, false); expect(mappings).toEqual(expectedMapping); @@ -1245,7 +1245,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(literalYml); + const fields: Field[] = load(literalYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields, true); expect(mappings).toEqual(expectedMapping); @@ -1267,7 +1267,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(metaFieldLiteralYaml); + const fields: Field[] = load(metaFieldLiteralYaml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(JSON.stringify(mappings)).toEqual(JSON.stringify(metaFieldMapping)); @@ -1306,7 +1306,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(metaFieldLiteralYaml); + const fields: Field[] = load(metaFieldLiteralYaml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(JSON.stringify(mappings)).toEqual(JSON.stringify(metaFieldMapping)); @@ -1328,7 +1328,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(fieldLiteralYaml); + const fields: Field[] = load(fieldLiteralYaml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(JSON.stringify(mappings)).toEqual(JSON.stringify(fieldMapping)); @@ -1348,7 +1348,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(textWithRuntimeFieldsLiteralYml); + const fields: Field[] = load(textWithRuntimeFieldsLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(runtimeFieldMapping); @@ -1373,7 +1373,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(textWithRuntimeFieldsLiteralYml); + const fields: Field[] = load(textWithRuntimeFieldsLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(runtimeFieldMapping); @@ -1403,7 +1403,7 @@ describe('EPM template', () => { }, }, }; - const fields: Field[] = safeLoad(textWithRuntimeFieldsLiteralYml); + const fields: Field[] = load(textWithRuntimeFieldsLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(runtimeFieldMapping); @@ -1434,7 +1434,7 @@ describe('EPM template', () => { }, ], }; - const fields: Field[] = safeLoad(textWithRuntimeFieldsLiteralYml); + const fields: Field[] = load(textWithRuntimeFieldsLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(runtimeFieldMapping); @@ -1466,7 +1466,7 @@ describe('EPM template', () => { }, ], }; - const fields: Field[] = safeLoad(textWithRuntimeFieldsLiteralYml); + const fields: Field[] = load(textWithRuntimeFieldsLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(runtimeFieldMapping); @@ -1499,7 +1499,7 @@ describe('EPM template', () => { }, ], }; - const fields: Field[] = safeLoad(textWithRuntimeFieldsLiteralYml); + const fields: Field[] = load(textWithRuntimeFieldsLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields, true); expect(mappings).toEqual(runtimeFieldMapping); @@ -1531,7 +1531,7 @@ describe('EPM template', () => { }, ], }; - const fields: Field[] = safeLoad(textWithRuntimeFieldsLiteralYml); + const fields: Field[] = load(textWithRuntimeFieldsLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields, true); expect(mappings).toEqual(runtimeFieldMapping); @@ -1563,7 +1563,7 @@ describe('EPM template', () => { }, ], }; - const fields: Field[] = safeLoad(textWithRuntimeFieldsLiteralYml); + const fields: Field[] = load(textWithRuntimeFieldsLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(runtimeFieldMapping); @@ -1597,7 +1597,7 @@ describe('EPM template', () => { }, ], }; - const fields: Field[] = safeLoad(textWithRuntimeFieldsLiteralYml); + const fields: Field[] = load(textWithRuntimeFieldsLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields); expect(mappings).toEqual(runtimeFieldMapping); @@ -1652,7 +1652,7 @@ describe('EPM template', () => { }, ], }; - const fields: Field[] = safeLoad(textWithRuntimeFieldsLiteralYml); + const fields: Field[] = load(textWithRuntimeFieldsLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields, true); expect(mappings).toEqual(runtimeFieldMapping); @@ -1709,7 +1709,7 @@ describe('EPM template', () => { }, ], }; - const fields: Field[] = safeLoad(textWithRuntimeFieldsLiteralYml); + const fields: Field[] = load(textWithRuntimeFieldsLiteralYml); const processedFields = processFields(fields); const mappings = generateMappings(processedFields, true); expect(mappings).toEqual(runtimeFieldMapping); @@ -1721,7 +1721,7 @@ describe('EPM template', () => { type: object object_type: constant_keyword `; - const fields: Field[] = safeLoad(textWithRuntimeFieldsLiteralYml); + const fields: Field[] = load(textWithRuntimeFieldsLiteralYml); expect(() => { const processedFields = processFields(fields); generateMappings(processedFields); diff --git a/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/install.ts b/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/install.ts index c7472c268e29c..cbdde6feee64c 100644 --- a/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/install.ts +++ b/x-pack/plugins/fleet/server/services/epm/elasticsearch/transform/install.ts @@ -7,7 +7,7 @@ import type { ElasticsearchClient, Logger, SavedObjectsClientContract } from '@kbn/core/server'; import { errors } from '@elastic/elasticsearch'; -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import { isPopulatedObject } from '@kbn/ml-is-populated-object'; import { uniqBy } from 'lodash'; @@ -179,7 +179,7 @@ const processTransformAssetsPerModule = ( } const packageAssets = transformsSpecifications.get(transformModuleId); - const content = safeLoad(getAssetFromAssetsMap(assetsMap, path).toString('utf-8')); + const content = load(getAssetFromAssetsMap(assetsMap, path).toString('utf-8')); // Handling fields.yml and all other files within 'fields' folder if (fileName === TRANSFORM_SPECS_TYPES.FIELDS || isFields(path)) { diff --git a/x-pack/plugins/fleet/server/services/epm/fields/field.test.ts b/x-pack/plugins/fleet/server/services/epm/fields/field.test.ts index df3a4408232c6..9381403f3f10d 100644 --- a/x-pack/plugins/fleet/server/services/epm/fields/field.test.ts +++ b/x-pack/plugins/fleet/server/services/epm/fields/field.test.ts @@ -9,7 +9,7 @@ import { readFileSync } from 'fs'; import path from 'path'; import globby from 'globby'; -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import { getField, processFields, processFieldsWithWildcard } from './field'; import type { Field, Fields } from './field'; @@ -30,7 +30,7 @@ test('tests loading fields.yml', () => { const files = globby.sync(path.join(__dirname, '/tests/*.yml')); for (const file of files) { const fieldsYML = readFileSync(file, 'utf-8'); - const fields: Field[] = safeLoad(fieldsYML); + const fields: Field[] = load(fieldsYML); const processedFields = processFields(fields); // Check that content file and generated file are equal @@ -778,8 +778,8 @@ describe('processFields', () => { Total swap memory. `; - const noWildcardFields: Field[] = safeLoad(noWildcardYml); - const wildcardWithObjectTypeFields: Field[] = safeLoad(wildcardWithObjectTypeYml); + const noWildcardFields: Field[] = load(noWildcardYml); + const wildcardWithObjectTypeFields: Field[] = load(wildcardWithObjectTypeYml); test('Does not add object type when object_type field when is already defined and name has wildcard', () => { expect(processFieldsWithWildcard(wildcardWithObjectTypeFields)).toMatchInlineSnapshot(` diff --git a/x-pack/plugins/fleet/server/services/epm/fields/field.ts b/x-pack/plugins/fleet/server/services/epm/fields/field.ts index b0f8338c89775..a3ebf58d02e3b 100644 --- a/x-pack/plugins/fleet/server/services/epm/fields/field.ts +++ b/x-pack/plugins/fleet/server/services/epm/fields/field.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import type { PackageInstallContext } from '../../../../common/types'; import { getAssetsDataFromAssetsMap } from '../packages/assets'; @@ -322,8 +322,8 @@ export const loadDatastreamsFieldsFromYaml = ( return fieldDefinitionFiles.reduce((acc, file) => { // Make sure it is defined as it is optional. Should never happen. if (file.buffer) { - const tmpFields = safeLoad(file.buffer.toString()); - // safeLoad() returns undefined for empty files, we don't want that + const tmpFields = load(file.buffer.toString()); + // load() returns undefined for empty files, we don't want that if (tmpFields) { acc = acc.concat(tmpFields); } @@ -345,8 +345,8 @@ export const loadTransformFieldsFromYaml = ( return fieldDefinitionFiles.reduce((acc, file) => { // Make sure it is defined as it is optional. Should never happen. if (file.buffer) { - const tmpFields = safeLoad(file.buffer.toString()); - // safeLoad() returns undefined for empty files, we don't want that + const tmpFields = load(file.buffer.toString()); + // load() returns undefined for empty files, we don't want that if (tmpFields) { acc = acc.concat(tmpFields); } diff --git a/x-pack/plugins/fleet/server/services/epm/packages/custom_integrations/assets/dataset/ingest_pipeline.ts b/x-pack/plugins/fleet/server/services/epm/packages/custom_integrations/assets/dataset/ingest_pipeline.ts index 4d7313cacff72..3fc05d3bd7b0a 100644 --- a/x-pack/plugins/fleet/server/services/epm/packages/custom_integrations/assets/dataset/ingest_pipeline.ts +++ b/x-pack/plugins/fleet/server/services/epm/packages/custom_integrations/assets/dataset/ingest_pipeline.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { safeDump } from 'js-yaml'; +import { dump } from 'js-yaml'; // NOTE: The install methods will take care of adding a reference to a @custom pipeline. We don't need to add one here. export const createDefaultPipeline = (dataset: string, type: string) => { @@ -25,5 +25,5 @@ export const createDefaultPipeline = (dataset: string, type: string) => { managed: true, }, }; - return safeDump(pipeline); + return dump(pipeline); }; diff --git a/x-pack/plugins/fleet/server/services/epm/packages/custom_integrations/assets/dataset/manifest.ts b/x-pack/plugins/fleet/server/services/epm/packages/custom_integrations/assets/dataset/manifest.ts index efca290e31092..21dd67cc207ff 100644 --- a/x-pack/plugins/fleet/server/services/epm/packages/custom_integrations/assets/dataset/manifest.ts +++ b/x-pack/plugins/fleet/server/services/epm/packages/custom_integrations/assets/dataset/manifest.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { safeDump } from 'js-yaml'; +import { dump } from 'js-yaml'; import { convertStringToTitle } from '../../utils'; import type { AssetOptions } from '../generate'; @@ -17,5 +17,5 @@ export const createDatasetManifest = (dataset: string, assetOptions: AssetOption title: convertStringToTitle(dataset), type, }; - return safeDump(manifest); + return dump(manifest); }; diff --git a/x-pack/plugins/fleet/server/services/epm/packages/custom_integrations/assets/manifest.ts b/x-pack/plugins/fleet/server/services/epm/packages/custom_integrations/assets/manifest.ts index 4c27ad6c45343..ac30f439fecbb 100644 --- a/x-pack/plugins/fleet/server/services/epm/packages/custom_integrations/assets/manifest.ts +++ b/x-pack/plugins/fleet/server/services/epm/packages/custom_integrations/assets/manifest.ts @@ -4,7 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { safeDump } from 'js-yaml'; +import { dump } from 'js-yaml'; import type { AssetOptions } from './generate'; @@ -34,5 +34,5 @@ export const createManifest = (assetOptions: AssetOptions) => { }, }; - return safeDump(manifest); + return dump(manifest); }; diff --git a/x-pack/plugins/fleet/server/services/epm/packages/get.ts b/x-pack/plugins/fleet/server/services/epm/packages/get.ts index e59f0ad4b5ae9..2ab0856063367 100644 --- a/x-pack/plugins/fleet/server/services/epm/packages/get.ts +++ b/x-pack/plugins/fleet/server/services/epm/packages/get.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import pMap from 'p-map'; import minimatch from 'minimatch'; import type { @@ -378,7 +378,7 @@ export async function getInstalledPackageManifests( const parsedManifests = result.saved_objects.reduce>( (acc, asset) => { - acc.set(asset.attributes.asset_path, safeLoad(asset.attributes.data_utf8)); + acc.set(asset.attributes.asset_path, load(asset.attributes.data_utf8)); return acc; }, new Map() diff --git a/x-pack/plugins/fleet/server/services/epm/packages/get_template_inputs.ts b/x-pack/plugins/fleet/server/services/epm/packages/get_template_inputs.ts index e4a68ad7bc0aa..640fc3877eabf 100644 --- a/x-pack/plugins/fleet/server/services/epm/packages/get_template_inputs.ts +++ b/x-pack/plugins/fleet/server/services/epm/packages/get_template_inputs.ts @@ -7,7 +7,7 @@ import type { SavedObjectsClientContract } from '@kbn/core/server'; import { merge } from 'lodash'; -import { safeDump } from 'js-yaml'; +import { dump } from 'js-yaml'; import { packageToPackagePolicy } from '../../../../common/services/package_to_package_policy'; import { getInputsWithStreamIds, _compilePackagePolicyInputs } from '../../package_policy'; @@ -121,7 +121,7 @@ export async function getTemplateInputs( if (format === 'json') { return { inputs }; } else if (format === 'yml') { - const yaml = safeDump( + const yaml = dump( { inputs }, { skipInvalid: true, diff --git a/x-pack/plugins/fleet/server/services/epm/packages/utils.test.ts b/x-pack/plugins/fleet/server/services/epm/packages/utils.test.ts index 8de21942d7552..166687a836fb1 100644 --- a/x-pack/plugins/fleet/server/services/epm/packages/utils.test.ts +++ b/x-pack/plugins/fleet/server/services/epm/packages/utils.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { safeDump } from 'js-yaml'; +import { dump } from 'js-yaml'; import type { AssetsMap } from '../../../../common/types'; @@ -14,7 +14,7 @@ import type { RegistryDataStream } from '../../../../common'; import { resolveDataStreamFields } from './utils'; describe('resolveDataStreamFields', () => { - const statusAssetYml = safeDump([ + const statusAssetYml = dump([ { name: 'apache.status', type: 'group', diff --git a/x-pack/plugins/fleet/server/services/epm/packages/utils.ts b/x-pack/plugins/fleet/server/services/epm/packages/utils.ts index 72e1e4dd50bf4..59a95a72d4afd 100644 --- a/x-pack/plugins/fleet/server/services/epm/packages/utils.ts +++ b/x-pack/plugins/fleet/server/services/epm/packages/utils.ts @@ -9,7 +9,7 @@ import { withSpan } from '@kbn/apm-utils'; import type { FieldMetadataPlain } from '@kbn/fields-metadata-plugin/common'; import type { ExtractedDatasetFields } from '@kbn/fields-metadata-plugin/server'; -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import type { RegistryDataStream } from '../../../../common'; import type { AssetsMap } from '../../../../common/types'; @@ -90,7 +90,7 @@ export const resolveDataStreamFields = ({ const fieldsAssetBuffer = assetsMap.get(fieldsAssetPath); if (fieldsAssetBuffer) { - const fieldsAssetJSON = safeLoad(fieldsAssetBuffer.toString('utf8')); + const fieldsAssetJSON = load(fieldsAssetBuffer.toString('utf8')); const normalizedFields = normalizeFields(fieldsAssetJSON); Object.assign(dataStreamFields, normalizedFields); } diff --git a/x-pack/plugins/fleet/server/services/output.ts b/x-pack/plugins/fleet/server/services/output.ts index 96a056c7a9603..22226a9586910 100644 --- a/x-pack/plugins/fleet/server/services/output.ts +++ b/x-pack/plugins/fleet/server/services/output.ts @@ -6,7 +6,7 @@ */ import { v5 as uuidv5 } from 'uuid'; import { omit } from 'lodash'; -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import deepEqual from 'fast-deep-equal'; import { indexBy } from 'lodash/fp'; @@ -524,7 +524,7 @@ class OutputService { if (outputTypeSupportPresets(data.type)) { if ( data.preset === 'balanced' && - outputYmlIncludesReservedPerformanceKey(output.config_yaml ?? '', safeLoad) + outputYmlIncludesReservedPerformanceKey(output.config_yaml ?? '', load) ) { throw new OutputInvalidError( `preset cannot be balanced when config_yaml contains one of ${RESERVED_CONFIG_YML_KEYS.join( @@ -600,11 +600,11 @@ class OutputService { } if (!data.preset && data.type === outputType.Elasticsearch) { - data.preset = getDefaultPresetForEsOutput(data.config_yaml ?? '', safeLoad); + data.preset = getDefaultPresetForEsOutput(data.config_yaml ?? '', load); } if (output.config_yaml) { - const configJs = safeLoad(output.config_yaml); + const configJs = load(output.config_yaml); const isShipperDisabled = !configJs?.shipper || configJs?.shipper?.enabled === false; if (isShipperDisabled && output.shipper) { @@ -876,7 +876,7 @@ class OutputService { if (updateData.type && outputTypeSupportPresets(updateData.type)) { if ( updateData.preset === 'balanced' && - outputYmlIncludesReservedPerformanceKey(updateData.config_yaml ?? '', safeLoad) + outputYmlIncludesReservedPerformanceKey(updateData.config_yaml ?? '', load) ) { throw new OutputInvalidError( `preset cannot be balanced when config_yaml contains one of ${RESERVED_CONFIG_YML_KEYS.join( @@ -1064,7 +1064,7 @@ class OutputService { } if (!data.preset && data.type === outputType.Elasticsearch) { - updateData.preset = getDefaultPresetForEsOutput(data.config_yaml ?? '', safeLoad); + updateData.preset = getDefaultPresetForEsOutput(data.config_yaml ?? '', load); } // Remove the shipper data if the shipper is not enabled from the yaml config @@ -1072,7 +1072,7 @@ class OutputService { updateData.shipper = null; } if (data.config_yaml) { - const configJs = safeLoad(data.config_yaml); + const configJs = load(data.config_yaml); const isShipperDisabled = !configJs?.shipper || configJs?.shipper?.enabled === false; if (isShipperDisabled && data.shipper) { @@ -1150,7 +1150,7 @@ class OutputService { await pMap( outputs.items.filter((output) => outputTypeSupportPresets(output.type) && !output.preset), async (output) => { - const preset = getDefaultPresetForEsOutput(output.config_yaml ?? '', safeLoad); + const preset = getDefaultPresetForEsOutput(output.config_yaml ?? '', load); await outputService.update( soClient, diff --git a/x-pack/plugins/fleet/server/services/package_policy.ts b/x-pack/plugins/fleet/server/services/package_policy.ts index 32058445d0745..bda503257b481 100644 --- a/x-pack/plugins/fleet/server/services/package_policy.ts +++ b/x-pack/plugins/fleet/server/services/package_policy.ts @@ -22,7 +22,7 @@ import type { } from '@kbn/core/server'; import { SavedObjectsUtils } from '@kbn/core/server'; import { v4 as uuidv4 } from 'uuid'; -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import { DEFAULT_SPACE_ID } from '@kbn/spaces-plugin/common/constants'; @@ -2287,7 +2287,7 @@ class PackagePolicyClientWithAuthz extends PackagePolicyClientImpl { } function validatePackagePolicyOrThrow(packagePolicy: NewPackagePolicy, pkgInfo: PackageInfo) { - const validationResults = validatePackagePolicy(packagePolicy, pkgInfo, safeLoad); + const validationResults = validatePackagePolicy(packagePolicy, pkgInfo, load); if (validationHasErrors(validationResults)) { const responseFormattedValidationErrors = Object.entries(getFlattenedObject(validationResults)) .map(([key, value]) => ({ @@ -2784,7 +2784,7 @@ export function updatePackageInputs( inputs, }; - const validationResults = validatePackagePolicy(resultingPackagePolicy, packageInfo, safeLoad); + const validationResults = validatePackagePolicy(resultingPackagePolicy, packageInfo, load); if (validationHasErrors(validationResults)) { const responseFormattedValidationErrors = Object.entries(getFlattenedObject(validationResults)) diff --git a/x-pack/plugins/fleet/server/services/preconfiguration/outputs.ts b/x-pack/plugins/fleet/server/services/preconfiguration/outputs.ts index fa7103bebb3b4..3b6b795b7ecda 100644 --- a/x-pack/plugins/fleet/server/services/preconfiguration/outputs.ts +++ b/x-pack/plugins/fleet/server/services/preconfiguration/outputs.ts @@ -9,7 +9,7 @@ import crypto from 'crypto'; import type { ElasticsearchClient, SavedObjectsClientContract } from '@kbn/core/server'; import { isEqual } from 'lodash'; -import { safeDump } from 'js-yaml'; +import { dump } from 'js-yaml'; import type { PreconfiguredOutput, @@ -82,7 +82,7 @@ export async function createOrUpdatePreconfiguredOutputs( const { id, config, ...outputData } = output; - const configYaml = config ? safeDump(config) : undefined; + const configYaml = config ? dump(config) : undefined; const data: NewOutput = { ...outputData, diff --git a/x-pack/plugins/inference/scripts/util/read_kibana_config.ts b/x-pack/plugins/inference/scripts/util/read_kibana_config.ts index 5b64bb2f56189..7d539e881bee8 100644 --- a/x-pack/plugins/inference/scripts/util/read_kibana_config.ts +++ b/x-pack/plugins/inference/scripts/util/read_kibana_config.ts @@ -17,7 +17,7 @@ export const readKibanaConfig = () => { const kibanaDevConfig = path.join(kibanaConfigDir, 'kibana.dev.yml'); const kibanaConfig = path.join(kibanaConfigDir, 'kibana.yml'); - const loadedKibanaConfig = (yaml.safeLoad( + const loadedKibanaConfig = (yaml.load( fs.readFileSync(fs.existsSync(kibanaDevConfig) ? kibanaDevConfig : kibanaConfig, 'utf8') ) || {}) as {}; diff --git a/x-pack/plugins/integration_assistant/server/graphs/ecs/pipeline.ts b/x-pack/plugins/integration_assistant/server/graphs/ecs/pipeline.ts index e2d91c094d520..b5a6e23000d32 100644 --- a/x-pack/plugins/integration_assistant/server/graphs/ecs/pipeline.ts +++ b/x-pack/plugins/integration_assistant/server/graphs/ecs/pipeline.ts @@ -5,7 +5,7 @@ * 2.0. */ /* eslint-disable @typescript-eslint/no-explicit-any */ -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import { Environment, FileSystemLoader } from 'nunjucks'; import { join as joinPath } from 'path'; import { Pipeline, ESProcessorItem } from '../../../common'; @@ -191,7 +191,7 @@ export function createPipeline(state: EcsMappingState): IngestPipeline { }); const template = env.getTemplate('pipeline.yml.njk'); const renderedTemplate = template.render(mappedValues); - let ingestPipeline = safeLoad(renderedTemplate) as Pipeline; + let ingestPipeline = load(renderedTemplate) as Pipeline; if (state.additionalProcessors.length > 0) { ingestPipeline = combineProcessors(ingestPipeline, state.additionalProcessors); } diff --git a/x-pack/plugins/integration_assistant/server/integration_builder/build_integration.test.ts b/x-pack/plugins/integration_assistant/server/integration_builder/build_integration.test.ts index 50ec954bcb118..d3bd013e6e267 100644 --- a/x-pack/plugins/integration_assistant/server/integration_builder/build_integration.test.ts +++ b/x-pack/plugins/integration_assistant/server/integration_builder/build_integration.test.ts @@ -252,7 +252,7 @@ describe('renderPackageManifestYAML', () => { const manifestContent = renderPackageManifestYAML(integration); // The manifest content must be parseable as YAML. - const manifest = yaml.safeLoad(manifestContent); + const manifest = yaml.load(manifestContent) as Record; expect(manifest).toBeDefined(); expect(manifest.title).toBe(integration.title); diff --git a/x-pack/plugins/integration_assistant/server/integration_builder/build_integration.ts b/x-pack/plugins/integration_assistant/server/integration_builder/build_integration.ts index 0a97977c653a5..b9bc1b55268d7 100644 --- a/x-pack/plugins/integration_assistant/server/integration_builder/build_integration.ts +++ b/x-pack/plugins/integration_assistant/server/integration_builder/build_integration.ts @@ -9,7 +9,7 @@ import AdmZip from 'adm-zip'; import nunjucks from 'nunjucks'; import { getDataPath } from '@kbn/utils'; import { join as joinPath } from 'path'; -import { safeDump } from 'js-yaml'; +import { dump } from 'js-yaml'; import type { DataStream, Integration } from '../../common'; import { createSync, ensureDirSync, generateUniqueId, removeDirSync } from '../util'; import { createAgentInput } from './agent'; @@ -228,7 +228,7 @@ export function renderPackageManifestYAML(integration: Integration): string { uniqueInputsList // inputs ); - return safeDump(packageData); + return dump(packageData); } function createPackageManifest(packageDir: string, integration: Integration): void { diff --git a/x-pack/plugins/integration_assistant/server/integration_builder/pipeline.ts b/x-pack/plugins/integration_assistant/server/integration_builder/pipeline.ts index 2cb22e4dfa8ab..d733fd001be02 100644 --- a/x-pack/plugins/integration_assistant/server/integration_builder/pipeline.ts +++ b/x-pack/plugins/integration_assistant/server/integration_builder/pipeline.ts @@ -11,6 +11,6 @@ import { createSync } from '../util'; export function createPipeline(specificDataStreamDir: string, pipeline: object): void { const filePath = joinPath(specificDataStreamDir, 'elasticsearch/ingest_pipeline/default.yml'); - const yamlContent = `---\n${yaml.safeDump(pipeline, { sortKeys: false })}`; + const yamlContent = `---\n${yaml.dump(pipeline, { sortKeys: false })}`; createSync(filePath, yamlContent); } diff --git a/x-pack/plugins/integration_assistant/server/util/processors.ts b/x-pack/plugins/integration_assistant/server/util/processors.ts index b2e6b1683482a..e77140b91a926 100644 --- a/x-pack/plugins/integration_assistant/server/util/processors.ts +++ b/x-pack/plugins/integration_assistant/server/util/processors.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import { join as joinPath } from 'path'; import { Environment, FileSystemLoader } from 'nunjucks'; import { deepCopy } from './util'; @@ -44,7 +44,7 @@ function createAppendProcessors(processors: SimplifiedProcessors): ESProcessorIt }); const template = env.getTemplate('append.yml.njk'); const renderedTemplate = template.render({ processors }); - const appendProcessors = safeLoad(renderedTemplate) as ESProcessorItem[]; + const appendProcessors = load(renderedTemplate) as ESProcessorItem[]; return appendProcessors; } @@ -57,7 +57,7 @@ export function createGrokProcessor(grokPatterns: string[]): ESProcessorItem { }); const template = env.getTemplate('grok.yml.njk'); const renderedTemplate = template.render({ grokPatterns }); - const grokProcessor = safeLoad(renderedTemplate) as ESProcessorItem; + const grokProcessor = load(renderedTemplate) as ESProcessorItem; return grokProcessor; } @@ -74,6 +74,6 @@ export function createKVProcessor(kvInput: KVProcessor, state: KVState): ESProce packageName: state.packageName, dataStreamName: state.dataStreamName, }); - const kvProcessor = safeLoad(renderedTemplate) as ESProcessorItem; + const kvProcessor = load(renderedTemplate) as ESProcessorItem; return kvProcessor; } diff --git a/x-pack/plugins/integration_assistant/server/util/samples.ts b/x-pack/plugins/integration_assistant/server/util/samples.ts index 745c3d214095f..65b26ef0476d0 100644 --- a/x-pack/plugins/integration_assistant/server/util/samples.ts +++ b/x-pack/plugins/integration_assistant/server/util/samples.ts @@ -160,7 +160,7 @@ export function generateFields(mergedDocs: string): string { .filter((key) => !ecsTopKeysSet.has(key)) .map((key) => recursiveParse(doc[key], [key])); - return yaml.safeDump(fieldsStructure, { sortKeys: false }); + return yaml.dump(fieldsStructure, { sortKeys: false }); } export function merge( diff --git a/x-pack/plugins/observability_solution/apm/public/components/fleet_integration/apm_agents/runtime_attachment/supported_agents/java_runtime_attachment.tsx b/x-pack/plugins/observability_solution/apm/public/components/fleet_integration/apm_agents/runtime_attachment/supported_agents/java_runtime_attachment.tsx index 8f558c49e66ee..204e9266c6bfe 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/fleet_integration/apm_agents/runtime_attachment/supported_agents/java_runtime_attachment.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/fleet_integration/apm_agents/runtime_attachment/supported_agents/java_runtime_attachment.tsx @@ -205,7 +205,7 @@ function decodeDiscoveryRulesYaml( defaultDiscoveryRules: IDiscoveryRule[] = [] ): IDiscoveryRule[] { try { - const parsedYaml: DiscoveryRulesParsedYaml = yaml.safeLoad(discoveryRulesYaml) ?? []; + const parsedYaml = (yaml.load(discoveryRulesYaml) as DiscoveryRulesParsedYaml) ?? []; if (parsedYaml.length === 0) { return defaultDiscoveryRules; @@ -232,5 +232,5 @@ function encodeDiscoveryRulesYaml(discoveryRules: IDiscoveryRule[]): string { [`${operation}-${type}`]: probe, }) ); - return yaml.safeDump(mappedDiscoveryRules); + return yaml.dump(mappedDiscoveryRules); } diff --git a/x-pack/plugins/observability_solution/apm/scripts/shared/read_kibana_config.ts b/x-pack/plugins/observability_solution/apm/scripts/shared/read_kibana_config.ts index c440fc5dfcea4..20e0aedeeca03 100644 --- a/x-pack/plugins/observability_solution/apm/scripts/shared/read_kibana_config.ts +++ b/x-pack/plugins/observability_solution/apm/scripts/shared/read_kibana_config.ts @@ -17,7 +17,7 @@ export const readKibanaConfig = () => { const kibanaDevConfig = path.join(kibanaConfigDir, 'kibana.dev.yml'); const kibanaConfig = path.join(kibanaConfigDir, 'kibana.yml'); - const loadedKibanaConfig = (yaml.safeLoad( + const loadedKibanaConfig = (yaml.load( fs.readFileSync(fs.existsSync(kibanaDevConfig) ? kibanaDevConfig : kibanaConfig, 'utf8') ) || {}) as {}; diff --git a/x-pack/plugins/observability_solution/apm/server/routes/fleet/get_apm_package_policy_definition.ts b/x-pack/plugins/observability_solution/apm/server/routes/fleet/get_apm_package_policy_definition.ts index 8060c3c2ab622..06037bf53fdc6 100644 --- a/x-pack/plugins/observability_solution/apm/server/routes/fleet/get_apm_package_policy_definition.ts +++ b/x-pack/plugins/observability_solution/apm/server/routes/fleet/get_apm_package_policy_definition.ts @@ -99,7 +99,7 @@ function ensureValidMultiText(textMultiValue: string[] | undefined) { function escapeInvalidYamlString(yamlString: string) { try { - yaml.safeLoad(yamlString); + yaml.load(yamlString); } catch (error) { if (error instanceof yaml.YAMLException) { return `"${yamlString}"`; diff --git a/x-pack/plugins/observability_solution/observability_ai_assistant_app/scripts/evaluation/read_kibana_config.ts b/x-pack/plugins/observability_solution/observability_ai_assistant_app/scripts/evaluation/read_kibana_config.ts index a765adcf52f5b..fca94a8d57d05 100644 --- a/x-pack/plugins/observability_solution/observability_ai_assistant_app/scripts/evaluation/read_kibana_config.ts +++ b/x-pack/plugins/observability_solution/observability_ai_assistant_app/scripts/evaluation/read_kibana_config.ts @@ -17,7 +17,7 @@ export const readKibanaConfig = () => { const kibanaDevConfig = path.join(kibanaConfigDir, 'kibana.dev.yml'); const kibanaConfig = path.join(kibanaConfigDir, 'kibana.yml'); - const loadedKibanaConfig = (yaml.safeLoad( + const loadedKibanaConfig = (yaml.load( fs.readFileSync(fs.existsSync(kibanaDevConfig) ? kibanaDevConfig : kibanaConfig, 'utf8') ) || {}) as {}; diff --git a/x-pack/plugins/observability_solution/observability_onboarding/common/elastic_agent_logs/custom_logs/__snapshots__/generate_custom_logs_yml.test.ts.snap b/x-pack/plugins/observability_solution/observability_onboarding/common/elastic_agent_logs/custom_logs/__snapshots__/generate_custom_logs_yml.test.ts.snap index dc388bb5e260d..491866d36fa7a 100644 --- a/x-pack/plugins/observability_solution/observability_onboarding/common/elastic_agent_logs/custom_logs/__snapshots__/generate_custom_logs_yml.test.ts.snap +++ b/x-pack/plugins/observability_solution/observability_onboarding/common/elastic_agent_logs/custom_logs/__snapshots__/generate_custom_logs_yml.test.ts.snap @@ -5,8 +5,8 @@ exports[`generateCustomLogsYml should return a basic yml configuration 1`] = ` default: type: elasticsearch hosts: - - 'http://localhost:9200' - api_key: 'elastic:changeme' + - http://localhost:9200 + api_key: elastic:changeme inputs: - id: my-logs-id type: logfile @@ -26,8 +26,8 @@ exports[`generateCustomLogsYml should return a yml configuration with customConf default: type: elasticsearch hosts: - - 'http://localhost:9200' - api_key: 'elastic:changeme' + - http://localhost:9200 + api_key: elastic:changeme inputs: - id: my-logs-id type: logfile @@ -52,8 +52,8 @@ exports[`generateCustomLogsYml should return a yml configuration with multiple l default: type: elasticsearch hosts: - - 'http://localhost:9200' - api_key: 'elastic:changeme' + - http://localhost:9200 + api_key: elastic:changeme inputs: - id: my-logs-id type: logfile @@ -74,8 +74,8 @@ exports[`generateCustomLogsYml should return a yml configuration with service na default: type: elasticsearch hosts: - - 'http://localhost:9200' - api_key: 'elastic:changeme' + - http://localhost:9200 + api_key: elastic:changeme inputs: - id: my-logs-id type: logfile diff --git a/x-pack/plugins/observability_solution/observability_onboarding/common/elastic_agent_logs/custom_logs/generate_custom_logs_yml.test.ts b/x-pack/plugins/observability_solution/observability_onboarding/common/elastic_agent_logs/custom_logs/generate_custom_logs_yml.test.ts index 6268e34bc3d49..6cacfab2b792e 100644 --- a/x-pack/plugins/observability_solution/observability_onboarding/common/elastic_agent_logs/custom_logs/generate_custom_logs_yml.test.ts +++ b/x-pack/plugins/observability_solution/observability_onboarding/common/elastic_agent_logs/custom_logs/generate_custom_logs_yml.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { safeDump } from 'js-yaml'; +import { dump } from 'js-yaml'; import { generateCustomLogsYml } from './generate_custom_logs_yml'; const baseMockConfig = { @@ -46,7 +46,7 @@ describe('generateCustomLogsYml', () => { it('should return a yml configuration with customConfigurations', () => { const mockConfig = { ...baseMockConfig, - customConfigurations: safeDump({ + customConfigurations: dump({ ['agent.retry']: { enabled: true, retriesCount: 3, diff --git a/x-pack/plugins/observability_solution/observability_onboarding/common/elastic_agent_logs/custom_logs/generate_custom_logs_yml.ts b/x-pack/plugins/observability_solution/observability_onboarding/common/elastic_agent_logs/custom_logs/generate_custom_logs_yml.ts index 4564abe04bd63..b836012f55fda 100644 --- a/x-pack/plugins/observability_solution/observability_onboarding/common/elastic_agent_logs/custom_logs/generate_custom_logs_yml.ts +++ b/x-pack/plugins/observability_solution/observability_onboarding/common/elastic_agent_logs/custom_logs/generate_custom_logs_yml.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { safeDump, safeLoad } from 'js-yaml'; +import { dump, load } from 'js-yaml'; export const generateCustomLogsYml = ({ datasetName = '', @@ -26,7 +26,7 @@ export const generateCustomLogsYml = ({ esHost: string[]; logfileId: string; }) => { - const customConfigYaml = safeLoad(customConfigurations ?? ''); + const customConfigYaml = load(customConfigurations ?? ''); const processors = [ { add_fields: { @@ -38,7 +38,7 @@ export const generateCustomLogsYml = ({ }, ]; - return safeDump({ + return dump({ ...{ outputs: { default: { diff --git a/x-pack/plugins/observability_solution/observability_onboarding/common/elastic_agent_logs/system_logs/__snapshots__/generate_system_logs_yml.test.ts.snap b/x-pack/plugins/observability_solution/observability_onboarding/common/elastic_agent_logs/system_logs/__snapshots__/generate_system_logs_yml.test.ts.snap index 074876d9d9119..ed4d602ba6a2f 100644 --- a/x-pack/plugins/observability_solution/observability_onboarding/common/elastic_agent_logs/system_logs/__snapshots__/generate_system_logs_yml.test.ts.snap +++ b/x-pack/plugins/observability_solution/observability_onboarding/common/elastic_agent_logs/system_logs/__snapshots__/generate_system_logs_yml.test.ts.snap @@ -5,8 +5,8 @@ exports[`generateSystemLogsYml should return system logs oriented yml configurat default: type: elasticsearch hosts: - - 'http://localhost:9200' - api_key: 'elastic:changeme' + - http://localhost:9200 + api_key: elastic:changeme inputs: - id: system-logs-8df0ff52-6f3b-4b5a-a2da-f06c55d111d1 type: logfile diff --git a/x-pack/plugins/observability_solution/observability_onboarding/common/elastic_agent_logs/system_logs/generate_system_logs_yml.ts b/x-pack/plugins/observability_solution/observability_onboarding/common/elastic_agent_logs/system_logs/generate_system_logs_yml.ts index d3c80f864674a..26552b8612193 100644 --- a/x-pack/plugins/observability_solution/observability_onboarding/common/elastic_agent_logs/system_logs/generate_system_logs_yml.ts +++ b/x-pack/plugins/observability_solution/observability_onboarding/common/elastic_agent_logs/system_logs/generate_system_logs_yml.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { safeDump } from 'js-yaml'; +import { dump } from 'js-yaml'; interface SystemLogsStream { id: string; @@ -36,7 +36,7 @@ export const generateSystemLogsYml = ({ esHost: string[]; uuid: string; }) => { - return safeDump({ + return dump({ outputs: { default: { type: 'elasticsearch', diff --git a/x-pack/plugins/observability_solution/observability_onboarding/server/routes/flow/route.ts b/x-pack/plugins/observability_solution/observability_onboarding/server/routes/flow/route.ts index 6b30ed8c3e089..1589269d99aa8 100644 --- a/x-pack/plugins/observability_solution/observability_onboarding/server/routes/flow/route.ts +++ b/x-pack/plugins/observability_solution/observability_onboarding/server/routes/flow/route.ts @@ -12,7 +12,7 @@ import { FleetUnauthorizedError, type PackageClient, } from '@kbn/fleet-plugin/server'; -import { safeDump } from 'js-yaml'; +import { dump } from 'js-yaml'; import { PackageDataStreamTypes } from '@kbn/fleet-plugin/common/types'; import { getObservabilityOnboardingFlow, saveObservabilityOnboardingFlow } from '../../lib/state'; import type { SavedObservabilityOnboardingFlow } from '../../saved_objects/observability_onboarding_status'; @@ -531,7 +531,7 @@ const generateAgentConfigYAML = ({ elasticsearchUrl: string[]; installedIntegrations: InstalledIntegration[]; }) => { - return safeDump({ + return dump({ outputs: { default: { type: 'elasticsearch', @@ -557,7 +557,7 @@ const generateAgentConfigTar = ({ path: 'elastic-agent.yml', mode: 0o644, mtime: now, - data: safeDump({ + data: dump({ outputs: { default: { type: 'elasticsearch', @@ -578,7 +578,7 @@ const generateAgentConfigTar = ({ path: `inputs.d/${integration.pkgName}.yml`, mode: 0o644, mtime: now, - data: safeDump({ inputs: integration.inputs }), + data: dump({ inputs: integration.inputs }), })), ]); }; diff --git a/x-pack/plugins/observability_solution/observability_onboarding/tsconfig.json b/x-pack/plugins/observability_solution/observability_onboarding/tsconfig.json index 8730f85b5943f..8ff05aeb7154e 100644 --- a/x-pack/plugins/observability_solution/observability_onboarding/tsconfig.json +++ b/x-pack/plugins/observability_solution/observability_onboarding/tsconfig.json @@ -4,10 +4,9 @@ "outDir": "target/types" }, "include": [ - "../../../../typings/**/*", "common/**/*", "public/**/*", - "typings/**/*", + "../../../../typings/**/*", "public/**/*.json", "server/**/*" ], diff --git a/x-pack/plugins/observability_solution/synthetics/e2e/tasks/read_kibana_config.ts b/x-pack/plugins/observability_solution/synthetics/e2e/tasks/read_kibana_config.ts index ad7ab18f1f2e8..75f446d1cdefb 100644 --- a/x-pack/plugins/observability_solution/synthetics/e2e/tasks/read_kibana_config.ts +++ b/x-pack/plugins/observability_solution/synthetics/e2e/tasks/read_kibana_config.ts @@ -17,7 +17,7 @@ export const readKibanaConfig = () => { const kibanaDevConfig = path.join(kibanaConfigDir, 'kibana.dev.yml'); const kibanaConfig = path.join(kibanaConfigDir, 'kibana.yml'); - return (yaml.safeLoad( + return (yaml.load( fs.readFileSync(fs.existsSync(kibanaDevConfig) ? kibanaDevConfig : kibanaConfig, 'utf8') ) || {}) as Record; }; diff --git a/x-pack/plugins/observability_solution/uptime/e2e/tasks/read_kibana_config.ts b/x-pack/plugins/observability_solution/uptime/e2e/tasks/read_kibana_config.ts index f8c8dc2eb6fdd..b892454b12c97 100644 --- a/x-pack/plugins/observability_solution/uptime/e2e/tasks/read_kibana_config.ts +++ b/x-pack/plugins/observability_solution/uptime/e2e/tasks/read_kibana_config.ts @@ -16,7 +16,7 @@ export const readKibanaConfig = () => { const kibanaDevConfig = path.join(kibanaConfigDir, 'kibana.dev.yml'); const kibanaConfig = path.join(kibanaConfigDir, 'kibana.yml'); - return (yaml.safeLoad( + return (yaml.load( fs.readFileSync(fs.existsSync(kibanaDevConfig) ? kibanaDevConfig : kibanaConfig, 'utf8') ) || {}) as Record; }; diff --git a/x-pack/plugins/osquery/cypress/cypress_base.config.ts b/x-pack/plugins/osquery/cypress/cypress_base.config.ts index 820df131c700f..75109dc423ff3 100644 --- a/x-pack/plugins/osquery/cypress/cypress_base.config.ts +++ b/x-pack/plugins/osquery/cypress/cypress_base.config.ts @@ -7,7 +7,7 @@ import { merge } from 'lodash'; import path from 'path'; -import { safeLoad as loadYaml } from 'js-yaml'; +import { load as loadYaml } from 'js-yaml'; import { readFileSync } from 'fs'; import type { YamlRoleDefinitions } from '@kbn/test-suites-serverless/shared/lib'; import { setupUserDataLoader } from '@kbn/test-suites-serverless/functional/test_suites/security/cypress/support/setup_data_loader_tasks'; diff --git a/x-pack/plugins/osquery/docs/openapi/ess/osquery_api_2023_10_31.bundled.schema.yaml b/x-pack/plugins/osquery/docs/openapi/ess/osquery_api_2023_10_31.bundled.schema.yaml index 4f6933aef5f2f..1c660af3c886f 100644 --- a/x-pack/plugins/osquery/docs/openapi/ess/osquery_api_2023_10_31.bundled.schema.yaml +++ b/x-pack/plugins/osquery/docs/openapi/ess/osquery_api_2023_10_31.bundled.schema.yaml @@ -1,10 +1,10 @@ openapi: 3.0.3 info: - description: 'Run live queries, manage packs and saved queries.' + description: Run live queries, manage packs and saved queries. title: Security Solution Osquery API (Elastic Cloud and self-hosted) version: '2023-10-31' servers: - - url: 'http://{kibana_host}:{port}' + - url: http://{kibana_host}:{port} variables: kibana_host: default: localhost @@ -50,7 +50,7 @@ paths: summary: Create a live query tags: - Security Solution Osquery API - '/api/osquery/live_queries/{id}': + /api/osquery/live_queries/{id}: get: description: Get the details of a live query using the query ID. operationId: OsqueryGetLiveQueryDetails @@ -75,7 +75,7 @@ paths: summary: Get live query details tags: - Security Solution Osquery API - '/api/osquery/live_queries/{id}/results/{actionId}': + /api/osquery/live_queries/{id}/results/{actionId}: get: description: Get the results of a live query using the query action ID. operationId: OsqueryGetLiveQueryResults @@ -144,7 +144,7 @@ paths: summary: Create a pack tags: - Security Solution Osquery API - '/api/osquery/packs/{id}': + /api/osquery/packs/{id}: delete: description: Delete a query pack using the pack ID. operationId: OsqueryDeletePacks @@ -250,7 +250,7 @@ paths: summary: Create a saved query tags: - Security Solution Osquery API - '/api/osquery/saved_queries/{id}': + /api/osquery/saved_queries/{id}: delete: description: Delete a saved query using the query ID. operationId: OsqueryDeleteSavedQuery @@ -637,5 +637,5 @@ components: security: - BasicAuth: [] tags: - - description: 'Run live queries, manage packs and saved queries.' + - description: Run live queries, manage packs and saved queries. name: Security Solution Osquery API diff --git a/x-pack/plugins/osquery/docs/openapi/serverless/osquery_api_2023_10_31.bundled.schema.yaml b/x-pack/plugins/osquery/docs/openapi/serverless/osquery_api_2023_10_31.bundled.schema.yaml index 836298b2e7cba..98c114af74705 100644 --- a/x-pack/plugins/osquery/docs/openapi/serverless/osquery_api_2023_10_31.bundled.schema.yaml +++ b/x-pack/plugins/osquery/docs/openapi/serverless/osquery_api_2023_10_31.bundled.schema.yaml @@ -1,10 +1,10 @@ openapi: 3.0.3 info: - description: 'Run live queries, manage packs and saved queries.' + description: Run live queries, manage packs and saved queries. title: Security Solution Osquery API (Elastic Cloud Serverless) version: '2023-10-31' servers: - - url: 'http://{kibana_host}:{port}' + - url: http://{kibana_host}:{port} variables: kibana_host: default: localhost @@ -50,7 +50,7 @@ paths: summary: Create a live query tags: - Security Solution Osquery API - '/api/osquery/live_queries/{id}': + /api/osquery/live_queries/{id}: get: description: Get the details of a live query using the query ID. operationId: OsqueryGetLiveQueryDetails @@ -75,7 +75,7 @@ paths: summary: Get live query details tags: - Security Solution Osquery API - '/api/osquery/live_queries/{id}/results/{actionId}': + /api/osquery/live_queries/{id}/results/{actionId}: get: description: Get the results of a live query using the query action ID. operationId: OsqueryGetLiveQueryResults @@ -144,7 +144,7 @@ paths: summary: Create a pack tags: - Security Solution Osquery API - '/api/osquery/packs/{id}': + /api/osquery/packs/{id}: delete: description: Delete a query pack using the pack ID. operationId: OsqueryDeletePacks @@ -250,7 +250,7 @@ paths: summary: Create a saved query tags: - Security Solution Osquery API - '/api/osquery/saved_queries/{id}': + /api/osquery/saved_queries/{id}: delete: description: Delete a saved query using the query ID. operationId: OsqueryDeleteSavedQuery @@ -637,5 +637,5 @@ components: security: - BasicAuth: [] tags: - - description: 'Run live queries, manage packs and saved queries.' + - description: Run live queries, manage packs and saved queries. name: Security Solution Osquery API diff --git a/x-pack/plugins/rule_registry/scripts/generate_ecs_fieldmap/index.js b/x-pack/plugins/rule_registry/scripts/generate_ecs_fieldmap/index.js index b8ed10cda9375..3b039bdeb99a9 100644 --- a/x-pack/plugins/rule_registry/scripts/generate_ecs_fieldmap/index.js +++ b/x-pack/plugins/rule_registry/scripts/generate_ecs_fieldmap/index.js @@ -30,7 +30,7 @@ async function generate() { ); } - const flatYaml = await yaml.safeLoad(await readFile(ecsYamlFilename)); + const flatYaml = await yaml.load(await readFile(ecsYamlFilename)); const fields = reduce( flatYaml, diff --git a/x-pack/plugins/security_solution/docs/openapi/ess/security_solution_detections_api_2023_10_31.bundled.schema.yaml b/x-pack/plugins/security_solution/docs/openapi/ess/security_solution_detections_api_2023_10_31.bundled.schema.yaml index 8642113778fe0..0df64f51f37ce 100644 --- a/x-pack/plugins/security_solution/docs/openapi/ess/security_solution_detections_api_2023_10_31.bundled.schema.yaml +++ b/x-pack/plugins/security_solution/docs/openapi/ess/security_solution_detections_api_2023_10_31.bundled.schema.yaml @@ -7,7 +7,7 @@ info: title: Security Solution Detections API (Elastic Cloud and self-hosted) version: '2023-10-31' servers: - - url: 'http://{kibana_host}:{port}' + - url: http://{kibana_host}:{port} variables: kibana_host: default: localhost @@ -362,7 +362,7 @@ paths: items: $ref: '#/components/schemas/RuleCreateProps' type: array - description: 'A JSON array of rules, where each rule contains the required fields.' + description: A JSON array of rules, where each rule contains the required fields. required: true responses: '200': @@ -492,7 +492,7 @@ paths: items: $ref: '#/components/schemas/RulePatchProps' type: array - description: 'A JSON array of rules, where each rule contains the required fields.' + description: A JSON array of rules, where each rule contains the required fields. required: true responses: '200': @@ -1682,12 +1682,12 @@ components: Interval in which the rule runs. For example, `"1h"` means the rule runs every hour. example: 1h - pattern: '^[1-9]\d*[smh]$' + pattern: ^[1-9]\d*[smh]$ type: string lookback: description: Lookback time for the rule example: 1h - pattern: '^[1-9]\d*[smh]$' + pattern: ^[1-9]\d*[smh]$ type: string required: - interval @@ -4990,9 +4990,9 @@ components: - no_actions - rule type: string - - description: 'Time interval in seconds, minutes, hours, or days.' + - description: Time interval in seconds, minutes, hours, or days. example: 1h - pattern: '^[1-9]\d*[smhd]$' + pattern: ^[1-9]\d*[smhd]$ type: string RuleAuthorArray: items: @@ -5228,7 +5228,7 @@ components: discriminator: propertyName: type RuleSignatureId: - description: 'Could be any string, not necessarily a UUID' + description: Could be any string, not necessarily a UUID type: string RuleSource: description: >- diff --git a/x-pack/plugins/security_solution/docs/openapi/ess/security_solution_endpoint_management_api_2023_10_31.bundled.schema.yaml b/x-pack/plugins/security_solution/docs/openapi/ess/security_solution_endpoint_management_api_2023_10_31.bundled.schema.yaml index d2f297b6109fa..0513864243682 100644 --- a/x-pack/plugins/security_solution/docs/openapi/ess/security_solution_endpoint_management_api_2023_10_31.bundled.schema.yaml +++ b/x-pack/plugins/security_solution/docs/openapi/ess/security_solution_endpoint_management_api_2023_10_31.bundled.schema.yaml @@ -4,7 +4,7 @@ info: title: Security Solution Endpoint Management API (Elastic Cloud and self-hosted) version: '2023-10-31' servers: - - url: 'http://{kibana_host}:{port}' + - url: http://{kibana_host}:{port} variables: kibana_host: default: localhost @@ -31,7 +31,7 @@ paths: summary: Get response actions tags: - Security Solution Endpoint Management API - '/api/endpoint/action_log/{agent_id}': + /api/endpoint/action_log/{agent_id}: get: deprecated: true description: Get an action request log for the specified agent ID. @@ -80,7 +80,7 @@ paths: summary: Get response actions status tags: - Security Solution Endpoint Management API - '/api/endpoint/action/{action_id}': + /api/endpoint/action/{action_id}: get: description: Get the details of a response action using the action ID. operationId: EndpointGetActionsDetails @@ -100,7 +100,7 @@ paths: summary: Get action details tags: - Security Solution Endpoint Management API - '/api/endpoint/action/{action_id}/file/{file_id}': + /api/endpoint/action/{action_id}/file/{file_id}: get: description: Get information for the specified file using the file ID. operationId: EndpointFileInfo @@ -125,7 +125,7 @@ paths: summary: Get file information tags: - Security Solution Endpoint Management API - '/api/endpoint/action/{action_id}/file/{file_id}/download': + /api/endpoint/action/{action_id}/file/{file_id}/download: get: description: Download a file from an endpoint. operationId: EndpointFileDownload @@ -310,7 +310,7 @@ paths: - Security Solution Endpoint Management API /api/endpoint/action/unisolate: post: - description: 'Release an isolated endpoint, allowing it to rejoin a network.' + description: Release an isolated endpoint, allowing it to rejoin a network. operationId: EndpointUnisolateAction requestBody: content: @@ -417,7 +417,7 @@ paths: summary: Get a metadata list tags: - Security Solution Endpoint Management API - '/api/endpoint/metadata/{id}': + /api/endpoint/metadata/{id}: get: operationId: GetEndpointMetadata parameters: @@ -497,7 +497,7 @@ paths: summary: Get an agent policy summary tags: - Security Solution Endpoint Management API - '/api/endpoint/protection_updates_note/{package_policy_id}': + /api/endpoint/protection_updates_note/{package_policy_id}: get: operationId: GetProtectionUpdatesNote parameters: @@ -543,7 +543,7 @@ paths: summary: Create or update a protection updates note tags: - Security Solution Endpoint Management API - '/api/endpoint/suggestions/{suggestion_type}': + /api/endpoint/suggestions/{suggestion_type}: post: operationId: GetEndpointSuggestions parameters: diff --git a/x-pack/plugins/security_solution/docs/openapi/ess/security_solution_entity_analytics_api_2023_10_31.bundled.schema.yaml b/x-pack/plugins/security_solution/docs/openapi/ess/security_solution_entity_analytics_api_2023_10_31.bundled.schema.yaml index 9e56395f2af75..b1f7e444371f7 100644 --- a/x-pack/plugins/security_solution/docs/openapi/ess/security_solution_entity_analytics_api_2023_10_31.bundled.schema.yaml +++ b/x-pack/plugins/security_solution/docs/openapi/ess/security_solution_entity_analytics_api_2023_10_31.bundled.schema.yaml @@ -4,7 +4,7 @@ info: title: Security Solution Entity Analytics API (Elastic Cloud and self-hosted) version: '2023-10-31' servers: - - url: 'http://{kibana_host}:{port}' + - url: http://{kibana_host}:{port} variables: kibana_host: default: localhost @@ -182,7 +182,7 @@ paths: - Security Solution Entity Analytics API /api/asset_criticality/list: get: - description: 'List asset criticality records, paging, sorting and filtering as needed.' + description: List asset criticality records, paging, sorting and filtering as needed. operationId: FindAssetCriticalityRecords parameters: - description: The field to sort by. @@ -276,7 +276,7 @@ paths: summary: List the Entity Store engines tags: - Security Solution Entity Analytics API - '/api/entity_store/engines/{entityType}': + /api/entity_store/engines/{entityType}: delete: operationId: DeleteEntityStore parameters: @@ -324,7 +324,7 @@ paths: summary: Get the Entity Store engine tags: - Security Solution Entity Analytics API - '/api/entity_store/engines/{entityType}/init': + /api/entity_store/engines/{entityType}/init: post: operationId: InitEntityStore parameters: @@ -356,7 +356,7 @@ paths: summary: Initialize the Entity Store tags: - Security Solution Entity Analytics API - '/api/entity_store/engines/{entityType}/start': + /api/entity_store/engines/{entityType}/start: post: operationId: StartEntityStore parameters: @@ -379,7 +379,7 @@ paths: summary: Start the Entity Store engine tags: - Security Solution Entity Analytics API - '/api/entity_store/engines/{entityType}/stats': + /api/entity_store/engines/{entityType}/stats: post: operationId: GetEntityStoreStats parameters: @@ -414,7 +414,7 @@ paths: summary: Get the Entity Store engine stats tags: - Security Solution Entity Analytics API - '/api/entity_store/engines/{entityType}/stop': + /api/entity_store/engines/{entityType}/stop: post: operationId: StopEntityStore parameters: diff --git a/x-pack/plugins/security_solution/docs/openapi/ess/security_solution_timeline_api_2023_10_31.bundled.schema.yaml b/x-pack/plugins/security_solution/docs/openapi/ess/security_solution_timeline_api_2023_10_31.bundled.schema.yaml index c5aa5c5385521..36b20f661d3f0 100644 --- a/x-pack/plugins/security_solution/docs/openapi/ess/security_solution_timeline_api_2023_10_31.bundled.schema.yaml +++ b/x-pack/plugins/security_solution/docs/openapi/ess/security_solution_timeline_api_2023_10_31.bundled.schema.yaml @@ -6,7 +6,7 @@ info: title: Security Solution Timeline API (Elastic Cloud and self-hosted) version: '2023-10-31' servers: - - url: 'http://{kibana_host}:{port}' + - url: http://{kibana_host}:{port} variables: kibana_host: default: localhost @@ -53,7 +53,7 @@ paths: summary: Delete a note tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution get: description: Get all notes for a given document. operationId: GetNotes @@ -99,7 +99,7 @@ paths: summary: Get notes tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution patch: description: Add a note to a Timeline or update an existing note. operationId: PersistNoteRoute @@ -164,7 +164,7 @@ paths: summary: Add or update a note tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution /api/pinned_event: patch: description: Pin an event to an existing Timeline. @@ -214,7 +214,7 @@ paths: summary: Pin an event tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution /api/timeline: delete: description: Delete one or more Timelines or Timeline templates. @@ -260,7 +260,7 @@ paths: summary: Delete Timelines or Timeline templates tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution get: description: Get the details of an existing saved Timeline or Timeline template. operationId: GetTimeline @@ -296,7 +296,7 @@ paths: summary: Get Timeline or Timeline template details tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution patch: description: >- Update an existing Timeline. You can update the title, description, date @@ -364,7 +364,7 @@ paths: summary: Update a Timeline tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution post: description: Create a new Timeline or Timeline template. operationId: CreateTimelines @@ -434,7 +434,7 @@ paths: summary: Create a Timeline or Timeline template tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution /api/timeline/_draft: get: description: >- @@ -472,7 +472,7 @@ paths: description: Indicates that the draft Timeline was successfully retrieved. '403': content: - 'application:json': + application:json: schema: type: object properties: @@ -486,7 +486,7 @@ paths: create a draft Timeline. '409': content: - 'application:json': + application:json: schema: type: object properties: @@ -501,7 +501,7 @@ paths: summary: Get draft Timeline or Timeline template details tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution post: description: > Create a clean draft Timeline or Timeline template for the current user. @@ -552,7 +552,7 @@ paths: Timeline is cleared and returned. '403': content: - 'application:json': + application:json: schema: type: object properties: @@ -565,7 +565,7 @@ paths: create a draft Timeline. '409': content: - 'application:json': + application:json: schema: type: object properties: @@ -579,7 +579,7 @@ paths: summary: Create a clean draft Timeline or Timeline template tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution /api/timeline/_export: post: description: Export Timelines as an NDJSON file. @@ -626,7 +626,7 @@ paths: summary: Export Timelines tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution /api/timeline/_favorite: patch: description: Favorite a Timeline or Timeline template for the current user. @@ -675,7 +675,7 @@ paths: description: Indicates the favorite status was successfully updated. '403': content: - 'application:json': + application:json: schema: type: object properties: @@ -689,7 +689,7 @@ paths: summary: Favorite a Timeline or Timeline template tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution /api/timeline/_import: post: description: Import Timelines. @@ -780,7 +780,7 @@ paths: summary: Import Timelines tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution /api/timeline/_prepackaged: post: description: Install or update prepackaged Timelines. @@ -825,7 +825,7 @@ paths: description: Indicates the installation of prepackaged Timelines was successful. '500': content: - 'application:json': + application:json: schema: type: object properties: @@ -839,7 +839,7 @@ paths: summary: Install prepackaged Timelines tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution /api/timeline/resolve: get: operationId: ResolveTimeline @@ -879,7 +879,7 @@ paths: summary: Get an existing saved Timeline or Timeline template tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution /api/timelines: get: description: Get a list of all saved Timelines or Timeline templates. @@ -971,7 +971,7 @@ paths: description: Indicates that the (template) Timelines were found and returned. '400': content: - 'application:json': + application:json: schema: type: object properties: @@ -983,7 +983,7 @@ paths: summary: Get Timelines or Timeline templates tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution components: schemas: BareNote: diff --git a/x-pack/plugins/security_solution/docs/openapi/serverless/security_solution_detections_api_2023_10_31.bundled.schema.yaml b/x-pack/plugins/security_solution/docs/openapi/serverless/security_solution_detections_api_2023_10_31.bundled.schema.yaml index 514c4c87405cd..4699de9a25228 100644 --- a/x-pack/plugins/security_solution/docs/openapi/serverless/security_solution_detections_api_2023_10_31.bundled.schema.yaml +++ b/x-pack/plugins/security_solution/docs/openapi/serverless/security_solution_detections_api_2023_10_31.bundled.schema.yaml @@ -7,7 +7,7 @@ info: title: Security Solution Detections API (Elastic Cloud Serverless) version: '2023-10-31' servers: - - url: 'http://{kibana_host}:{port}' + - url: http://{kibana_host}:{port} variables: kibana_host: default: localhost @@ -962,12 +962,12 @@ components: Interval in which the rule runs. For example, `"1h"` means the rule runs every hour. example: 1h - pattern: '^[1-9]\d*[smh]$' + pattern: ^[1-9]\d*[smh]$ type: string lookback: description: Lookback time for the rule example: 1h - pattern: '^[1-9]\d*[smh]$' + pattern: ^[1-9]\d*[smh]$ type: string required: - interval @@ -4143,9 +4143,9 @@ components: - no_actions - rule type: string - - description: 'Time interval in seconds, minutes, hours, or days.' + - description: Time interval in seconds, minutes, hours, or days. example: 1h - pattern: '^[1-9]\d*[smhd]$' + pattern: ^[1-9]\d*[smhd]$ type: string RuleAuthorArray: items: @@ -4381,7 +4381,7 @@ components: discriminator: propertyName: type RuleSignatureId: - description: 'Could be any string, not necessarily a UUID' + description: Could be any string, not necessarily a UUID type: string RuleSource: description: >- diff --git a/x-pack/plugins/security_solution/docs/openapi/serverless/security_solution_endpoint_management_api_2023_10_31.bundled.schema.yaml b/x-pack/plugins/security_solution/docs/openapi/serverless/security_solution_endpoint_management_api_2023_10_31.bundled.schema.yaml index ad4133a5fd9c6..24951f89d1bf1 100644 --- a/x-pack/plugins/security_solution/docs/openapi/serverless/security_solution_endpoint_management_api_2023_10_31.bundled.schema.yaml +++ b/x-pack/plugins/security_solution/docs/openapi/serverless/security_solution_endpoint_management_api_2023_10_31.bundled.schema.yaml @@ -4,7 +4,7 @@ info: title: Security Solution Endpoint Management API (Elastic Cloud Serverless) version: '2023-10-31' servers: - - url: 'http://{kibana_host}:{port}' + - url: http://{kibana_host}:{port} variables: kibana_host: default: localhost @@ -31,7 +31,7 @@ paths: summary: Get response actions tags: - Security Solution Endpoint Management API - '/api/endpoint/action_log/{agent_id}': + /api/endpoint/action_log/{agent_id}: get: deprecated: true description: Get an action request log for the specified agent ID. @@ -80,7 +80,7 @@ paths: summary: Get response actions status tags: - Security Solution Endpoint Management API - '/api/endpoint/action/{action_id}': + /api/endpoint/action/{action_id}: get: description: Get the details of a response action using the action ID. operationId: EndpointGetActionsDetails @@ -100,7 +100,7 @@ paths: summary: Get action details tags: - Security Solution Endpoint Management API - '/api/endpoint/action/{action_id}/file/{file_id}': + /api/endpoint/action/{action_id}/file/{file_id}: get: description: Get information for the specified file using the file ID. operationId: EndpointFileInfo @@ -125,7 +125,7 @@ paths: summary: Get file information tags: - Security Solution Endpoint Management API - '/api/endpoint/action/{action_id}/file/{file_id}/download': + /api/endpoint/action/{action_id}/file/{file_id}/download: get: description: Download a file from an endpoint. operationId: EndpointFileDownload @@ -310,7 +310,7 @@ paths: - Security Solution Endpoint Management API /api/endpoint/action/unisolate: post: - description: 'Release an isolated endpoint, allowing it to rejoin a network.' + description: Release an isolated endpoint, allowing it to rejoin a network. operationId: EndpointUnisolateAction requestBody: content: @@ -367,7 +367,7 @@ paths: summary: Get a metadata list tags: - Security Solution Endpoint Management API - '/api/endpoint/metadata/{id}': + /api/endpoint/metadata/{id}: get: operationId: GetEndpointMetadata parameters: @@ -447,7 +447,7 @@ paths: summary: Get an agent policy summary tags: - Security Solution Endpoint Management API - '/api/endpoint/protection_updates_note/{package_policy_id}': + /api/endpoint/protection_updates_note/{package_policy_id}: get: operationId: GetProtectionUpdatesNote parameters: @@ -493,7 +493,7 @@ paths: summary: Create or update a protection updates note tags: - Security Solution Endpoint Management API - '/api/endpoint/suggestions/{suggestion_type}': + /api/endpoint/suggestions/{suggestion_type}: post: operationId: GetEndpointSuggestions parameters: diff --git a/x-pack/plugins/security_solution/docs/openapi/serverless/security_solution_entity_analytics_api_2023_10_31.bundled.schema.yaml b/x-pack/plugins/security_solution/docs/openapi/serverless/security_solution_entity_analytics_api_2023_10_31.bundled.schema.yaml index 754c8f94d1c63..7506b8eb0d998 100644 --- a/x-pack/plugins/security_solution/docs/openapi/serverless/security_solution_entity_analytics_api_2023_10_31.bundled.schema.yaml +++ b/x-pack/plugins/security_solution/docs/openapi/serverless/security_solution_entity_analytics_api_2023_10_31.bundled.schema.yaml @@ -4,7 +4,7 @@ info: title: Security Solution Entity Analytics API (Elastic Cloud Serverless) version: '2023-10-31' servers: - - url: 'http://{kibana_host}:{port}' + - url: http://{kibana_host}:{port} variables: kibana_host: default: localhost @@ -182,7 +182,7 @@ paths: - Security Solution Entity Analytics API /api/asset_criticality/list: get: - description: 'List asset criticality records, paging, sorting and filtering as needed.' + description: List asset criticality records, paging, sorting and filtering as needed. operationId: FindAssetCriticalityRecords parameters: - description: The field to sort by. @@ -276,7 +276,7 @@ paths: summary: List the Entity Store engines tags: - Security Solution Entity Analytics API - '/api/entity_store/engines/{entityType}': + /api/entity_store/engines/{entityType}: delete: operationId: DeleteEntityStore parameters: @@ -324,7 +324,7 @@ paths: summary: Get the Entity Store engine tags: - Security Solution Entity Analytics API - '/api/entity_store/engines/{entityType}/init': + /api/entity_store/engines/{entityType}/init: post: operationId: InitEntityStore parameters: @@ -356,7 +356,7 @@ paths: summary: Initialize the Entity Store tags: - Security Solution Entity Analytics API - '/api/entity_store/engines/{entityType}/start': + /api/entity_store/engines/{entityType}/start: post: operationId: StartEntityStore parameters: @@ -379,7 +379,7 @@ paths: summary: Start the Entity Store engine tags: - Security Solution Entity Analytics API - '/api/entity_store/engines/{entityType}/stats': + /api/entity_store/engines/{entityType}/stats: post: operationId: GetEntityStoreStats parameters: @@ -414,7 +414,7 @@ paths: summary: Get the Entity Store engine stats tags: - Security Solution Entity Analytics API - '/api/entity_store/engines/{entityType}/stop': + /api/entity_store/engines/{entityType}/stop: post: operationId: StopEntityStore parameters: diff --git a/x-pack/plugins/security_solution/docs/openapi/serverless/security_solution_timeline_api_2023_10_31.bundled.schema.yaml b/x-pack/plugins/security_solution/docs/openapi/serverless/security_solution_timeline_api_2023_10_31.bundled.schema.yaml index 144ea915b9a2f..5c676bec03ef5 100644 --- a/x-pack/plugins/security_solution/docs/openapi/serverless/security_solution_timeline_api_2023_10_31.bundled.schema.yaml +++ b/x-pack/plugins/security_solution/docs/openapi/serverless/security_solution_timeline_api_2023_10_31.bundled.schema.yaml @@ -6,7 +6,7 @@ info: title: Security Solution Timeline API (Elastic Cloud Serverless) version: '2023-10-31' servers: - - url: 'http://{kibana_host}:{port}' + - url: http://{kibana_host}:{port} variables: kibana_host: default: localhost @@ -53,7 +53,7 @@ paths: summary: Delete a note tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution get: description: Get all notes for a given document. operationId: GetNotes @@ -99,7 +99,7 @@ paths: summary: Get notes tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution patch: description: Add a note to a Timeline or update an existing note. operationId: PersistNoteRoute @@ -164,7 +164,7 @@ paths: summary: Add or update a note tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution /api/pinned_event: patch: description: Pin an event to an existing Timeline. @@ -214,7 +214,7 @@ paths: summary: Pin an event tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution /api/timeline: delete: description: Delete one or more Timelines or Timeline templates. @@ -260,7 +260,7 @@ paths: summary: Delete Timelines or Timeline templates tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution get: description: Get the details of an existing saved Timeline or Timeline template. operationId: GetTimeline @@ -296,7 +296,7 @@ paths: summary: Get Timeline or Timeline template details tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution patch: description: >- Update an existing Timeline. You can update the title, description, date @@ -364,7 +364,7 @@ paths: summary: Update a Timeline tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution post: description: Create a new Timeline or Timeline template. operationId: CreateTimelines @@ -434,7 +434,7 @@ paths: summary: Create a Timeline or Timeline template tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution /api/timeline/_draft: get: description: >- @@ -472,7 +472,7 @@ paths: description: Indicates that the draft Timeline was successfully retrieved. '403': content: - 'application:json': + application:json: schema: type: object properties: @@ -486,7 +486,7 @@ paths: create a draft Timeline. '409': content: - 'application:json': + application:json: schema: type: object properties: @@ -501,7 +501,7 @@ paths: summary: Get draft Timeline or Timeline template details tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution post: description: > Create a clean draft Timeline or Timeline template for the current user. @@ -552,7 +552,7 @@ paths: Timeline is cleared and returned. '403': content: - 'application:json': + application:json: schema: type: object properties: @@ -565,7 +565,7 @@ paths: create a draft Timeline. '409': content: - 'application:json': + application:json: schema: type: object properties: @@ -579,7 +579,7 @@ paths: summary: Create a clean draft Timeline or Timeline template tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution /api/timeline/_export: post: description: Export Timelines as an NDJSON file. @@ -626,7 +626,7 @@ paths: summary: Export Timelines tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution /api/timeline/_favorite: patch: description: Favorite a Timeline or Timeline template for the current user. @@ -675,7 +675,7 @@ paths: description: Indicates the favorite status was successfully updated. '403': content: - 'application:json': + application:json: schema: type: object properties: @@ -689,7 +689,7 @@ paths: summary: Favorite a Timeline or Timeline template tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution /api/timeline/_import: post: description: Import Timelines. @@ -780,7 +780,7 @@ paths: summary: Import Timelines tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution /api/timeline/_prepackaged: post: description: Install or update prepackaged Timelines. @@ -825,7 +825,7 @@ paths: description: Indicates the installation of prepackaged Timelines was successful. '500': content: - 'application:json': + application:json: schema: type: object properties: @@ -839,7 +839,7 @@ paths: summary: Install prepackaged Timelines tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution /api/timeline/resolve: get: operationId: ResolveTimeline @@ -879,7 +879,7 @@ paths: summary: Get an existing saved Timeline or Timeline template tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution /api/timelines: get: description: Get a list of all saved Timelines or Timeline templates. @@ -971,7 +971,7 @@ paths: description: Indicates that the (template) Timelines were found and returned. '400': content: - 'application:json': + application:json: schema: type: object properties: @@ -983,7 +983,7 @@ paths: summary: Get Timelines or Timeline templates tags: - Security Solution Timeline API - - 'access:securitySolution' + - access:securitySolution components: schemas: BareNote: diff --git a/x-pack/plugins/security_solution/scripts/beat_docs/build.js b/x-pack/plugins/security_solution/scripts/beat_docs/build.js index 997416eaa8a3b..db766e6f738a6 100644 --- a/x-pack/plugins/security_solution/scripts/beat_docs/build.js +++ b/x-pack/plugins/security_solution/scripts/beat_docs/build.js @@ -138,7 +138,7 @@ const manageZipFields = async (beat, filePath, beatFields) => { try { await extract(filePath, { dir: beat.outputDir }); console.log('building fields', beat.index); - const obj = yaml.safeLoad( + const obj = yaml.load( fs.readFileSync(`${beat.outputDir}/winlogbeat-${BEATS_VERSION}-windows-x86_64/fields.yml`, { encoding: 'utf-8', }) @@ -172,7 +172,7 @@ const manageTarFields = async (beat, filePath, beatFields) => return reject(new Error(err)); } console.log('building fields', beat.index); - const obj = yaml.safeLoad( + const obj = yaml.load( fs.readFileSync(`${beat.outputDir}/fields.yml`, { encoding: 'utf-8' }) ); const ebeatFields = convertSchemaToHash(obj, beatFields); diff --git a/x-pack/plugins/security_solution/scripts/endpoint/common/elastic_agent_service.ts b/x-pack/plugins/security_solution/scripts/endpoint/common/elastic_agent_service.ts index 0e4f7572c806c..92dc2d6f8ab60 100644 --- a/x-pack/plugins/security_solution/scripts/endpoint/common/elastic_agent_service.ts +++ b/x-pack/plugins/security_solution/scripts/endpoint/common/elastic_agent_service.ts @@ -11,7 +11,7 @@ import type { KbnClient } from '@kbn/test'; import type { ToolingLog } from '@kbn/tooling-log'; import chalk from 'chalk'; import execa from 'execa'; -import { safeDump } from 'js-yaml'; +import { dump } from 'js-yaml'; import { fetchFleetServerUrl, getAgentVersionMatchingCurrentStack, @@ -111,7 +111,7 @@ export const startElasticAgentWithDocker = async ({ }) ).stdout; } catch (error) { - log.error(safeDump(error)); + log.error(dump(error)); throw error; } diff --git a/x-pack/test/fleet_api_integration/apis/epm/get_templates_inputs.ts b/x-pack/test/fleet_api_integration/apis/epm/get_templates_inputs.ts index 0f77bde3b15fa..a1eac19eed8b7 100644 --- a/x-pack/test/fleet_api_integration/apis/epm/get_templates_inputs.ts +++ b/x-pack/test/fleet_api_integration/apis/epm/get_templates_inputs.ts @@ -94,7 +94,7 @@ export default function (providerContext: FtrProviderContext) { metricsets: - status hosts: - - 'http://127.0.0.1' + - http://127.0.0.1 period: 10s server_status_path: /server-status `; diff --git a/x-pack/test/fleet_api_integration/apis/epm/install_by_upload.ts b/x-pack/test/fleet_api_integration/apis/epm/install_by_upload.ts index f2ca43c4c7e6d..30b2eacce0fb7 100644 --- a/x-pack/test/fleet_api_integration/apis/epm/install_by_upload.ts +++ b/x-pack/test/fleet_api_integration/apis/epm/install_by_upload.ts @@ -251,7 +251,7 @@ export default function (providerContext: FtrProviderContext) { .send(buf) .expect(400); expect((res.error as HTTPError).text).to.equal( - '{"statusCode":400,"error":"Bad Request","message":"Could not parse top-level package manifest at top-level directory apache-0.1.4: YAMLException: bad indentation of a mapping entry at line 2, column 7:\\n name: apache\\n ^."}' + '{"statusCode":400,"error":"Bad Request","message":"Could not parse top-level package manifest at top-level directory apache-0.1.4: YAMLException: bad indentation of a mapping entry (2:7)\\n\\n 1 | format_version: 1.0.0\\n 2 | name: apache\\n-----------^\\n 3 | title: Apache\\n 4 | version: 0.1.4."}' ); }); diff --git a/x-pack/test/observability_onboarding_api_integration/tests/elastic_agent/config.spec.ts b/x-pack/test/observability_onboarding_api_integration/tests/elastic_agent/config.spec.ts index 5a9f95ad25112..9a86035bb4409 100644 --- a/x-pack/test/observability_onboarding_api_integration/tests/elastic_agent/config.spec.ts +++ b/x-pack/test/observability_onboarding_api_integration/tests/elastic_agent/config.spec.ts @@ -6,7 +6,7 @@ */ import expect from '@kbn/expect'; -import { safeLoad } from 'js-yaml'; +import { load } from 'js-yaml'; import { FtrProviderContext } from '../../common/ftr_provider_context'; export default function ApiTest({ getService }: FtrProviderContext) { @@ -39,7 +39,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { expect(req.status).to.be(200); - const ymlConfig = safeLoad(req.text); + const ymlConfig = load(req.text); expect(ymlConfig.inputs[0].data_stream.namespace).to.be(''); expect(ymlConfig.inputs[0].streams[0].data_stream.dataset).to.be(''); expect(ymlConfig.inputs[0].streams[0].paths).to.be.empty(); @@ -75,7 +75,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { expect(req.status).to.be(200); - const ymlConfig = safeLoad(req.text); + const ymlConfig = load(req.text); expect(ymlConfig.inputs[0].data_stream.namespace).to.be(namespace); expect(ymlConfig.inputs[0].streams[0].data_stream.dataset).to.be(datasetName); expect(ymlConfig.inputs[0].streams[0].paths).to.be.eql([logFilepath]); @@ -107,7 +107,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { expect(req.status).to.be(200); - const ymlConfig = safeLoad(req.text); + const ymlConfig = load(req.text); expect(ymlConfig.inputs[0].data_stream.namespace).to.be('default'); expect(ymlConfig.inputs[0].streams.length).to.be(2); expect(ymlConfig.inputs[0].streams[0].data_stream.dataset).to.be('system.auth'); diff --git a/x-pack/test/security_solution_playwright/api_utils/api_key.ts b/x-pack/test/security_solution_playwright/api_utils/api_key.ts index e1f93c9937961..e53f62ba6e819 100644 --- a/x-pack/test/security_solution_playwright/api_utils/api_key.ts +++ b/x-pack/test/security_solution_playwright/api_utils/api_key.ts @@ -15,7 +15,7 @@ import { REPO_ROOT } from '@kbn/repo-info'; const getYamlData = (filePath: string): any => { const fileContents = fs.readFileSync(filePath, 'utf8'); - return yaml.safeLoad(fileContents); + return yaml.load(fileContents); }; const getRoleConfiguration = (role: string, filePath: string): any => { diff --git a/x-pack/test_serverless/shared/lib/security/kibana_roles/kibana_roles.ts b/x-pack/test_serverless/shared/lib/security/kibana_roles/kibana_roles.ts index a2d244072de87..47969d1643eff 100644 --- a/x-pack/test_serverless/shared/lib/security/kibana_roles/kibana_roles.ts +++ b/x-pack/test_serverless/shared/lib/security/kibana_roles/kibana_roles.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { safeLoad as loadYaml } from 'js-yaml'; +import { load as loadYaml } from 'js-yaml'; import { readFileSync } from 'fs'; import * as path from 'path'; import { cloneDeep, merge } from 'lodash'; diff --git a/yarn.lock b/yarn.lock index d4c06d61f9a02..bc436411c2bc8 100644 --- a/yarn.lock +++ b/yarn.lock @@ -10706,10 +10706,10 @@ resolved "https://registry.yarnpkg.com/@types/js-search/-/js-search-1.4.0.tgz#f2d4afa176a4fc7b17fb46a1593847887fa1fb7b" integrity sha1-8tSvoXak/HsX+0ahWThHiH+h+3s= -"@types/js-yaml@^3.11.1": - version "3.12.1" - resolved "https://registry.yarnpkg.com/@types/js-yaml/-/js-yaml-3.12.1.tgz#5c6f4a1eabca84792fbd916f0cb40847f123c656" - integrity sha512-SGGAhXLHDx+PK4YLNcNGa6goPf9XRWQNAUUbffkwVGGXIxmDKWyGGL4inzq2sPmExu431Ekb9aEMn9BkPqEYFA== +"@types/js-yaml@^4.0.9": + version "4.0.9" + resolved "https://registry.yarnpkg.com/@types/js-yaml/-/js-yaml-4.0.9.tgz#cd82382c4f902fed9691a2ed79ec68c5898af4c2" + integrity sha512-k4MGaQl5TGo/iipqb2UDG2UwjXziSWkh0uysQelTlJpX1qGlpUZYm8PnO4DxG1qBomtJUdYJ6qR6xdIah10JLg== "@types/jsdom@^20.0.0", "@types/jsdom@^20.0.1": version "20.0.1" @@ -21696,7 +21696,7 @@ js-yaml@4.1.0, js-yaml@^4.1.0: dependencies: argparse "^2.0.1" -js-yaml@^3.13.1, js-yaml@^3.14.1: +js-yaml@^3.13.1: version "3.14.1" resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.14.1.tgz#dae812fdb3825fa306609a8717383c50c36a0537" integrity sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==