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

[8.x] [APM] Replace security plugin authc with Kibana core (#203771) #204896

Merged
merged 1 commit into from
Dec 19, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -10753,7 +10753,6 @@
"xpack.apm.anomalyRuleType.anomalyDetector": "Types de détecteurs",
"xpack.apm.anomalyRuleType.anomalyDetector.infoLabel": "Vous devez sélectionner au moins un détecteur",
"xpack.apm.anomalyScore": "Anomalie {severity, select, minor {mineure} major {majeure} critical {critique} other {de sévérité inconnue}}",
"xpack.apm.api.apiKeys.securityRequired": "Le plug-in de sécurité est requis",
"xpack.apm.api.fleet.cloud_apm_package_policy.requiredRoleOnCloud": "Opération autorisée uniquement pour les utilisateurs Elastic Cloud disposant du rôle de superutilisateur.",
"xpack.apm.api.fleet.fleetSecurityRequired": "Les plug-ins Fleet et Security sont requis",
"xpack.apm.api.storageExplorer.securityRequired": "Le plug-in de sécurité est requis",
Expand Down Expand Up @@ -49866,4 +49865,4 @@
"xpack.watcher.watchEdit.thresholdWatchExpression.aggType.fieldIsRequiredValidationMessage": "Ce champ est requis.",
"xpack.watcher.watcherDescription": "Détectez les modifications survenant dans vos données en créant, gérant et monitorant des alertes."
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10622,7 +10622,6 @@
"xpack.apm.anomalyRuleType.anomalyDetector": "検知器タイプ",
"xpack.apm.anomalyRuleType.anomalyDetector.infoLabel": "検知器を最低1つ選択する必要があります",
"xpack.apm.anomalyScore": "{severity, select, minor {軽微な} major {重要な} critical {重大な} other {不明な重要度の}}異常",
"xpack.apm.api.apiKeys.securityRequired": "セキュリティプラグインが必要です",
"xpack.apm.api.fleet.cloud_apm_package_policy.requiredRoleOnCloud": "スーパーユーザーロールが付与されたElastic Cloudユーザーのみが操作できます。",
"xpack.apm.api.fleet.fleetSecurityRequired": "FleetおよびSecurityプラグインが必要です",
"xpack.apm.api.storageExplorer.securityRequired": "セキュリティプラグインが必要です",
Expand Down Expand Up @@ -49714,4 +49713,4 @@
"xpack.watcher.watchEdit.thresholdWatchExpression.aggType.fieldIsRequiredValidationMessage": "フィールドを選択してください。",
"xpack.watcher.watcherDescription": "アラートの作成、管理、監視によりデータへの変更を検知します。"
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10673,7 +10673,6 @@
"xpack.apm.anomalyRuleType.anomalyDetector": "检测工具类型",
"xpack.apm.anomalyRuleType.anomalyDetector.infoLabel": "应至少选择一个检测工具",
"xpack.apm.anomalyScore": "{severity, select, minor {轻微} major {重大} critical {严重} other {严重性未知}}异常",
"xpack.apm.api.apiKeys.securityRequired": "需要 Security 插件",
"xpack.apm.api.fleet.cloud_apm_package_policy.requiredRoleOnCloud": "操作仅允许具有超级用户角色的 Elastic Cloud 用户执行。",
"xpack.apm.api.fleet.fleetSecurityRequired": "需要 Fleet 和 Security 插件",
"xpack.apm.api.storageExplorer.securityRequired": "需要 Security 插件",
Expand Down Expand Up @@ -49816,4 +49815,4 @@
"xpack.watcher.watchEdit.thresholdWatchExpression.aggType.fieldIsRequiredValidationMessage": "此字段必填。",
"xpack.watcher.watcherDescription": "通过创建、管理和监测警报来检测数据中的更改。"
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,13 @@ export function registerGetApmServicesListFunction({
} as const,
},
async ({ arguments: args }, signal) => {
const { logger } = resources;
const { logger, core } = resources;
const coreStart = await core.start();
const [apmAlertsClient, mlClient, randomSampler] = await Promise.all([
getApmAlertsClient(resources),
getMlClient(resources),
getRandomSampler({
security: resources.plugins.security,
coreStart,
probability: 1,
request: resources.request,
}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,12 @@ export function registerAssistantFunctions({
},
};

const {
request,
plugins: { security },
} = apmRouteHandlerResources;
const { request, core } = apmRouteHandlerResources;

const coreStart = await core.start();
const [apmEventClient, randomSampler] = await Promise.all([
getApmEventClient(apmRouteHandlerResources),
getRandomSampler({ security, request, probability: 1 }),
getRandomSampler({ coreStart, request, probability: 1 }),
]);

const hasData = await hasHistoricalAgentData(apmEventClient);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,30 +5,26 @@
* 2.0.
*/

import { KibanaRequest } from '@kbn/core/server';
import { CoreStart, KibanaRequest } from '@kbn/core/server';
import seedrandom from 'seedrandom';
import { APMRouteHandlerResources } from '../../../routes/apm_routes/register_apm_server_routes';

export type RandomSampler = Awaited<ReturnType<typeof getRandomSampler>>;

export async function getRandomSampler({
security,
coreStart,
request,
probability,
}: {
security: APMRouteHandlerResources['plugins']['security'];
coreStart: CoreStart;
request: KibanaRequest;
probability: number;
}) {
let seed = 1;

if (security) {
const securityPluginStart = await security.start();
const username = securityPluginStart.authc.getCurrentUser(request)?.username;
const username = coreStart.security.authc.getCurrentUser(request)?.username;

if (username) {
seed = Math.abs(seedrandom(username).int32());
}
if (username) {
seed = Math.abs(seedrandom(username).int32());
}

return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ export class APMPlugin
);

plugins.observability.alertDetailsContextualInsightsService.registerHandler(
getAlertDetailsContextHandler(resourcePlugins, logger)
getAlertDetailsContextHandler(getCoreStart(), resourcePlugins, logger)
);

return { config$ };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,16 @@ const agentExplorerRoute = createApmServerRoute({
]),
}),
async handler(resources): Promise<AgentExplorerAgentsResponse> {
const {
params,
request,
plugins: { security },
} = resources;
const { params, request, core } = resources;

const { environment, kuery, start, end, probability, serviceName, agentLanguage } =
params.query;

const coreStart = await core.start();

const [apmEventClient, randomSampler] = await Promise.all([
getApmEventClient(resources),
getRandomSampler({ security, request, probability }),
getRandomSampler({ coreStart, request, probability }),
]);

return getAgents({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
* 2.0.
*/

import { CoreStart } from '@kbn/core/server';
import { ApmPluginRequestHandlerContext } from '../typings';
import { APMPluginStartDependencies } from '../../types';

export interface AgentKeysPrivilegesResponse {
areApiKeysEnabled: boolean;
Expand All @@ -16,10 +16,10 @@ export interface AgentKeysPrivilegesResponse {

export async function getAgentKeysPrivileges({
context,
securityPluginStart,
coreStart,
}: {
context: ApmPluginRequestHandlerContext;
securityPluginStart: NonNullable<APMPluginStartDependencies['security']>;
coreStart: CoreStart;
}): Promise<AgentKeysPrivilegesResponse> {
const esClient = (await context.core).elasticsearch.client;
const [securityHasPrivilegesResponse, areApiKeysEnabled] = await Promise.all([
Expand All @@ -28,7 +28,7 @@ export async function getAgentKeysPrivileges({
cluster: ['manage_security', 'manage_api_key', 'manage_own_api_key'],
},
}),
securityPluginStart.authc.apiKeys.areAPIKeysEnabled(),
coreStart.security.authc.apiKeys.areAPIKeysEnabled(),
]);

const {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
* 2.0.
*/

import Boom from '@hapi/boom';
import { i18n } from '@kbn/i18n';
import * as t from 'io-ts';
import { createApmServerRoute } from '../apm_routes/create_apm_server_route';
import { AgentKeysResponse, getAgentKeys } from './get_agent_keys';
Expand All @@ -33,19 +31,12 @@ const agentKeysPrivilegesRoute = createApmServerRoute({
endpoint: 'GET /internal/apm/agent_keys/privileges',
security: { authz: { requiredPrivileges: ['apm'] } },
handler: async (resources): Promise<AgentKeysPrivilegesResponse> => {
const {
plugins: { security },
context,
} = resources;
const { context, core } = resources;

if (!security) {
throw Boom.internal(SECURITY_REQUIRED_MESSAGE);
}

const securityPluginStart = await security.start();
const coreStart = await core.start();
const agentKeysPrivileges = await getAgentKeysPrivileges({
context,
securityPluginStart,
coreStart,
});

return agentKeysPrivileges;
Expand All @@ -63,23 +54,15 @@ const invalidateAgentKeyRoute = createApmServerRoute({
body: t.type({ id: t.string }),
}),
handler: async (resources): Promise<InvalidateAgentKeyResponse> => {
const {
context,
params,
plugins: { security },
} = resources;
const { context, params, core } = resources;
const {
body: { id },
} = params;

if (!security) {
throw Boom.internal(SECURITY_REQUIRED_MESSAGE);
}

const securityPluginStart = await security.start();
const coreStart = await core.start();
const { isAdmin } = await getAgentKeysPrivileges({
context,
securityPluginStart,
coreStart,
});

const invalidatedKeys = await invalidateAgentKey({
Expand Down Expand Up @@ -126,7 +109,3 @@ export const agentKeysRouteRepository = {
...invalidateAgentKeyRoute,
...createAgentKeyRoute,
};

const SECURITY_REQUIRED_MESSAGE = i18n.translate('xpack.apm.api.apiKeys.securityRequired', {
defaultMessage: 'Security plugin is required',
});
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { Logger } from '@kbn/core/server';
import { CoreStart, Logger } from '@kbn/core/server';
import type {
AlertDetailsContextualInsight,
AlertDetailsContextualInsightsHandler,
Expand All @@ -32,6 +32,7 @@ import { APMRouteHandlerResources } from '../../apm_routes/register_apm_server_r
import { getApmErrors } from './get_apm_errors';

export const getAlertDetailsContextHandler = (
coreStartPromise: Promise<CoreStart>,
resourcePlugins: APMRouteHandlerResources['plugins'],
logger: Logger
): AlertDetailsContextualInsightsHandler => {
Expand Down Expand Up @@ -64,6 +65,7 @@ export const getAlertDetailsContextHandler = (
},
};

const coreStart = await coreStartPromise;
const [
apmEventClient,
annotationsClient,
Expand All @@ -81,7 +83,7 @@ export const getAlertDetailsContextHandler = (
requestContext.core,
getMlClient(resources),
getRandomSampler({
security: resourcePlugins.security,
coreStart,
probability: 1,
request: requestContext.request,
}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,12 @@ const getDownstreamDependenciesRoute = createApmServerRoute({
}),
security: { authz: { requiredPrivileges: ['apm'] } },
handler: async (resources): Promise<{ content: APMDownstreamDependency[] }> => {
const {
params,
request,
plugins: { security },
} = resources;
const { params, request, core } = resources;

const coreStart = await core.start();
const [apmEventClient, randomSampler] = await Promise.all([
getApmEventClient(resources),
getRandomSampler({ security, request, probability: 1 }),
getRandomSampler({ coreStart, request, probability: 1 }),
]);

const { query } = params;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,12 @@ const topDependenciesRoute = createApmServerRoute({
]),
security: { authz: { requiredPrivileges: ['apm'] } },
handler: async (resources): Promise<TopDependenciesResponse> => {
const {
request,
plugins: { security },
} = resources;
const { request, core } = resources;

const coreStart = await core.start();
const [apmEventClient, randomSampler] = await Promise.all([
getApmEventClient(resources),
getRandomSampler({ security, request, probability: 1 }),
getRandomSampler({ coreStart, request, probability: 1 }),
]);
const { environment, offset, numBuckets, kuery, start, end } = resources.params.query;

Expand Down Expand Up @@ -89,14 +87,12 @@ const upstreamServicesForDependencyRoute = createApmServerRoute({
]),
security: { authz: { requiredPrivileges: ['apm'] } },
handler: async (resources): Promise<UpstreamServicesForDependencyResponse> => {
const {
request,
plugins: { security },
} = resources;
const { request, core } = resources;

const coreStart = await core.start();
const [apmEventClient, randomSampler] = await Promise.all([
getApmEventClient(resources),
getRandomSampler({ security, request, probability: 1 }),
getRandomSampler({ coreStart, request, probability: 1 }),
]);

const {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,15 @@
* 2.0.
*/

import { KibanaRequest } from '@kbn/core/server';
import { APMPluginStartDependencies } from '../../types';
import { CoreStart, KibanaRequest } from '@kbn/core/server';

export function isSuperuser({
securityPluginStart,
coreStart,
request,
}: {
securityPluginStart: NonNullable<APMPluginStartDependencies['security']>;
coreStart: CoreStart;
request: KibanaRequest;
}) {
const user = securityPluginStart.authc.getCurrentUser(request);
const user = coreStart.security.authc.getCurrentUser(request);
return user?.roles.includes('superuser');
}
Original file line number Diff line number Diff line change
Expand Up @@ -149,19 +149,17 @@ const createCloudApmPackagePolicyRoute = createApmServerRoute({
throw Boom.internal(FLEET_SECURITY_REQUIRED_MESSAGE);
}

const [savedObjectsClient, coreStart, fleetPluginStart, securityPluginStart, apmIndices] =
await Promise.all([
(await context.core).savedObjects.client,
resources.core.start(),
plugins.fleet.start(),
plugins.security.start(),
resources.getApmIndices(),
]);
const [savedObjectsClient, coreStart, fleetPluginStart, apmIndices] = await Promise.all([
(await context.core).savedObjects.client,
resources.core.start(),
plugins.fleet.start(),
resources.getApmIndices(),
]);

const esClient = coreStart.elasticsearch.client.asScoped(resources.request).asCurrentUser;
const cloudPluginSetup = plugins.cloud?.setup;

const hasRequiredRole = isSuperuser({ securityPluginStart, request });
const hasRequiredRole = isSuperuser({ coreStart, request });
if (!hasRequiredRole || !cloudApmMigrationEnabled) {
throw Boom.forbidden(CLOUD_SUPERUSER_REQUIRED_MESSAGE);
}
Expand Down
Loading
Loading