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

[CLOUD-UI] Cloud onboarding token #198444

Merged
merged 21 commits into from
Nov 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
2342a07
wip add api integration test
XavierM Aug 27, 2024
22943b6
add api to save onboarding data
XavierM Oct 30, 2024
d816fdb
Merge branch 'main' of github.com:elastic/kibana into cloud-onboardin…
XavierM Oct 30, 2024
ff3d392
fixes + wip test
XavierM Oct 31, 2024
7e88c33
Merge branch 'main' of github.com:elastic/kibana into cloud-onboardin…
XavierM Oct 31, 2024
0c8fc14
APi integration test working
XavierM Nov 4, 2024
5d730a2
Merge branch 'main' into cloud-onboarding-token
TinaHeiligers Nov 4, 2024
54b7b16
add unit tets for post
XavierM Nov 4, 2024
0381ee2
Merge branch 'main' of github.com:elastic/kibana into cloud-onboardin…
XavierM Nov 4, 2024
7ca6a13
Merge branch 'cloud-onboarding-token' of github.com:XavierM/kibana in…
XavierM Nov 5, 2024
52a5a5a
fix hidden + type
XavierM Nov 5, 2024
478af3e
[CI] Auto-commit changed files from 'node scripts/notice'
kibanamachine Nov 5, 2024
bd27c5c
[CI] Auto-commit changed files from 'node scripts/check_mappings_upda…
kibanamachine Nov 5, 2024
9d52b80
[CI] Auto-commit changed files from 'node scripts/jest_integration -u…
kibanamachine Nov 5, 2024
7824961
fix integration test
XavierM Nov 5, 2024
fb861fc
Merge branch 'cloud-onboarding-token' of github.com:XavierM/kibana in…
XavierM Nov 5, 2024
e28128e
wrong file
XavierM Nov 5, 2024
8fd0e4d
fix privileges
XavierM Nov 7, 2024
7580bea
Merge branch 'main' of github.com:elastic/kibana into cloud-onboardin…
XavierM Nov 7, 2024
8195fb7
Merge branch 'main' of github.com:elastic/kibana into cloud-onboardin…
XavierM Nov 13, 2024
197da3d
Merge branch 'main' into cloud-onboarding-token
XavierM Nov 19, 2024
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
1 change: 1 addition & 0 deletions .buildkite/ftr_platform_stateful_configs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -375,3 +375,4 @@ enabled:
- x-pack/test/custom_branding/config.ts
# stateful config files that run deployment-agnostic tests
- x-pack/test/api_integration/deployment_agnostic/configs/stateful/platform.stateful.config.ts
- x-pack/test/api_integration/apis/cloud/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,7 @@
"payload.connector.type",
"type"
],
"cloud": [],
"cloud-security-posture-settings": [],
"config": [
"buildNum"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -788,6 +788,10 @@
}
}
},
"cloud": {
"dynamic": false,
"properties": {}
},
"cloud-security-posture-settings": {
"dynamic": false,
"properties": {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ describe('checking migration metadata changes on all registered SO types', () =>
"cases-rules": "6d1776f5c46a99e1a0f3085c537146c1cdfbc829",
"cases-telemetry": "f219eb7e26772884342487fc9602cfea07b3cedc",
"cases-user-actions": "483f10db9b3bd1617948d7032a98b7791bf87414",
"cloud": "b549f4f7ab1fd41aab366a66afa52a2a008aefea",
"cloud-security-posture-settings": "e0f61c68bbb5e4cfa46ce8994fa001e417df51ca",
"config": "179b3e2bc672626aafce3cf92093a113f456af38",
"config-global": "8e8a134a2952df700d7d4ec51abb794bbd4cf6da",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ const previouslyRegisteredTypes = [
'canvas-element',
'canvas-workpad',
'canvas-workpad-template',
'cloud',
'cloud-security-posture-settings',
'cases',
'cases-comments',
Expand Down
14 changes: 11 additions & 3 deletions x-pack/plugins/cloud/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type { Logger } from '@kbn/logging';
import type { CoreSetup, Plugin, PluginInitializerContext } from '@kbn/core/server';
import type { UsageCollectionSetup } from '@kbn/usage-collection-plugin/server';
import type { SolutionId } from '@kbn/core-chrome-browser';

import { registerCloudDeploymentMetadataAnalyticsContext } from '../common/register_cloud_deployment_id_analytics_context';
import type { CloudConfigType } from './config';
import { registerCloudUsageCollector } from './collectors';
Expand All @@ -18,7 +19,9 @@ 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';
import { defineRoutes } from './routes';
import { CloudRequestHandlerContext } from './routes/types';
import { setupSavedObjects } from './saved_objects';

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

setupSavedObjects(core.savedObjects, this.logger);
return {
...this.getCloudUrls(),
cloudId: this.config.id,
Expand Down
8 changes: 8 additions & 0 deletions x-pack/plugins/cloud/server/routes/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
* 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.
*/

export const CLOUD_DATA_SAVED_OBJECT_ID = 'cloud-data-saved-object-id';
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { Logger } from '@kbn/logging';
import { ElasticsearchConfigType } from '../../common/types';
import { ELASTICSEARCH_CONFIG_ROUTE } from '../../common/constants';

export function defineRoutes({
export function setElasticsearchRoute({
elasticsearchUrl,
logger,
router,
Expand Down
43 changes: 43 additions & 0 deletions x-pack/plugins/cloud/server/routes/get_cloud_data_route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* 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 { RouteOptions } from '.';
import { CLOUD_DATA_SAVED_OBJECT_ID } from './constants';
import { CLOUD_DATA_SAVED_OBJECT_TYPE } from '../saved_objects';
import { CloudDataAttributes } from './types';

export const setGetCloudSolutionDataRoute = ({ router }: RouteOptions) => {
router.versioned
.get({
path: `/internal/cloud/solution`,
access: 'internal',
summary: 'Get cloud data for solutions',
})
.addVersion(
{
version: '1',
validate: {
request: {},
},
},
async (context, request, response) => {
const coreContext = await context.core;
const savedObjectsClient = coreContext.savedObjects.getClient({
includedHiddenTypes: [CLOUD_DATA_SAVED_OBJECT_TYPE],
});
try {
const cloudDataSo = await savedObjectsClient.get<CloudDataAttributes>(
CLOUD_DATA_SAVED_OBJECT_TYPE,
CLOUD_DATA_SAVED_OBJECT_ID
);
return response.ok({ body: cloudDataSo?.attributes ?? null });
} catch (error) {
return response.customError(error);
}
}
);
};
27 changes: 27 additions & 0 deletions x-pack/plugins/cloud/server/routes/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
* 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 { setPostCloudSolutionDataRoute } from './set_cloud_data_route';
import { CloudRequestHandlerContext } from './types';
import { setElasticsearchRoute } from './elasticsearch_route';
import { setGetCloudSolutionDataRoute } from './get_cloud_data_route';

export interface RouteOptions {
logger: Logger;
router: IRouter<CloudRequestHandlerContext>;
elasticsearchUrl?: string;
}

export function defineRoutes(opts: RouteOptions) {
const { logger, elasticsearchUrl, router } = opts;

setElasticsearchRoute({ logger, elasticsearchUrl, router });
setGetCloudSolutionDataRoute({ logger, router });
setPostCloudSolutionDataRoute({ logger, router });
}
119 changes: 119 additions & 0 deletions x-pack/plugins/cloud/server/routes/set_cloud_data_route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
/*
* 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 { httpServerMock, httpServiceMock } from '@kbn/core/server/mocks';
import {
RequestHandlerContext,
RouteValidatorConfig,
SavedObjectsErrorHelpers,
kibanaResponseFactory,
} from '@kbn/core/server';
import { CLOUD_DATA_SAVED_OBJECT_TYPE } from '../saved_objects';
import { CLOUD_DATA_SAVED_OBJECT_ID } from './constants';
import { setPostCloudSolutionDataRoute } from './set_cloud_data_route';
import { RouteOptions } from '.';

const mockSavedObjectsClientGet = jest.fn();
const mockSavedObjectsClientCreate = jest.fn();
const mockSavedObjectsClientUpdate = jest.fn();

const mockRouteContext = {
core: {
savedObjects: {
getClient: () => ({
get: mockSavedObjectsClientGet,
create: mockSavedObjectsClientCreate,
update: mockSavedObjectsClientUpdate,
}),
},
},
} as unknown as RequestHandlerContext;

describe('POST /internal/cloud/solution', () => {
const setup = async () => {
const httpService = httpServiceMock.createSetupContract();
const router = httpService.createRouter();

setPostCloudSolutionDataRoute({
router,
} as unknown as RouteOptions);

const [routeDefinition, routeHandler] =
router.versioned.post.mock.results[0].value.addVersion.mock.calls[0];

return {
routeValidation: routeDefinition.validate as RouteValidatorConfig<{}, {}, {}>,
routeHandler,
};
};
beforeEach(() => {
jest.clearAllMocks();
});

it('should create cloud data if it does not exist', async () => {
const { routeHandler } = await setup();

mockSavedObjectsClientGet.mockRejectedValue(
SavedObjectsErrorHelpers.createGenericNotFoundError()
);

const request = httpServerMock.createKibanaRequest({
body: {
onboardingData: {
solutionType: 'security',
token: 'test-token',
},
},
method: 'post',
});

await routeHandler(mockRouteContext, request, kibanaResponseFactory);

expect(mockSavedObjectsClientGet).toHaveBeenCalledWith(
CLOUD_DATA_SAVED_OBJECT_TYPE,
CLOUD_DATA_SAVED_OBJECT_ID
);
expect(mockSavedObjectsClientCreate).toHaveBeenCalledWith(
CLOUD_DATA_SAVED_OBJECT_TYPE,
{ onboardingData: request.body.onboardingData },
{ id: CLOUD_DATA_SAVED_OBJECT_ID }
);
});

it('should update cloud data if it exists', async () => {
const { routeHandler } = await setup();

mockSavedObjectsClientGet.mockResolvedValue({
id: CLOUD_DATA_SAVED_OBJECT_ID,
attributes: {
onboardingData: { solutionType: 'o11y', token: 'test-33' },
},
});

const request = httpServerMock.createKibanaRequest({
body: {
onboardingData: {
solutionType: 'security',
token: 'test-token',
},
},
method: 'post',
});

await routeHandler(mockRouteContext, request, kibanaResponseFactory);

expect(mockSavedObjectsClientGet).toHaveBeenCalledWith(
CLOUD_DATA_SAVED_OBJECT_TYPE,
CLOUD_DATA_SAVED_OBJECT_ID
);
expect(mockSavedObjectsClientUpdate).toHaveBeenCalledWith(
CLOUD_DATA_SAVED_OBJECT_TYPE,
CLOUD_DATA_SAVED_OBJECT_ID,
{ onboardingData: request.body.onboardingData }
);
});
});
92 changes: 92 additions & 0 deletions x-pack/plugins/cloud/server/routes/set_cloud_data_route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/*
* 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 { schema } from '@kbn/config-schema';
import { ReservedPrivilegesSet, SavedObjectsErrorHelpers } from '@kbn/core/server';
import { RouteOptions } from '.';
import { CLOUD_DATA_SAVED_OBJECT_ID } from './constants';
import { CLOUD_DATA_SAVED_OBJECT_TYPE } from '../saved_objects';
import { CloudDataAttributes } from './types';

const createBodySchemaV1 = schema.object({
onboardingData: schema.object({
solutionType: schema.oneOf([
schema.literal('security'),
schema.literal('observability'),
schema.literal('search'),
schema.literal('elasticsearch'),
]),
token: schema.string(),
}),
});

export const setPostCloudSolutionDataRoute = ({ router }: RouteOptions) => {
router.versioned
.post({
path: `/internal/cloud/solution`,
access: 'internal',
summary: 'Save cloud data for solutions',
security: {
authz: {
requiredPrivileges: [ReservedPrivilegesSet.superuser],
},
},
})
.addVersion(
{
version: '1',
validate: {
request: {
body: createBodySchemaV1,
},
},
},
async (context, request, response) => {
const coreContext = await context.core;
const savedObjectsClient = coreContext.savedObjects.getClient({
includedHiddenTypes: [CLOUD_DATA_SAVED_OBJECT_TYPE],
});
let cloudDataSo = null;
try {
cloudDataSo = await savedObjectsClient.get<CloudDataAttributes>(
CLOUD_DATA_SAVED_OBJECT_TYPE,
CLOUD_DATA_SAVED_OBJECT_ID
);
} catch (error) {
if (SavedObjectsErrorHelpers.isNotFoundError(error)) {
cloudDataSo = null;
} else {
return response.customError(error);
}
}

try {
if (cloudDataSo === null) {
await savedObjectsClient.create<CloudDataAttributes>(
CLOUD_DATA_SAVED_OBJECT_TYPE,
{
onboardingData: request.body.onboardingData,
},
{ id: CLOUD_DATA_SAVED_OBJECT_ID }
);
} else {
await savedObjectsClient.update<CloudDataAttributes>(
CLOUD_DATA_SAVED_OBJECT_TYPE,
CLOUD_DATA_SAVED_OBJECT_ID,
{
onboardingData: request.body.onboardingData,
}
);
}
} catch (error) {
return response.badRequest(error);
}

return response.ok();
}
);
};
Loading