Skip to content

Commit

Permalink
Move authorization inside validateSystemActions
Browse files Browse the repository at this point in the history
  • Loading branch information
cnasikas committed Apr 10, 2024
1 parent 9ded5d2 commit 9af266a
Show file tree
Hide file tree
Showing 10 changed files with 296 additions and 70 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
SavedObjectsFindResult,
SavedObjectsUpdateResponse,
} from '@kbn/core/server';
import { validateSystemActions } from '../../../../lib/validate_system_actions';
import { validateAndAuthorizeSystemActions } from '../../../../lib/validate_authorize_system_actions';
import { RuleAction, RuleSystemAction } from '../../../../../common';
import { RULE_SAVED_OBJECT_TYPE } from '../../../../saved_objects';
import { BulkActionSkipResult } from '../../../../../common/bulk_edit';
Expand Down Expand Up @@ -682,10 +682,12 @@ async function getUpdatedAttributesFromOperations<Params extends RuleParams>({
value: [...genActions, ...genSystemActions],
};

await validateSystemActions({
await validateAndAuthorizeSystemActions({
actionsClient,
actionsAuthorization: context.actionsAuthorization,
connectorAdapterRegistry: context.connectorAdapterRegistry,
systemActions: genSystemActions,
rule: { consumer: updatedRule.consumer },
});

try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4353,5 +4353,35 @@ describe('create()', () => {
`[Error: Cannot use the same system action twice]`
);
});

test('should throw an error if the user does not have privileges to execute the action', async () => {
actionsAuthorization.ensureAuthorized.mockRejectedValueOnce(
'Unauthorized to execute actions'
);

const data = getMockData({
actions: [
{
group: 'default',
id: '1',
params: {
foo: true,
},
},
],
systemActions: [
{
id: 'system_action-id',
params: {
foo: 'test',
},
},
],
});

await expect(() => rulesClient.create({ data })).rejects.toMatchInlineSnapshot(
`"Unauthorized to execute actions"`
);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ import Semver from 'semver';
import Boom from '@hapi/boom';
import { SavedObject, SavedObjectsUtils } from '@kbn/core/server';
import { withSpan } from '@kbn/apm-utils';
import { getSystemActionKibanaPrivileges } from '../../../../lib/get_system_action_kibana_privileges';
import { validateSystemActions } from '../../../../lib/validate_system_actions';
import { validateAndAuthorizeSystemActions } from '../../../../lib/validate_authorize_system_actions';
import { RULE_SAVED_OBJECT_TYPE } from '../../../../saved_objects';
import { parseDuration, getRuleCircuitBreakerErrorMessage } from '../../../../../common';
import { WriteOperations, AlertingAuthorizationEntity } from '../../../../authorization';
Expand Down Expand Up @@ -99,22 +98,14 @@ export async function createRule<Params extends RuleParams = never>(
}

try {
await withSpan({ name: 'authorization.ensureAuthorized', type: 'rules' }, async () => {
const additionalPrivileges = await getSystemActionKibanaPrivileges({
actionsClient,
connectorAdapterRegistry: context.connectorAdapterRegistry,
systemActions: data.systemActions,
consumer: data.consumer,
});

return context.authorization.ensureAuthorized({
await withSpan({ name: 'authorization.ensureAuthorized', type: 'rules' }, async () =>
context.authorization.ensureAuthorized({
ruleTypeId: data.alertTypeId,
consumer: data.consumer,
operation: WriteOperations.Create,
entity: AlertingAuthorizationEntity.Rule,
additionalPrivileges,
});
});
})
);
} catch (error) {
context.auditLogger?.log(
ruleAuditEvent({
Expand Down Expand Up @@ -158,11 +149,13 @@ export async function createRule<Params extends RuleParams = never>(
validateActions(context, ruleType, data, allowMissingConnectorSecrets)
);

await withSpan({ name: 'validateSystemActions', type: 'rules' }, () =>
validateSystemActions({
await withSpan({ name: 'validateAndAuthorizeSystemActions', type: 'rules' }, () =>
validateAndAuthorizeSystemActions({
actionsClient,
actionsAuthorization: context.actionsAuthorization,
connectorAdapterRegistry: context.connectorAdapterRegistry,
systemActions: data.systemActions,
rule: { consumer: data.consumer },
})
);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
/*
* 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 { ConnectorAdapterRegistry } from './connector_adapter_registry';
import { getSystemActionKibanaPrivileges } from './get_system_action_kibana_privileges';
import type { ConnectorAdapter } from './types';

describe('getSystemActionKibanaPrivileges', () => {
const connectorAdapter: ConnectorAdapter = {
connectorTypeId: '.test',
ruleActionParamsSchema: schema.object({ foo: schema.string() }),
buildActionParams: jest.fn(),
getKibanaPrivileges: (args) => [`my-priv:${args.consumer}`],
};

const systemActions = [
{ id: 'my-id', actionTypeId: '.test', params: {} },
{ id: 'my-id-2', actionTypeId: '.test-2', params: {} },
];

let registry: ConnectorAdapterRegistry;

beforeEach(() => {
registry = new ConnectorAdapterRegistry();
registry.register(connectorAdapter);

registry.register({
...connectorAdapter,
connectorTypeId: '.test-2',
getKibanaPrivileges: (args) => [`my-priv-2:${args.consumer}`],
});

registry.register({
...connectorAdapter,
connectorTypeId: '.no-priv',
});
});

it('should return an empty array if systemActions are empty', () => {
const privileges = getSystemActionKibanaPrivileges({
connectorAdapterRegistry: registry,
systemActions: [],
rule: { consumer: 'stackAlerts' },
});

expect(privileges).toEqual([]);
});

it('should return an empty array if systemActions are not defined', () => {
const privileges = getSystemActionKibanaPrivileges({
connectorAdapterRegistry: registry,
rule: { consumer: 'stackAlerts' },
});

expect(privileges).toEqual([]);
});

it('should return the privileges correctly', () => {
const privileges = getSystemActionKibanaPrivileges({
connectorAdapterRegistry: registry,
systemActions,
rule: { consumer: 'stackAlerts' },
});

expect(privileges).toEqual(['my-priv:stackAlerts', 'my-priv-2:stackAlerts']);
});

it('should return the privileges correctly with system actions without connector adapter', () => {
const privileges = getSystemActionKibanaPrivileges({
connectorAdapterRegistry: registry,
systemActions: [...systemActions, { id: 'my-id-2', actionTypeId: '.not-valid', params: {} }],
rule: { consumer: 'stackAlerts' },
});

expect(privileges).toEqual(['my-priv:stackAlerts', 'my-priv-2:stackAlerts']);
});

it('should return the privileges correctly with system actions without getKibanaPrivileges defined', () => {
const privileges = getSystemActionKibanaPrivileges({
connectorAdapterRegistry: registry,
systemActions: [...systemActions, { id: 'my-id-2', actionTypeId: '.no-priv', params: {} }],
rule: { consumer: 'stackAlerts' },
});

expect(privileges).toEqual(['my-priv:stackAlerts', 'my-priv-2:stackAlerts']);
});

it('should not return duplicated privileges', () => {
const privileges = getSystemActionKibanaPrivileges({
connectorAdapterRegistry: registry,
systemActions: [systemActions[0], systemActions[0]],
rule: { consumer: 'stackAlerts' },
});

expect(privileges).toEqual(['my-priv:stackAlerts']);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* 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 { RuleSystemAction } from '../types';
import { ConnectorAdapterRegistry } from './connector_adapter_registry';

interface Args {
connectorAdapterRegistry: ConnectorAdapterRegistry;
rule: { consumer: string };
systemActions?: RuleSystemAction[];
}

export const getSystemActionKibanaPrivileges = ({
connectorAdapterRegistry,
systemActions = [],
rule,
}: Args): string[] => {
const kibanaPrivileges = systemActions
.filter((action) => connectorAdapterRegistry.has(action.actionTypeId))
.map((action) => connectorAdapterRegistry.get(action.actionTypeId))
.map((adapter) => adapter.getKibanaPrivileges?.({ consumer: rule.consumer }) ?? [])
.flat();

return Array.from(new Set(kibanaPrivileges));
};

This file was deleted.

Loading

0 comments on commit 9af266a

Please sign in to comment.