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

[Fleet] Tagging of integration assets #137184

Merged
merged 18 commits into from
Jul 29, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
8 changes: 7 additions & 1 deletion src/plugins/saved_objects_tagging_oss/common/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,14 @@ export interface GetAllTagsOptions {
asSystemRequest?: boolean;
}

export interface CreateTagOptions {
id?: string;
overwrite?: boolean;
refresh?: boolean | 'wait_for';
}

export interface ITagsClient {
create(attributes: TagAttributes): Promise<Tag>;
create(attributes: TagAttributes, options?: CreateTagOptions): Promise<Tag>;
get(id: string): Promise<Tag>;
getAll(options?: GetAllTagsOptions): Promise<Tag[]>;
delete(id: string): Promise<void>;
Expand Down
2 changes: 1 addition & 1 deletion x-pack/plugins/fleet/kibana.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"server": true,
"ui": true,
"configPath": ["xpack", "fleet"],
"requiredPlugins": ["licensing", "data", "encryptedSavedObjects", "navigation", "customIntegrations", "share", "spaces", "security", "unifiedSearch"],
"requiredPlugins": ["licensing", "data", "encryptedSavedObjects", "navigation", "customIntegrations", "share", "spaces", "security", "unifiedSearch", "savedObjectsTagging"],
"optionalPlugins": ["features", "cloud", "usageCollection", "home", "globalSearch", "telemetry", "discover", "ingestPipelines"],
"extraPublicDirs": ["common"],
"requiredBundles": ["kibanaReact", "cloud", "esUiShared", "infra", "kibanaUtils", "usageCollection", "unifiedSearch"]
Expand Down
5 changes: 5 additions & 0 deletions x-pack/plugins/fleet/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ import type { CloudSetup } from '@kbn/cloud-plugin/server';

import type { SpacesPluginStart } from '@kbn/spaces-plugin/server';

import type { SavedObjectTaggingStart } from '@kbn/saved-objects-tagging-plugin/server';

import type { FleetConfigType } from '../common/types';
import type { FleetAuthz } from '../common';
import type { ExperimentalFeatures } from '../common/experimental_features';
Expand Down Expand Up @@ -115,6 +117,7 @@ export interface FleetStartDeps {
encryptedSavedObjects: EncryptedSavedObjectsPluginStart;
security: SecurityPluginStart;
telemetry?: TelemetryPluginStart;
savedObjectsTagging: SavedObjectTaggingStart;
}

export interface FleetAppContext {
Expand All @@ -128,6 +131,7 @@ export interface FleetAppContext {
configInitialValue: FleetConfigType;
experimentalFeatures: ExperimentalFeatures;
savedObjects: SavedObjectsServiceStart;
savedObjectsTagging?: SavedObjectTaggingStart;
isProductionMode: PluginInitializerContext['env']['mode']['prod'];
kibanaVersion: PluginInitializerContext['env']['packageInfo']['version'];
kibanaBranch: PluginInitializerContext['env']['packageInfo']['branch'];
Expand Down Expand Up @@ -400,6 +404,7 @@ export class FleetPlugin
this.configInitialValue.enableExperimental || []
),
savedObjects: core.savedObjects,
savedObjectsTagging: plugins.savedObjectsTagging,
isProductionMode: this.isProductionMode,
kibanaVersion: this.kibanaVersion,
kibanaBranch: this.kibanaBranch,
Expand Down
11 changes: 11 additions & 0 deletions x-pack/plugins/fleet/server/services/app_context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ import type { SecurityPluginStart, SecurityPluginSetup } from '@kbn/security-plu

import type { CloudSetup } from '@kbn/cloud-plugin/server';

import type { SavedObjectTaggingStart } from '@kbn/saved-objects-tagging-plugin/server';

import type { FleetConfigType } from '../../common/types';
import type { ExperimentalFeatures } from '../../common/experimental_features';
import type {
Expand Down Expand Up @@ -58,6 +60,7 @@ class AppContextService {
private httpSetup?: HttpServiceSetup;
private externalCallbacks: ExternalCallbacksStorage = new Map();
private telemetryEventsSender: TelemetryEventsSender | undefined;
private savedObjectsTagging: SavedObjectTaggingStart | undefined;

public start(appContext: FleetAppContext) {
this.data = appContext.data;
Expand All @@ -75,6 +78,7 @@ class AppContextService {
this.kibanaBranch = appContext.kibanaBranch;
this.httpSetup = appContext.httpSetup;
this.telemetryEventsSender = appContext.telemetryEventsSender;
this.savedObjectsTagging = appContext.savedObjectsTagging;

if (appContext.config$) {
this.config$ = appContext.config$;
Expand Down Expand Up @@ -143,6 +147,13 @@ class AppContextService {
return this.savedObjects;
}

public getSavedObjectsTagging() {
if (!this.savedObjectsTagging) {
throw new Error('Saved object tagging start service not set.');
}
return this.savedObjectsTagging;
}

public getInternalUserSOClient(request: KibanaRequest) {
// soClient as kibana internal users, be careful on how you use it, security is not enabled
return appContextService.getSavedObjects().getScopedClient(request, {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import type { SavedObjectsImportSuccess, SavedObjectsImportFailure } from '@kbn/
import { createListStream } from '@kbn/utils';
import { partition } from 'lodash';

import type { IAssignmentService, ITagsClient } from '@kbn/saved-objects-tagging-plugin/server';

import { PACKAGES_SAVED_OBJECT_TYPE } from '../../../../../common';
import { getAsset, getPathParts } from '../../archive';
import { KibanaAssetType, KibanaSavedObjectType } from '../../../../types';
Expand All @@ -27,6 +29,10 @@ import { indexPatternTypes, getIndexPatternSavedObjects } from '../index_pattern
import { saveKibanaAssetsRefs } from '../../packages/install';
import { deleteKibanaSavedObjectsAssets } from '../../packages/remove';

import { withPackageSpan } from '../../packages/utils';

import { tagKibanaAssets } from './tag_assets';

type SavedObjectsImporterContract = Pick<SavedObjectsImporter, 'import' | 'resolveImportErrors'>;
const formatImportErrorsForLog = (errors: SavedObjectsImportFailure[]) =>
JSON.stringify(
Expand Down Expand Up @@ -128,15 +134,21 @@ export async function installKibanaAssets(options: {
export async function installKibanaAssetsAndReferences({
savedObjectsClient,
savedObjectsImporter,
savedObjectTagAssignmentService,
savedObjectTagClient,
logger,
pkgName,
pkgTitle,
paths,
installedPkg,
}: {
savedObjectsClient: SavedObjectsClientContract;
savedObjectsImporter: Pick<SavedObjectsImporter, 'import' | 'resolveImportErrors'>;
savedObjectTagAssignmentService: IAssignmentService;
savedObjectTagClient: ITagsClient;
logger: Logger;
pkgName: string;
pkgTitle: string;
paths: string[];
installedPkg?: SavedObject<Installation>;
}) {
Expand All @@ -156,6 +168,16 @@ export async function installKibanaAssetsAndReferences({
kibanaAssets,
});

await withPackageSpan('Create and assign package tags', () =>
tagKibanaAssets({
savedObjectTagAssignmentService,
savedObjectTagClient,
kibanaAssets,
pkgTitle,
pkgName,
})
);

return installedKibanaAssetsRefs;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
/*
* 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 { tagKibanaAssets } from './tag_assets';

describe('tagKibanaAssets', () => {
const savedObjectTagAssignmentService = {
updateTagAssignments: jest.fn(),
} as any;
const savedObjectTagClient = {
getAll: jest.fn(),
create: jest.fn(),
} as any;

beforeEach(() => {
savedObjectTagAssignmentService.updateTagAssignments.mockReset();
savedObjectTagClient.getAll.mockReset();
savedObjectTagClient.create.mockReset();
});

it('should create Managed and System tags when tagKibanaAssets with System package', async () => {
savedObjectTagClient.getAll.mockResolvedValue([]);
savedObjectTagClient.create.mockImplementation(({ name }: { name: string }) =>
Promise.resolve({ id: name.toLowerCase(), name })
);
const kibanaAssets = { dashboard: [{ id: 'dashboard1', type: 'dashboard' }] } as any;

await tagKibanaAssets({
savedObjectTagAssignmentService,
savedObjectTagClient,
kibanaAssets,
pkgTitle: 'System',
pkgName: 'system',
});

expect(savedObjectTagClient.create).toHaveBeenCalledWith(
{
name: 'Managed',
description: '',
color: '#FFFFFF',
},
{ id: 'managed', overwrite: true, refresh: false }
);
expect(savedObjectTagClient.create).toHaveBeenCalledWith(
{
name: 'System',
description: '',
color: '#FFFFFF',
},
{ id: 'system', overwrite: true, refresh: false }
);
expect(savedObjectTagAssignmentService.updateTagAssignments).toHaveBeenCalledWith({
tags: ['managed', 'system'],
assign: kibanaAssets.dashboard,
unassign: [],
refresh: false,
});
});

it('should only assign Managed and System tags when tags already exist', async () => {
savedObjectTagClient.getAll.mockResolvedValue([
{ id: 'managed', name: 'Managed' },
{ id: 'system', name: 'System' },
]);
const kibanaAssets = { dashboard: [{ id: 'dashboard1', type: 'dashboard' }] } as any;

await tagKibanaAssets({
savedObjectTagAssignmentService,
savedObjectTagClient,
kibanaAssets,
pkgTitle: 'System',
pkgName: 'system',
});

expect(savedObjectTagClient.create).not.toHaveBeenCalled();
expect(savedObjectTagAssignmentService.updateTagAssignments).toHaveBeenCalledWith({
tags: ['managed', 'system'],
assign: kibanaAssets.dashboard,
unassign: [],
refresh: false,
});
});

it('should skip non taggable asset types', async () => {
savedObjectTagClient.getAll.mockResolvedValue([]);
savedObjectTagClient.create.mockImplementation(({ name }: { name: string }) =>
Promise.resolve({ id: name.toLowerCase(), name })
);
const kibanaAssets = {
dashboard: [{ id: 'dashboard1', type: 'dashboard' }],
search: [{ id: 's1', type: 'search' }],
visualization: [{ id: 'v1', type: 'visualization' }],
} as any;

await tagKibanaAssets({
savedObjectTagAssignmentService,
savedObjectTagClient,
kibanaAssets,
pkgTitle: 'System',
pkgName: 'system',
});

expect(savedObjectTagAssignmentService.updateTagAssignments).toHaveBeenCalledWith({
tags: ['managed', 'system'],
assign: [...kibanaAssets.dashboard, ...kibanaAssets.visualization],
unassign: [],
refresh: false,
});
});

it('should do nothing if no taggable assets', async () => {
const kibanaAssets = { search: [{ id: 's1', type: 'search' }] } as any;

await tagKibanaAssets({
savedObjectTagAssignmentService,
savedObjectTagClient,
kibanaAssets,
pkgTitle: 'System',
pkgName: 'system',
});

expect(savedObjectTagAssignmentService.updateTagAssignments).not.toHaveBeenCalled();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
* 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 { taggableTypes } from '@kbn/saved-objects-tagging-plugin/common/constants';
import type { IAssignmentService, ITagsClient } from '@kbn/saved-objects-tagging-plugin/server';

import type { KibanaAssetType } from '../../../../../common';

import type { ArchiveAsset } from './install';

const TAG_COLOR = '#FFFFFF';
const MANAGED_TAG_NAME = 'Managed';
const MANAGED_TAG_ID = 'managed';

export async function tagKibanaAssets({
savedObjectTagAssignmentService,
savedObjectTagClient,
kibanaAssets,
pkgTitle,
pkgName,
}: {
savedObjectTagAssignmentService: IAssignmentService;
savedObjectTagClient: ITagsClient;
kibanaAssets: Record<KibanaAssetType, ArchiveAsset[]>;
pkgTitle: string;
pkgName: string;
}) {
const taggableAssets = Object.entries(kibanaAssets).flatMap(([assetType, assets]) => {
if (!taggableTypes.includes(assetType as KibanaAssetType)) {
return [];
}

if (!assets.length) {
return [];
}

return assets;
});

// no assets to tag
if (taggableAssets.length === 0) {
return;
}

const allTags = await savedObjectTagClient.getAll();
juliaElastic marked this conversation as resolved.
Show resolved Hide resolved
let managedTag = allTags.find((tag) => tag.name === MANAGED_TAG_NAME);
if (!managedTag) {
managedTag = await savedObjectTagClient.create(
{
name: MANAGED_TAG_NAME,
description: '',
color: TAG_COLOR,
},
{ id: MANAGED_TAG_ID, overwrite: true, refresh: false }
);
}

let packageTag = allTags.find((tag) => tag.name === pkgTitle);
if (!packageTag) {
packageTag = await savedObjectTagClient.create(
{
name: pkgTitle,
description: '',
color: TAG_COLOR,
},
{ id: pkgName, overwrite: true, refresh: false }
);
}

await savedObjectTagAssignmentService.updateTagAssignments({
tags: [managedTag.id, packageTag.id],
assign: taggableAssets,
unassign: [],
refresh: false,
});
}
Loading