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

Spaces - NP updates for usage collection and capabilities #57693

Merged
merged 18 commits into from
Feb 28, 2020
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
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
6 changes: 5 additions & 1 deletion src/core/server/http/http_server.mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ interface RequestFixtureOptions {
method?: RouteMethod;
socket?: Socket;
routeTags?: string[];
routeAuthRequired?: false;
legrego marked this conversation as resolved.
Show resolved Hide resolved
}

function createKibanaRequestMock({
Expand All @@ -53,6 +54,7 @@ function createKibanaRequestMock({
method = 'get',
socket = new Socket(),
routeTags,
routeAuthRequired,
}: RequestFixtureOptions = {}) {
const queryString = stringify(query, { sort: false });

Expand All @@ -70,7 +72,9 @@ function createKibanaRequestMock({
query: queryString,
search: queryString ? `?${queryString}` : queryString,
},
route: { settings: { tags: routeTags } },
route: {
settings: { tags: routeTags, auth: routeAuthRequired },
},
raw: {
req: { socket },
},
Expand Down
41 changes: 41 additions & 0 deletions src/plugins/usage_collection/server/mocks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

// eslint-disable-next-line @kbn/eslint/no-restricted-paths
legrego marked this conversation as resolved.
Show resolved Hide resolved
import { loggingServiceMock } from 'src/core/server/mocks';
import { UsageCollectionSetup } from './plugin';
import { CollectorSet } from './collector';

const createSetupContract = () => {
const setupContract = {
legrego marked this conversation as resolved.
Show resolved Hide resolved
...new CollectorSet({
logger: loggingServiceMock.createLogger(),
maximumWaitTimeForAllCollectorsInS: 1,
}),
registerLegacySavedObjects: jest.fn() as jest.Mocked<
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for creating the mock for us!

FYI: This method is about to be removed in #58401 😉
Which is about to be merged (waiting for a second review from another Pulse team member to merge it. Sometime today or tomorrow) :)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the heads-up. It looks like this will merge before #58401, so would you be ok removing the mock in your PR? I could drop it now, but then I'd have to suppress a TS warning about an incompatible interface, so you'd have to alter this file no matter what :/

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Absolutely! It's a simple removal :)

UsageCollectionSetup['registerLegacySavedObjects']
>,
} as UsageCollectionSetup;

return setupContract;
};

export const usageCollectionPluginMock = {
createSetupContract,
};
18 changes: 0 additions & 18 deletions x-pack/legacy/plugins/spaces/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,19 +34,6 @@ export const spaces = (kibana: Record<string, any>) =>
publicDir: resolve(__dirname, 'public'),
require: ['kibana', 'elasticsearch', 'xpack_main'],

uiCapabilities() {
return {
spaces: {
manage: true,
},
management: {
kibana: {
spaces: true,
},
},
};
},

uiExports: {
styleSheetPaths: resolve(__dirname, 'public/index.scss'),
managementSections: [],
Expand Down Expand Up @@ -110,14 +97,9 @@ export const spaces = (kibana: Record<string, any>) =>
throw new Error('New Platform XPack Spaces plugin is not available.');
}

const config = server.config();

const { registerLegacyAPI, createDefaultSpace } = spacesPlugin.__legacyCompat;

registerLegacyAPI({
legacyConfig: {
kibanaIndex: config.get('kibana.index'),
},
savedObjects: server.savedObjects,
auditLogger: {
create: (pluginId: string) =>
Expand Down
27 changes: 27 additions & 0 deletions x-pack/plugins/features/server/mocks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
legrego marked this conversation as resolved.
Show resolved Hide resolved
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { PluginSetupContract, PluginStartContract } from './plugin';

const createSetup = (): jest.Mocked<PluginSetupContract> => {
return {
getFeatures: jest.fn(),
getFeaturesUICapabilities: jest.fn(),
registerFeature: jest.fn(),
registerLegacyAPI: jest.fn(),
};
};

const createStart = (): jest.Mocked<PluginStartContract> => {
return {
getFeatures: jest.fn(),
};
};

export const featuresPluginMock = {
createSetup,
createStart,
};
23 changes: 16 additions & 7 deletions x-pack/plugins/features/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ export interface PluginSetupContract {
registerLegacyAPI: (legacyAPI: LegacyAPI) => void;
}

export interface PluginStartContract {
getFeatures(): Feature[];
}

/**
* Describes a set of APIs that are available in the legacy platform only and required by this plugin
* to function properly.
Expand All @@ -45,6 +49,8 @@ export interface LegacyAPI {
export class Plugin {
private readonly logger: Logger;

private featureRegistry!: FeatureRegistry;
legrego marked this conversation as resolved.
Show resolved Hide resolved

private legacyAPI?: LegacyAPI;
private readonly getLegacyAPI = () => {
if (!this.legacyAPI) {
Expand All @@ -61,18 +67,18 @@ export class Plugin {
core: CoreSetup,
{ timelion }: { timelion?: TimelionSetupContract }
): Promise<RecursiveReadonly<PluginSetupContract>> {
const featureRegistry = new FeatureRegistry();
this.featureRegistry = new FeatureRegistry();

defineRoutes({
router: core.http.createRouter(),
featureRegistry,
featureRegistry: this.featureRegistry,
getLegacyAPI: this.getLegacyAPI,
});

return deepFreeze({
registerFeature: featureRegistry.register.bind(featureRegistry),
getFeatures: featureRegistry.getAll.bind(featureRegistry),
getFeaturesUICapabilities: () => uiCapabilitiesForFeatures(featureRegistry.getAll()),
registerFeature: this.featureRegistry.register.bind(this.featureRegistry),
getFeatures: this.featureRegistry.getAll.bind(this.featureRegistry),
legrego marked this conversation as resolved.
Show resolved Hide resolved
getFeaturesUICapabilities: () => uiCapabilitiesForFeatures(this.featureRegistry.getAll()),

registerLegacyAPI: (legacyAPI: LegacyAPI) => {
this.legacyAPI = legacyAPI;
Expand All @@ -82,14 +88,17 @@ export class Plugin {
savedObjectTypes: this.legacyAPI.savedObjectTypes,
includeTimelion: timelion !== undefined && timelion.uiEnabled,
})) {
featureRegistry.register(feature);
this.featureRegistry.register(feature);
}
},
});
}

public start() {
public start(): RecursiveReadonly<PluginStartContract> {
this.logger.debug('Starting plugin');
return {
legrego marked this conversation as resolved.
Show resolved Hide resolved
getFeatures: this.featureRegistry.getAll.bind(this.featureRegistry),
};
}

public stop() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { capabilitiesProvider } from './capabilities_provider';

describe('Capabilities provider', () => {
it('provides the expected capabilities', () => {
expect(capabilitiesProvider()).toMatchInlineSnapshot(`
Object {
"management": Object {
"kibana": Object {
"spaces": true,
},
},
"spaces": Object {
"manage": true,
},
}
`);
});
});
16 changes: 16 additions & 0 deletions x-pack/plugins/spaces/server/capabilities/capabilities_provider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

export const capabilitiesProvider = () => ({
spaces: {
manage: true,
},
management: {
kibana: {
spaces: true,
},
},
});
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,12 @@

import { Feature } from '../../../../plugins/features/server';
import { Space } from '../../common/model/space';
import { toggleUICapabilities } from './toggle_ui_capabilities';
import { Capabilities } from 'src/core/public';
import { setupCapabilitiesSwitcher } from './capabilities_switcher';
import { Capabilities, CoreSetup } from 'src/core/server';
import { coreMock, httpServerMock } from 'src/core/server/mocks';
import { featuresPluginMock } from '../../../features/server/mocks';
import { spacesServiceMock } from '../spaces_service/spaces_service.mock';
import { PluginsSetup } from '../plugin';

const features: Feature[] = [
{
Expand Down Expand Up @@ -91,40 +95,88 @@ const buildCapabilities = () =>
},
}) as Capabilities;

describe('toggleUiCapabilities', () => {
it('does not toggle capabilities when the space has no disabled features', () => {
const setup = (space: Space) => {
const coreSetup = coreMock.createSetup();

const featuresStart = featuresPluginMock.createStart();
featuresStart.getFeatures.mockReturnValue(features);

coreSetup.getStartServices.mockResolvedValue([
coreMock.createStart(),
{ features: featuresStart },
]);

const spacesService = spacesServiceMock.createSetupContract();
spacesService.getActiveSpace.mockResolvedValue(space);

return setupCapabilitiesSwitcher(
(coreSetup as unknown) as CoreSetup<PluginsSetup>,
spacesService
);
};

describe('capabilitiesSwitcher', () => {
it('does not toggle capabilities when the space has no disabled features', async () => {
const space: Space = {
id: 'space',
name: '',
disabledFeatures: [],
};

const capabilities = buildCapabilities();
const result = toggleUICapabilities(features, capabilities, space);

const switcher = setup(space);
const request = httpServerMock.createKibanaRequest();
const result = await switcher(request, capabilities);

expect(result).toEqual(buildCapabilities());
});

it('does not toggle capabilities when the request is not authenticated', async () => {
const space: Space = {
id: 'space',
name: '',
disabledFeatures: ['feature_1', 'feature_2', 'feature_3'],
};

const capabilities = buildCapabilities();

const switcher = setup(space);
const request = httpServerMock.createKibanaRequest({ routeAuthRequired: false });

const result = await switcher(request, capabilities);

expect(result).toEqual(buildCapabilities());
});

it('ignores unknown disabledFeatures', () => {
it('ignores unknown disabledFeatures', async () => {
const space: Space = {
id: 'space',
name: '',
disabledFeatures: ['i-do-not-exist'],
};

const capabilities = buildCapabilities();
const result = toggleUICapabilities(features, capabilities, space);

const switcher = setup(space);
const request = httpServerMock.createKibanaRequest();
const result = await switcher(request, capabilities);

expect(result).toEqual(buildCapabilities());
});

it('disables the corresponding navLink, catalogue, management sections, and all capability flags for disabled features', () => {
it('disables the corresponding navLink, catalogue, management sections, and all capability flags for disabled features', async () => {
const space: Space = {
id: 'space',
name: '',
disabledFeatures: ['feature_2'],
};

const capabilities = buildCapabilities();
const result = toggleUICapabilities(features, capabilities, space);

const switcher = setup(space);
const request = httpServerMock.createKibanaRequest();
const result = await switcher(request, capabilities);

const expectedCapabilities = buildCapabilities();

Expand All @@ -137,15 +189,18 @@ describe('toggleUiCapabilities', () => {
expect(result).toEqual(expectedCapabilities);
});

it('can disable everything', () => {
it('can disable everything', async () => {
const space: Space = {
id: 'space',
name: '',
disabledFeatures: ['feature_1', 'feature_2', 'feature_3'],
};

const capabilities = buildCapabilities();
const result = toggleUICapabilities(features, capabilities, space);

const switcher = setup(space);
const request = httpServerMock.createKibanaRequest();
const result = await switcher(request, capabilities);

const expectedCapabilities = buildCapabilities();

Expand Down
Loading