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

Add deprecation warning when unknown SO types are present #111268

Merged
Show file tree
Hide file tree
Changes from 1 commit
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
35 changes: 35 additions & 0 deletions src/core/server/saved_objects/deprecations/deprecation_factory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* 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 type { RegisterDeprecationsConfig } from '../../deprecations';
import type { ISavedObjectTypeRegistry } from '../saved_objects_type_registry';
import type { SavedObjectConfig } from '../saved_objects_config';
import type { KibanaConfigType } from '../../kibana_config';
import { getUnknownTypesDeprecations } from './unknown_object_types';

interface GetDeprecationProviderOptions {
typeRegistry: ISavedObjectTypeRegistry;
savedObjectsConfig: SavedObjectConfig;
kibanaConfig: KibanaConfigType;
kibanaVersion: string;
}

export const getSavedObjectsDeprecationsProvider = (
config: GetDeprecationProviderOptions
): RegisterDeprecationsConfig => {
return {
getDeprecations: async (context) => {
return [
...(await getUnknownTypesDeprecations({
...config,
esClient: context.esClient,
})),
];
},
};
};
10 changes: 10 additions & 0 deletions src/core/server/saved_objects/deprecations/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/*
* 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.
*/

export { hasUnknownObjectTypes } from './unknown_object_types';
export { getSavedObjectsDeprecationsProvider } from './deprecation_factory';
95 changes: 95 additions & 0 deletions src/core/server/saved_objects/deprecations/unknown_object_types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
* 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 { estypes } from '@elastic/elasticsearch';
import { i18n } from '@kbn/i18n';
import type { DeprecationsDetails } from '../../deprecations';
import { IScopedClusterClient } from '../../elasticsearch';
import { ISavedObjectTypeRegistry } from '../saved_objects_type_registry';
import { SavedObjectsRawDocSource } from '../serialization';
import type { KibanaConfigType } from '../../kibana_config';
import type { SavedObjectConfig } from '../saved_objects_config';
import { getIndexForType } from '../service/lib';

interface UnknownTypesDeprecationOptions {
typeRegistry: ISavedObjectTypeRegistry;
esClient: IScopedClusterClient;
kibanaConfig: KibanaConfigType;
savedObjectsConfig: SavedObjectConfig;
kibanaVersion: string;
}

export const hasUnknownObjectTypes = async ({
typeRegistry,
esClient,
kibanaConfig,
savedObjectsConfig,
kibanaVersion,
}: UnknownTypesDeprecationOptions) => {
const knownTypes = typeRegistry.getAllTypes().map((type) => type.name);
const targetIndices = [
...new Set(
knownTypes.map((type) =>
getIndexForType({
type,
typeRegistry,
migV2Enabled: savedObjectsConfig.migration.enableV2,
kibanaVersion,
defaultIndex: kibanaConfig.index,
})
)
),
pgayvallet marked this conversation as resolved.
Show resolved Hide resolved
];

const query: estypes.QueryDslQueryContainer = {
bool: {
must_not: knownTypes.map((type) => ({
term: { type },
})),
},
};

const { body } = await esClient.asInternalUser.search<SavedObjectsRawDocSource>({
index: targetIndices,
body: {
size: 10000,
Comment on lines +85 to +88
Copy link
Contributor Author

Choose a reason for hiding this comment

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

What should I do if this throws? Should I just not register the deprecation?

Copy link
Member

@Bamieh Bamieh Sep 6, 2021

Choose a reason for hiding this comment

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

i think the deprecation service needs to support sending an error inside the returned array from the getDeprecation function.

Currently if the whole getDeprecation throws then the service will show failed to fetch deprecation for x feature. We might need to mimic this behavior inside the array entries just like we do for the whole function.

Maybe until we support this we are OK with throwing everything (es connectivity issue usually means ES is unreachable or something).

query,
},
});
pgayvallet marked this conversation as resolved.
Show resolved Hide resolved
const { hits: unknownDocs } = body.hits;

return unknownDocs.length > 0;
};

export const getUnknownTypesDeprecations = async (
options: UnknownTypesDeprecationOptions
): Promise<DeprecationsDetails[]> => {
const deprecations: DeprecationsDetails[] = [];
if (await hasUnknownObjectTypes(options)) {
deprecations.push({
title: i18n.translate('core.savedObjects.deprecations.unknownTypes.title', {
defaultMessage: 'Saved objects with unknown types are present in Kibana system indices',
}),
message: i18n.translate('core.savedObjects.deprecations.unknownTypes.message', {
defaultMessage: '',
}),
level: 'critical',
requireRestart: false,
deprecationType: undefined, // not config nor feature...
Copy link
Member

Choose a reason for hiding this comment

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

Do you have in ind a specific deprecation type we can add or are you comfortable with undefined?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

As suggested by the UA team in another issue, I think we should have this field mandatory and at least add an other category

correctiveActions: {
manualSteps: [], // TODO
api: {
path: '/internal/saved_objects/deprecations/_delete_unknown_types',
method: 'POST',
body: {},
},
},
});
}
return deprecations;
};
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 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 { IRouter } from '../../../http';
import { catchAndReturnBoomErrors } from '../utils';

