Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consume elasticsearch.publicBaseUrl where possible #192741

Merged
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const createOpts = async (props: KibanaConnectionDetailsProviderProps) => {
const { http, docLinks, analytics } = start.core;
const locator = start.plugins?.share?.url?.locators.get('MANAGEMENT_APP_LOCATOR');
const manageKeysLink = await locator?.getUrl({ sectionId: 'security', appId: 'api_keys' });
const elasticsearchConfig = await start.plugins?.cloud?.fetchElasticsearchConfig();
const result: ConnectionDetailsOpts = {
...options,
navigateToUrl: start.core.application
Expand All @@ -35,7 +36,7 @@ const createOpts = async (props: KibanaConnectionDetailsProviderProps) => {
},
endpoints: {
id: start.plugins?.cloud?.cloudId,
url: start.plugins?.cloud?.elasticsearchUrl,
url: elasticsearchConfig?.elasticsearchUrl,
cloudIdLearMoreLink: docLinks?.links?.cloud?.beatsAndLogstashConfiguration,
...options?.endpoints,
},
Expand Down
15 changes: 11 additions & 4 deletions packages/cloud/deployment_details/services.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/

import React, { FC, PropsWithChildren, useContext } from 'react';
import React, { FC, PropsWithChildren, useContext, useEffect } from 'react';

export interface DeploymentDetailsContextValue {
cloudId?: string;
Expand Down Expand Up @@ -58,7 +57,7 @@ export interface DeploymentDetailsKibanaDependencies {
cloud: {
isCloudEnabled: boolean;
cloudId?: string;
elasticsearchUrl?: string;
fetchElasticsearchConfig: () => Promise<{ elasticsearchUrl?: string }>;
};
/** DocLinksStart contract */
docLinks: {
Expand All @@ -79,11 +78,19 @@ export interface DeploymentDetailsKibanaDependencies {
export const DeploymentDetailsKibanaProvider: FC<
PropsWithChildren<DeploymentDetailsKibanaDependencies>
> = ({ children, ...services }) => {
const [elasticsearchUrl, setElasticsearchUrl] = React.useState<string>('');

useEffect(() => {
services.cloud.fetchElasticsearchConfig().then((config) => {
setElasticsearchUrl(config.elasticsearchUrl || '');
});
}, [services.cloud]);

const {
core: {
application: { navigateToUrl },
},
cloud: { isCloudEnabled, cloudId, elasticsearchUrl },
cloud: { isCloudEnabled, cloudId },
share: {
url: { locators },
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ test('set correct defaults', () => {
"maxSockets": 800,
"password": undefined,
"pingTimeout": "PT30S",
"publicBaseUrl": undefined,
"requestHeadersWhitelist": Array [
"authorization",
"es-client-authentication",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,13 @@ export class ElasticsearchConfig implements IElasticsearchConfig {
*/
public readonly hosts: string[];

/**
* Optional host that users can use to connect to your Elasticsearch cluster,
* this URL will be shown in Kibana as the Elasticsearch URL
*/

public readonly publicBaseUrl?: string;

/**
* List of Kibana client-side headers to send to Elasticsearch when request
* scoped cluster client is used. If this is an empty array then *no* client-side
Expand Down Expand Up @@ -473,6 +480,7 @@ export class ElasticsearchConfig implements IElasticsearchConfig {
this.skipStartupConnectionCheck = rawConfig.skipStartupConnectionCheck;
this.apisToRedactInLogs = rawConfig.apisToRedactInLogs;
this.dnsCacheTtl = rawConfig.dnsCacheTtl;
this.publicBaseUrl = rawConfig.publicBaseUrl;

const { alwaysPresentCertificate, verificationMode } = rawConfig.ssl;
const { key, keyPassphrase, certificate, certificateAuthorities } = readKeyAndCerts(rawConfig);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ export class ElasticsearchService
agentStatsProvider: {
getAgentsStats: agentManager.getAgentsStats.bind(agentManager),
},
publicBaseUrl: config.publicBaseUrl,
};
}

Expand Down Expand Up @@ -194,6 +195,7 @@ export class ElasticsearchService
metrics: {
elasticsearchWaitTime,
},
publicBaseUrl: config.publicBaseUrl,
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,12 @@ export interface ElasticsearchServiceStart {
* Returns the capabilities for the default cluster.
*/
getCapabilities: () => ElasticsearchCapabilities;

/**
* The public base URL (if any) that should be used by end users to access the Elasticsearch cluster.
*/

readonly publicBaseUrl?: string;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@ export function createPluginSetupContext<TPlugin, TPluginDependencies>({
docLinks: deps.docLinks,
elasticsearch: {
legacy: deps.elasticsearch.legacy,
publicBaseUrl: deps.elasticsearch.publicBaseUrl,
setUnauthorizedErrorHandler: deps.elasticsearch.setUnauthorizedErrorHandler,
},
executionContext: {
Expand Down
2 changes: 2 additions & 0 deletions x-pack/plugins/cloud/common/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,5 @@ export const ELASTIC_SUPPORT_LINK = 'https://support.elastic.co/';
* This is the page for managing your snapshots on Cloud.
*/
export const CLOUD_SNAPSHOTS_PATH = 'elasticsearch/snapshots/';

export const ELASTICSEARCH_CONFIG_ROUTE = '/api/internal/elasticsearch_config';
sphilipse marked this conversation as resolved.
Show resolved Hide resolved
4 changes: 4 additions & 0 deletions x-pack/plugins/cloud/common/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,7 @@
*/

export type OnBoardingDefaultSolution = 'es' | 'oblt' | 'security';

export interface ElasticsearchConfigType {
elasticsearch_url: string;
}
5 changes: 4 additions & 1 deletion x-pack/plugins/cloud/public/mocks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ function createSetupMock(): jest.Mocked<CloudSetup> {
deploymentUrl: 'deployment-url',
profileUrl: 'profile-url',
organizationUrl: 'organization-url',
elasticsearchUrl: 'elasticsearch-url',
fetchElasticsearchConfig: jest
.fn()
.mockResolvedValue({ elasticsearchUrl: 'elasticsearch-url' }),
kibanaUrl: 'kibana-url',
cloudHost: 'cloud-host',
cloudDefaultPort: '443',
Expand Down Expand Up @@ -53,6 +55,7 @@ const createStartMock = (): jest.Mocked<CloudStart> => ({
serverless: {
projectId: undefined,
},
fetchElasticsearchConfig: jest.fn().mockResolvedValue({ elasticsearchUrl: 'elasticsearch-url' }),
});

export const cloudMock = {
Expand Down
17 changes: 15 additions & 2 deletions x-pack/plugins/cloud/public/plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ describe('Cloud Plugin', () => {
const plugin = new CloudPlugin(initContext);

const coreSetup = coreMock.createSetup();
coreSetup.http.get.mockResolvedValue({ elasticsearch_url: 'elasticsearch-url' });
const setup = plugin.setup(coreSetup);

return { setup };
Expand Down Expand Up @@ -110,8 +111,8 @@ describe('Cloud Plugin', () => {
it('exposes components decoded from the cloudId', () => {
const decodedId: DecodedCloudId = {
defaultPort: '9000',
host: 'host',
elasticsearchUrl: 'elasticsearch-url',
host: 'host',
kibanaUrl: 'kibana-url',
};
decodeCloudIdMock.mockReturnValue(decodedId);
Expand All @@ -120,7 +121,6 @@ describe('Cloud Plugin', () => {
expect.objectContaining({
cloudDefaultPort: '9000',
cloudHost: 'host',
elasticsearchUrl: 'elasticsearch-url',
kibanaUrl: 'kibana-url',
})
);
Expand Down Expand Up @@ -184,6 +184,11 @@ describe('Cloud Plugin', () => {
});
expect(setup.serverless.projectType).toBe('security');
});
it('exposes fetchElasticsearchConfig', async () => {
const { setup } = setupPlugin();
const result = await setup.fetchElasticsearchConfig();
expect(result).toEqual({ elasticsearchUrl: 'elasticsearch-url' });
});
});
});

Expand Down Expand Up @@ -307,5 +312,13 @@ describe('Cloud Plugin', () => {
const start = plugin.start(coreStart);
expect(start.serverless.projectName).toBe('My Awesome Project');
});
it('exposes fetchElasticsearchConfig', async () => {
const { plugin } = startPlugin();
const coreStart = coreMock.createStart();
coreStart.http.get.mockResolvedValue({ elasticsearch_url: 'elasticsearch-url' });
const start = plugin.start(coreStart);
const result = await start.fetchElasticsearchConfig();
expect(result).toEqual({ elasticsearchUrl: 'elasticsearch-url' });
});
});
});
27 changes: 24 additions & 3 deletions x-pack/plugins/cloud/public/plugin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@ import { CLOUD_SNAPSHOTS_PATH } from '../common/constants';
import { decodeCloudId, type DecodedCloudId } from '../common/decode_cloud_id';
import { getFullCloudUrl } from '../common/utils';
import { parseOnboardingSolution } from '../common/parse_onboarding_default_solution';
import type { CloudSetup, CloudStart } from './types';
import type { CloudSetup, CloudStart, PublicElasticsearchConfigType } from './types';
import { getSupportUrl } from './utils';
import { ElasticsearchConfigType } from '../common/types';

export interface CloudConfigType {
id?: string;
Expand Down Expand Up @@ -66,12 +67,14 @@ export class CloudPlugin implements Plugin<CloudSetup> {
private readonly isServerlessEnabled: boolean;
private readonly contextProviders: Array<FC<PropsWithChildren<unknown>>> = [];
private readonly logger: Logger;
private elasticsearchUrl?: string;

constructor(private readonly initializerContext: PluginInitializerContext) {
this.config = this.initializerContext.config.get<CloudConfigType>();
this.isCloudEnabled = getIsCloudEnabled(this.config.id);
this.isServerlessEnabled = !!this.config.serverless?.project_id;
this.logger = initializerContext.logger.get();
this.elasticsearchUrl = undefined;
}

public setup(core: CoreSetup): CloudSetup {
Expand Down Expand Up @@ -99,7 +102,6 @@ export class CloudPlugin implements Plugin<CloudSetup> {
csp,
baseUrl,
...this.getCloudUrls(),
elasticsearchUrl: decodedId?.elasticsearchUrl,
kibanaUrl: decodedId?.kibanaUrl,
cloudHost: decodedId?.host,
cloudDefaultPort: decodedId?.defaultPort,
Expand All @@ -119,6 +121,7 @@ export class CloudPlugin implements Plugin<CloudSetup> {
registerCloudService: (contextProvider) => {
this.contextProviders.push(contextProvider);
},
fetchElasticsearchConfig: this.fetchElasticsearchConfig.bind(this, core.http),
};
}

Expand Down Expand Up @@ -166,7 +169,6 @@ export class CloudPlugin implements Plugin<CloudSetup> {
profileUrl,
organizationUrl,
projectsUrl,
elasticsearchUrl: decodedId?.elasticsearchUrl,
kibanaUrl: decodedId?.kibanaUrl,
isServerlessEnabled: this.isServerlessEnabled,
serverless: {
Expand All @@ -176,6 +178,7 @@ export class CloudPlugin implements Plugin<CloudSetup> {
},
performanceUrl,
usersAndRolesUrl,
fetchElasticsearchConfig: this.fetchElasticsearchConfig.bind(this, coreStart.http),
};
}

Expand Down Expand Up @@ -216,4 +219,22 @@ export class CloudPlugin implements Plugin<CloudSetup> {
projectsUrl: fullCloudProjectsUrl,
};
}

private async fetchElasticsearchConfig(
http: CoreStart['http']
): Promise<PublicElasticsearchConfigType> {
if (this.elasticsearchUrl) {
return { elasticsearchUrl: this.elasticsearchUrl };
}
try {
const result = await http.get<ElasticsearchConfigType>('/api/internal/elasticsearch_config');
this.elasticsearchUrl = result.elasticsearch_url;
sphilipse marked this conversation as resolved.
Show resolved Hide resolved
return { elasticsearchUrl: result.elasticsearch_url };
} catch {
this.logger.error('Failed to fetch Elasticsearch config');
return {
elasticsearchUrl: undefined,
};
}
}
}
12 changes: 8 additions & 4 deletions x-pack/plugins/cloud/public/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,9 @@ export interface CloudStart {
*/
projectsUrl?: string;
/**
* The full URL to the elasticsearch cluster.
* Fetches the full URL to the elasticsearch cluster.
*/
elasticsearchUrl?: string;
fetchElasticsearchConfig: () => Promise<PublicElasticsearchConfigType>;
sphilipse marked this conversation as resolved.
Show resolved Hide resolved
/**
* The full URL to the Kibana deployment.
*/
Expand Down Expand Up @@ -150,9 +150,9 @@ export interface CloudSetup {
*/
snapshotsUrl?: string;
/**
* The full URL to the elasticsearch cluster.
* Fetches the full URL to the elasticsearch cluster.
*/
elasticsearchUrl?: string;
fetchElasticsearchConfig: () => Promise<PublicElasticsearchConfigType>;
/**
* The full URL to the Kibana deployment.
*/
Expand Down Expand Up @@ -225,3 +225,7 @@ export interface CloudSetup {
orchestratorTarget?: string;
};
}

sphilipse marked this conversation as resolved.
Show resolved Hide resolved
export interface PublicElasticsearchConfigType {
elasticsearchUrl?: string;
}
6 changes: 5 additions & 1 deletion x-pack/plugins/cloud/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { decodeCloudId, DecodedCloudId } from '../common/decode_cloud_id';
import { parseOnboardingSolution } from '../common/parse_onboarding_default_solution';
import { getFullCloudUrl } from '../common/utils';
import { readInstanceSizeMb } from './env';
import { defineRoutes } from './routes/elasticsearch_routes';

interface PluginsSetup {
usageCollection?: UsageCollectionSetup;
Expand Down Expand Up @@ -201,6 +202,9 @@ export class CloudPlugin implements Plugin<CloudSetup, CloudStart> {
if (this.config.id) {
decodedId = decodeCloudId(this.config.id, this.logger);
}
const router = core.http.createRouter();
const elasticsearchUrl = core.elasticsearch.publicBaseUrl || decodedId?.elasticsearchUrl;
defineRoutes({ logger: this.logger, router, elasticsearchUrl });

return {
...this.getCloudUrls(),
Expand All @@ -209,7 +213,7 @@ export class CloudPlugin implements Plugin<CloudSetup, CloudStart> {
organizationId,
instanceSizeMb: readInstanceSizeMb(),
deploymentId,
elasticsearchUrl: core.elasticsearch.publicBaseUrl || decodedId?.elasticsearchUrl,
elasticsearchUrl,
kibanaUrl: decodedId?.kibanaUrl,
cloudHost: decodedId?.host,
cloudDefaultPort: decodedId?.defaultPort,
Expand Down
37 changes: 37 additions & 0 deletions x-pack/plugins/cloud/server/routes/elasticsearch_routes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* 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; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { IRouter } from '@kbn/core/server';
import { Logger } from '@kbn/logging';
import { ElasticsearchConfigType } from '../../common/types';
import { ELASTICSEARCH_CONFIG_ROUTE } from '../../common/constants';

export function defineRoutes({
elasticsearchUrl,
logger,
router,
}: {
elasticsearchUrl?: string;
logger: Logger;
router: IRouter;
}) {
router.get(
sphilipse marked this conversation as resolved.
Show resolved Hide resolved
{
path: ELASTICSEARCH_CONFIG_ROUTE,
validate: {},
},
sphilipse marked this conversation as resolved.
Show resolved Hide resolved
async (context, request, response) => {
const body: ElasticsearchConfigType = {
elasticsearch_url: elasticsearchUrl || '',
};
return response.ok({
body,
headers: { 'content-type': 'application/json' },
sphilipse marked this conversation as resolved.
Show resolved Hide resolved
});
}
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ describe('AnalyticsCollectionIntegrate', () => {
.toMatchInlineSnapshot(`
"<script type=\\"text/javascript\\">
window.elasticAnalytics.createTracker({
endpoint: \\"elasticsearch-url\\",
endpoint: \\"https://localhost:9200\\",
collectionName: \\"example\\",
apiKey: \\"########\\",
// Optional: sampling rate percentage: 0-1, 0 = no events, 1 = all events
Expand Down
Loading