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

[Actions] Authorize system action when create or editing rules #180437

Merged
merged 7 commits into from
Apr 10, 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 @@ -1581,6 +1581,114 @@ describe('bulkEdit()', () => {
}
`);
});

test('should throw an error if the user does not have privileges to execute the action', async () => {
const defaultAction = {
frequency: {
notifyWhen: 'onActiveAlert' as const,
summary: false,
throttle: null,
},
group: 'default',
id: '1',
params: {},
};

const systemAction = {
id: 'system_action-id',
params: {},
};

unsecuredSavedObjectsClient.bulkCreate.mockResolvedValue({
saved_objects: [
{
...existingRule,
attributes: {
...existingRule.attributes,
actions: [
{
frequency: {
notifyWhen: 'onActiveAlert' as const,
summary: false,
throttle: null,
},
group: 'default',
params: {},
actionRef: 'action_0',
actionTypeId: 'test-1',
uuid: '222',
},
{
params: {},
actionRef: 'system_action:system_action-id',
actionTypeId: 'test-2',
uuid: '222',
},
],
},
references: [
{
name: 'action_0',
type: 'action',
id: '1',
},
],
},
],
});

actionsClient.getBulk.mockResolvedValue([
{
id: '1',
actionTypeId: 'test-1',
config: {},
isMissingSecrets: false,
name: 'test default connector',
isPreconfigured: false,
isDeprecated: false,
isSystemAction: false,
},
{
id: 'system_action-id',
actionTypeId: 'test-2',
config: {},
isMissingSecrets: false,
name: 'system action connector',
isPreconfigured: false,
isDeprecated: false,
isSystemAction: true,
},
]);

actionsAuthorization.ensureAuthorized.mockRejectedValueOnce(
new Error('Unauthorized to execute actions')
);

const res = await rulesClient.bulkEdit({
filter: '',
operations: [
{
field: 'actions',
operation: 'add',
value: [defaultAction, systemAction],
},
],
});

expect(res.rules.length).toBe(0);
expect(res.skipped.length).toBe(0);
expect(res.total).toBe(1);

expect(res.errors).toEqual([
{
message: 'Unauthorized to execute actions',
rule: {
id: '1',
name: 'my rule name',
},
},
]);
});
});

describe('index pattern operations', () => {
Expand Down
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(
new Error('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(
`[Error: Unauthorized to execute actions]`
);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +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 { 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 @@ -98,7 +98,7 @@ export async function createRule<Params extends RuleParams = never>(
}

try {
await withSpan({ name: 'authorization.ensureAuthorized', type: 'rules' }, () =>
await withSpan({ name: 'authorization.ensureAuthorized', type: 'rules' }, async () =>
context.authorization.ensureAuthorized({
ruleTypeId: data.alertTypeId,
consumer: data.consumer,
Expand Down Expand Up @@ -149,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
Expand Up @@ -750,6 +750,49 @@ describe('AlertingAuthorization', () => {
`"Unauthorized by \\"myOtherApp\\" to create \\"myType\\" alert"`
);
});

test('checks additional privileges correctly', async () => {
const { authorization } = mockSecurity();
const checkPrivileges: jest.MockedFunction<
ReturnType<typeof authorization.checkPrivilegesDynamicallyWithRequest>
> = jest.fn();
authorization.checkPrivilegesDynamicallyWithRequest.mockReturnValue(checkPrivileges);
const alertAuthorization = new AlertingAuthorization({
request,
authorization,
ruleTypeRegistry,
features,
getSpace,
getSpaceId,
});

checkPrivileges.mockResolvedValueOnce({
username: 'some-user',
hasAllRequested: true,
privileges: { kibana: [] },
});

await alertAuthorization.ensureAuthorized({
ruleTypeId: 'myType',
consumer: 'myApp',
operation: WriteOperations.Create,
entity: AlertingAuthorizationEntity.Rule,
additionalPrivileges: ['test/create'],
});

expect(ruleTypeRegistry.get).toHaveBeenCalledWith('myType');

expect(authorization.actions.alerting.get).toHaveBeenCalledTimes(1);
expect(authorization.actions.alerting.get).toHaveBeenCalledWith(
'myType',
'myApp',
'rule',
'create'
);
expect(checkPrivileges).toHaveBeenCalledWith({
kibana: [mockAuthorizationAction('myType', 'myApp', 'rule', 'create'), 'test/create'],
});
});
});

describe('getFindAuthorizationFilter', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ export interface EnsureAuthorizedOpts {
consumer: string;
operation: ReadOperations | WriteOperations;
entity: AlertingAuthorizationEntity;
additionalPrivileges?: string[];
}

interface HasPrivileges {
Expand Down Expand Up @@ -172,6 +173,7 @@ export class AlertingAuthorization {
consumer: legacyConsumer,
operation,
entity,
additionalPrivileges = [],
}: EnsureAuthorizedOpts) {
const { authorization } = this;
const ruleType = this.ruleTypeRegistry.get(ruleTypeId);
Expand All @@ -186,7 +188,10 @@ export class AlertingAuthorization {
const checkPrivileges = authorization.checkPrivilegesDynamicallyWithRequest(this.request);

const { hasAllRequested } = await checkPrivileges({
kibana: [authorization.actions.alerting.get(ruleTypeId, consumer, entity, operation)],
kibana: [
authorization.actions.alerting.get(ruleTypeId, consumer, entity, operation),
...additionalPrivileges,
],
});

if (!isAvailableConsumer) {
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']);
});
});
Loading