export const registerDeleteUnknownTypesRoute = (router: IRouter) => {
router.post(
{
path: '/deprecations/_delete_unknown_types',
validate: false,
},
Comment on lines +25 to +29
Copy link
Contributor Author

Choose a reason for hiding this comment

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

A small security concern here: as we can't leverage the SOR to perform the cleanup, we're using the internal ES client instead (which also make sense, because we want to be able to delete all the unknown docs anyway, and because the SO security does not work with unknown types...).

However, this means that any authenticated user can potentially hit this endpoint, and cause the removal of the unknown docs. We could restrict the route with a access: tag, however this endpoint needs to be reachable by anyone having access to the UA management section to resolve the deprecation.

I don't think this is that big of a deal, but still worth a comment: are we fine with this?

Copy link
Contributor

Choose a reason for hiding this comment

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

The likelihood is low that this gets abused and in most cases the impact will be low, it will probably just delete unused data.

But as a pattern this feels wrong, it feels like something that will crop up for other teams too that have destructive correctiveActions e.g. https://github.com/elastic/kibana/blob/master/x-pack/plugins/reporting/server/routes/deprecations.ts#L100

In reporting's case, security is enforced by Elasticsearch. So there's some precedent that just because you're able to use the upgrade assistant doesn't mean you'll automatically be able to perform all corrective actions.

I wonder if it wouldn't be fine to require the kibana_admin to perform these upgrade assistant fixes?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I wonder if it wouldn't be fine to require the kibana_admin to perform these upgrade assistant fixes?

we could use the scoped client instead of the internal one, that would do it, but then other users would still see the deprecation, and clicking the button would throw a server error... I don't really like it either to be honest.

catchAndReturnBoomErrors(async (context, req, res) => {
// TODO: actually peform the action.
return res.ok({
pgayvallet marked this conversation as resolved.
Show resolved Hide resolved
body: {
success: true,
},
});
})
);
};
9 changes: 9 additions & 0 deletions src/core/server/saved_objects/routes/deprecations/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/*
* 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.
*/

export { registerDeleteUnknownTypesRoute } from './delete_unknown_types';
2 changes: 2 additions & 0 deletions src/core/server/saved_objects/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { registerExportRoute } from './export';
import { registerImportRoute } from './import';
import { registerResolveImportErrorsRoute } from './resolve_import_errors';
import { registerMigrateRoute } from './migrate';
import { registerDeleteUnknownTypesRoute } from './deprecations';

