kibana/examples/preboot_example/server/plugin.ts
Pierre Gayvallet 6627bd8b3a
Elasticsearch client: no longer default to using meta: true (#124488)
* Use `Client` interface instead of `KibanaClient`

* get rid of getKibanaEsClient and convertToKibanaClient

* get rid of last KibanaClient usages

* update usages and types in @kbn/securitysolution-es-utils

* fix some violations

* add sugar method around client mock

* update SO repository calls

* adapt more core usages

* export mock types

* batch 1

* batch 2

* batch 3

* batch 4

* batch 5

* batch 6

* batch 7

* batch 8

* batch 9

* security - batch 1

* security - batch 2

* security - batch 3

* last batch of initial violations

* fix resolve_time_pattern

* update generated doc

* fix /internal/index-pattern-management/preview_scripted_field endpoint

* fix monitoring's getLegacyClusterShim

* fix /api/snapshot_restore/privileges route

* fix UptimeESClient

* fix transforms/_nodes endpoint

* lint

* unit test fix - batch 1

* unit test fix - batch 2

* unit test fix - batch 3

* integration test fix - batch 1

* lint

* adapt ML client

* unit test fix - batch 4

* fix uptime test helper

* fix /api/transform/transforms/{transformId}/_update route

* fix ES client FTR test

* fix uptime unit test

* fix type errors on last unit tests

* fix RollupSearchStrategy call

* fix /internal/security/fields/{query} route

* fix GET /api/index_lifecycle_management/policies route

* fix mlClient.getDataFrameAnalytics

* fix APMEventClient

* fix security solution getBootstrapIndexExists

* fix data_enhanced's getSearchStatus

* remove unused @ts-expect-error

* fix unit tests due to latest code changes

* fix more calls in security_solution routes

* fix more calls in ml routes

* fix POST /api/index_management/component_templates route

* fix unit tests due to latest changes

* fix rule_registry's ResourceInstaller.createOrUpdateIndexTemplate

* fix more fleet client calls

* fix UA's GET cloud_backup_status route

* fix createLifecycleExecutorApiTest

* fix hasFleetServers

* fix unit tests due to latest changes

* changes due to last merge

* fix ml modelProvider.getModelsPipelines

* fix security_solution LifecycleQuery.search

* fix new CoreUsageDataService usage

* fix security solution's StatsQuery.search

* improve ml FTR assertions

* fix security_solution's EventsQuery.search

* fix EsClient type as we're keeping transport

* NITs

* clean RepositoryEsClient type

* update generated doc

* review comments

* adapt mlClient.anomalySearch signature

* remove unnecessary .then((body) => body)

* nit

* add unit tests for the client mocking functions

* fix new upgrade assistant /remote_clusters endpoint
2022-02-12 09:19:44 +01:00

135 lines
4.2 KiB
TypeScript

/*
* 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 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 or the Server
* Side Public License, v 1.
*/
import { schema } from '@kbn/config-schema';
import type { CorePreboot, PrebootPlugin, PluginInitializerContext } from 'src/core/server';
import fs from 'fs/promises';
import { errors } from '@elastic/elasticsearch';
import Boom from '@hapi/boom';
import type { ConfigType } from './config';
export function getDetailedErrorMessage(error: any): string {
if (error instanceof errors.ResponseError) {
return JSON.stringify(error.body);
}
if (Boom.isBoom(error)) {
return JSON.stringify(error.output.payload);
}
return error.message;
}
export class PrebootExamplePlugin implements PrebootPlugin {
readonly #initializerContext: PluginInitializerContext<ConfigType>;
constructor(initializerContext: PluginInitializerContext<ConfigType>) {
this.#initializerContext = initializerContext;
}
public setup(core: CorePreboot) {
const { skipSetup } = this.#initializerContext.config.get<ConfigType>();
let completeSetup: (result: { shouldReloadConfig: boolean }) => void;
core.http.registerRoutes('', (prebootRouter) => {
prebootRouter.get(
{
path: '/api/preboot/state',
validate: false,
options: { authRequired: false },
},
(_, request, response) => {
const isSetupModeActive = !skipSetup && core.preboot.isSetupOnHold();
return response.ok({ body: { isSetupModeActive } });
}
);
if (skipSetup) {
return;
}
prebootRouter.post(
{
path: '/api/preboot/complete_setup',
validate: {
body: schema.object({ shouldReloadConfig: schema.boolean() }),
},
options: { authRequired: false },
},
(_, request, response) => {
completeSetup({ shouldReloadConfig: request.body.shouldReloadConfig });
return response.noContent();
}
);
prebootRouter.post(
{
path: '/api/preboot/write_config',
validate: {
body: schema.object({ key: schema.string(), value: schema.string() }),
},
options: { authRequired: false },
},
async (_, request, response) => {
const configPath = this.#initializerContext.env.configs.find((path) =>
path.includes('dev')
);
if (!configPath) {
return response.customError({ statusCode: 500, body: 'Cannot find dev config.' });
}
await fs.appendFile(configPath, `${request.body.key}: ${request.body.value}\n`);
return response.noContent();
}
);
prebootRouter.post(
{
path: '/api/preboot/connect_to_es',
validate: {
body: schema.object({
host: schema.string(),
username: schema.string(),
password: schema.string(),
}),
},
options: { authRequired: false },
},
async (_, request, response) => {
const esClient = core.elasticsearch.createClient('data', {
hosts: [request.body.host],
});
const scopedClient = esClient.asScoped({
headers: {
authorization: `Basic ${Buffer.from(
`${request.body.username}:${request.body.password}`
).toString('base64')}`,
},
});
try {
return response.ok({
body: await scopedClient.asCurrentUser.security.authenticate(),
});
} catch (err) {
return response.customError({ statusCode: 500, body: getDetailedErrorMessage(err) });
}
}
);
core.preboot.holdSetupUntilResolved(
'Elasticsearch connection is not set up',
new Promise<{ shouldReloadConfig: boolean }>((resolve) => {
completeSetup = resolve;
})
);
});
}
public stop() {}
}