export function registerRoutes({
http,
Expand Down Expand Up @@ -58,4 +59,5 @@ export function registerRoutes({
const internalRouter = http.createRouter('/internal/saved_objects/');

registerMigrateRoute(internalRouter, migratorPromise);
registerDeleteUnknownTypesRoute(internalRouter);
}
19 changes: 18 additions & 1 deletion src/core/server/saved_objects/saved_objects_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
InternalElasticsearchServiceSetup,
InternalElasticsearchServiceStart,
} from '../elasticsearch';
import { InternalDeprecationsServiceSetup } from '../deprecations';
import { KibanaConfigType } from '../kibana_config';
import {
SavedObjectsConfigType,
Expand All @@ -44,6 +45,7 @@ import { registerRoutes } from './routes';
import { ServiceStatus } from '../status';
import { calculateStatus$ } from './status';
import { registerCoreObjectTypes } from './object_types';
import { getSavedObjectsDeprecationsProvider } from './deprecations';

/**
* Saved Objects is Kibana's data persistence mechanism allowing plugins to
Expand Down Expand Up @@ -251,6 +253,7 @@ export interface SavedObjectsSetupDeps {
http: InternalHttpServiceSetup;
elasticsearch: InternalElasticsearchServiceSetup;
coreUsageData: InternalCoreUsageDataSetup;
deprecations: InternalDeprecationsServiceSetup;
}

interface WrappedClientFactoryWrapper {
Expand Down Expand Up @@ -286,7 +289,7 @@ export class SavedObjectsService
this.logger.debug('Setting up SavedObjects service');

this.setupDeps = setupDeps;
const { http, elasticsearch, coreUsageData } = setupDeps;
const { http, elasticsearch, coreUsageData, deprecations } = setupDeps;

const savedObjectsConfig = await this.coreContext.configService
.atPath<SavedObjectsConfigType>('savedObjects')
Expand All @@ -298,6 +301,20 @@ export class SavedObjectsService
.toPromise();
this.config = new SavedObjectConfig(savedObjectsConfig, savedObjectsMigrationConfig);

const kibanaConfig = await this.coreContext.configService
.atPath<KibanaConfigType>('kibana')
.pipe(first())
.toPromise();

deprecations.getRegistry('core').registerDeprecations(
pgayvallet marked this conversation as resolved.
Show resolved Hide resolved
getSavedObjectsDeprecationsProvider({
kibanaConfig,
savedObjectsConfig: this.config,
kibanaVersion: this.coreContext.env.packageInfo.version,
typeRegistry: this.typeRegistry,
})
);

coreUsageData.registerType(this.typeRegistry);

registerRoutes({
Expand Down
36 changes: 36 additions & 0 deletions src/core/server/saved_objects/service/lib/get_index_for_type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* 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 { ISavedObjectTypeRegistry } from '../../saved_objects_type_registry';

interface GetIndexForTypeOptions {
type: string;
typeRegistry: ISavedObjectTypeRegistry;
migV2Enabled: boolean;
kibanaVersion: string;
defaultIndex: string;
}

export const getIndexForType = ({
type,
typeRegistry,
migV2Enabled,
defaultIndex,
kibanaVersion,
}: GetIndexForTypeOptions): string => {
// TODO migrationsV2: Remove once we remove migrations v1
// This is a hacky, but it required the least amount of changes to
// existing code to support a migrations v2 index. Long term we would
// want to always use the type registry to resolve a type's index
// (including the default index).
if (migV2Enabled) {
return `${typeRegistry.getIndex(type) || defaultIndex}_${kibanaVersion}`;
} else {
return typeRegistry.getIndex(type) || defaultIndex;
}
};
2 changes: 2 additions & 0 deletions src/core/server/saved_objects/service/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,5 @@ export type {
SavedObjectsUpdateObjectsSpacesResponse,
SavedObjectsUpdateObjectsSpacesResponseObject,
} from './update_objects_spaces';

export { getIndexForType } from './get_index_for_type';
18 changes: 8 additions & 10 deletions src/core/server/saved_objects/service/lib/repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ import {
SavedObjectsUpdateObjectsSpacesObject,
SavedObjectsUpdateObjectsSpacesOptions,
} from './update_objects_spaces';
import { getIndexForType } from './get_index_for_type';

// BEWARE: The SavedObjectClient depends on the implementation details of the SavedObjectsRepository
// so any breaking changes to this repository are considered breaking changes to the SavedObjectsClient.
Expand Down Expand Up @@ -2099,16 +2100,13 @@ export class SavedObjectsRepository {
* @param type - the type
*/
private getIndexForType(type: string) {
// TODO migrationsV2: Remove once we remove migrations v1
// This is a hacky, but it required the least amount of changes to
// existing code to support a migrations v2 index. Long term we would
// want to always use the type registry to resolve a type's index
// (including the default index).
if (this._migrator.soMigrationsConfig.enableV2) {
return `${this._registry.getIndex(type) || this._index}_${this._migrator.kibanaVersion}`;
} else {
return this._registry.getIndex(type) || this._index;
}
return getIndexForType({
type,
defaultIndex: this._index,
typeRegistry: this._registry,
kibanaVersion: this._migrator.kibanaVersion,
migV2Enabled: this._migrator.soMigrationsConfig.enableV2,
pgayvallet marked this conversation as resolved.
Show resolved Hide resolved
});
}

/**
Expand Down
12 changes: 7 additions & 5 deletions src/core/server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,10 @@ export class Server {

const capabilitiesSetup = this.capabilities.setup({ http: httpSetup });

const deprecationsSetup = this.deprecations.setup({
http: httpSetup,
});

const elasticsearchServiceSetup = await this.elasticsearch.setup({
http: httpSetup,
executionContext: executionContextSetup,
Expand All @@ -228,6 +232,7 @@ export class Server {
const savedObjectsSetup = await this.savedObjects.setup({
http: httpSetup,
elasticsearch: elasticsearchServiceSetup,
deprecations: deprecationsSetup,
coreUsageData: coreUsageDataSetup,
});

Expand Down Expand Up @@ -259,10 +264,6 @@ export class Server {

const loggingSetup = this.logging.setup();

const deprecationsSetup = this.deprecations.setup({
http: httpSetup,
});

const coreSetup: InternalCoreSetup = {
capabilities: capabilitiesSetup,
context: contextServiceSetup,
Expand Down Expand Up @@ -302,6 +303,7 @@ export class Server {

const executionContextStart = this.executionContext.start();
const elasticsearchStart = await this.elasticsearch.start();
const deprecationsStart = this.deprecations.start();
const soStartSpan = startTransaction?.startSpan('saved_objects.migration', 'migration');
const savedObjectsStart = await this.savedObjects.start({
elasticsearch: elasticsearchStart,
Expand All @@ -319,7 +321,7 @@ export class Server {
savedObjects: savedObjectsStart,
exposedConfigsToUsage: this.plugins.getExposedPluginConfigsToUsage(),
});
const deprecationsStart = this.deprecations.start();

this.status.start();

this.coreStart = {
Expand Down