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

[ResponseOps][Alerts] Fix authorization issues with discover as consumers #192321

Merged
merged 14 commits into from
Sep 30, 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 @@ -5,7 +5,7 @@
* 2.0.
*/

import { fromKueryExpression } from '@kbn/es-query';
import { KueryNode, fromKueryExpression, toKqlExpression } from '@kbn/es-query';
import { KibanaRequest } from '@kbn/core/server';
import { ruleTypeRegistryMock } from '../rule_type_registry.mock';
import { securityMock } from '@kbn/security-plugin/server/mocks';
Expand Down Expand Up @@ -910,20 +910,19 @@ describe('AlertingAuthorization', () => {
getSpaceId,
});
ruleTypeRegistry.list.mockReturnValue(setOfAlertTypes);
expect(
(
await alertAuthorization.getFindAuthorizationFilter(AlertingAuthorizationEntity.Rule, {
type: AlertingAuthorizationFilterType.KQL,
fieldNames: {
ruleTypeId: 'path.to.rule_type_id',
consumer: 'consumer-field',
},
})
).filter
).toEqual(
fromKueryExpression(
`((path.to.rule_type_id:myAppAlertType and consumer-field:(alerts or myApp or myOtherApp or myAppWithSubFeature)) or (path.to.rule_type_id:mySecondAppAlertType and consumer-field:(alerts or myApp or myOtherApp or myAppWithSubFeature)) or (path.to.rule_type_id:myOtherAppAlertType and consumer-field:(alerts or myApp or myOtherApp or myAppWithSubFeature)))`
)

const filter = (
await alertAuthorization.getFindAuthorizationFilter(AlertingAuthorizationEntity.Rule, {
type: AlertingAuthorizationFilterType.KQL,
fieldNames: {
ruleTypeId: 'path.to.rule_type_id',
consumer: 'consumer-field',
},
})
).filter;

expect(toKqlExpression(filter as KueryNode)).toMatchInlineSnapshot(
`"((path.to.rule_type_id: myAppAlertType AND (consumer-field: alerts OR consumer-field: discover OR consumer-field: myApp OR consumer-field: myOtherApp OR consumer-field: myAppWithSubFeature)) OR (path.to.rule_type_id: mySecondAppAlertType AND (consumer-field: alerts OR consumer-field: discover OR consumer-field: myApp OR consumer-field: myOtherApp OR consumer-field: myAppWithSubFeature)) OR (path.to.rule_type_id: myOtherAppAlertType AND (consumer-field: alerts OR consumer-field: discover OR consumer-field: myApp OR consumer-field: myOtherApp OR consumer-field: myAppWithSubFeature)))"`
);
});
test('throws if user has no privileges to any rule type', async () => {
Expand Down Expand Up @@ -1274,6 +1273,10 @@ describe('AlertingAuthorization', () => {
"all": true,
"read": true,
},
"discover": Object {
"all": true,
"read": true,
},
"myApp": Object {
"all": true,
"read": true,
Expand Down Expand Up @@ -1311,6 +1314,10 @@ describe('AlertingAuthorization', () => {
"all": true,
"read": true,
},
"discover": Object {
"all": true,
"read": true,
},
"myApp": Object {
"all": true,
"read": true,
Expand Down Expand Up @@ -2251,20 +2258,18 @@ describe('AlertingAuthorization', () => {
});
});
test('creates a filter based on the privileged types', async () => {
expect(
(
await alertAuthorization.getFindAuthorizationFilter(AlertingAuthorizationEntity.Rule, {
type: AlertingAuthorizationFilterType.KQL,
fieldNames: {
ruleTypeId: 'path.to.rule_type_id',
consumer: 'consumer-field',
},
})
).filter
).toEqual(
fromKueryExpression(
`path.to.rule_type_id:.esQuery and consumer-field:(alerts or stackAlerts or discover)`
)
const filter = (
await alertAuthorization.getFindAuthorizationFilter(AlertingAuthorizationEntity.Rule, {
type: AlertingAuthorizationFilterType.KQL,
fieldNames: {
ruleTypeId: 'path.to.rule_type_id',
consumer: 'consumer-field',
},
})
).filter;

expect(toKqlExpression(filter as KueryNode)).toMatchInlineSnapshot(
`"(path.to.rule_type_id: .esQuery AND (consumer-field: alerts OR consumer-field: discover OR consumer-field: stackAlerts))"`
);
});
});
Expand Down Expand Up @@ -2557,21 +2562,20 @@ describe('AlertingAuthorization', () => {
expect(ruleTypeRegistry.get).toHaveBeenCalledTimes(1);
});
});

test('creates a filter based on the privileged types', async () => {
expect(
(
await alertAuthorization.getFindAuthorizationFilter(AlertingAuthorizationEntity.Rule, {
type: AlertingAuthorizationFilterType.KQL,
fieldNames: {
ruleTypeId: 'path.to.rule_type_id',
consumer: 'consumer-field',
},
})
).filter
).toEqual(
fromKueryExpression(
`(path.to.rule_type_id:.esQuery and consumer-field:(alerts or stackAlerts or logs or discover)) or (path.to.rule_type_id:.logs-threshold-o11y and consumer-field:(alerts or stackAlerts or logs or discover)) or (path.to.rule_type_id:.threshold-rule-o11y and consumer-field:(alerts or stackAlerts or logs or discover))`
)
const filter = (
await alertAuthorization.getFindAuthorizationFilter(AlertingAuthorizationEntity.Rule, {
type: AlertingAuthorizationFilterType.KQL,
fieldNames: {
ruleTypeId: 'path.to.rule_type_id',
consumer: 'consumer-field',
},
})
).filter;

expect(toKqlExpression(filter as KueryNode)).toMatchInlineSnapshot(
`"((path.to.rule_type_id: .esQuery AND (consumer-field: alerts OR consumer-field: discover OR consumer-field: stackAlerts OR consumer-field: logs)) OR (path.to.rule_type_id: .logs-threshold-o11y AND (consumer-field: alerts OR consumer-field: discover OR consumer-field: stackAlerts OR consumer-field: logs)) OR (path.to.rule_type_id: .threshold-rule-o11y AND (consumer-field: alerts OR consumer-field: discover OR consumer-field: stackAlerts OR consumer-field: logs)))"`
);
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { KueryNode } from '@kbn/es-query';
import { SecurityPluginSetup } from '@kbn/security-plugin/server';
import { FeaturesPluginStart } from '@kbn/features-plugin/server';
import { Space } from '@kbn/spaces-plugin/server';
import { STACK_ALERTS_FEATURE_ID } from '@kbn/rule-data-utils';
import { RegistryRuleType } from '../rule_type_registry';
import { ALERTING_FEATURE_ID, RuleTypeRegistry } from '../types';
import {
Expand Down Expand Up @@ -88,6 +89,8 @@ export interface ConstructorOptions {
authorization?: SecurityPluginSetup['authz'];
}

const DISCOVER_FEATURE_ID = 'discover';

export class AlertingAuthorization {
private readonly ruleTypeRegistry: RuleTypeRegistry;
private readonly request: KibanaRequest;
Expand Down Expand Up @@ -135,7 +138,7 @@ export class AlertingAuthorization {

this.allPossibleConsumers = this.featuresIds.then((featuresIds) => {
return featuresIds.size
? asAuthorizedConsumers([ALERTING_FEATURE_ID, ...featuresIds], {
? asAuthorizedConsumers([ALERTING_FEATURE_ID, DISCOVER_FEATURE_ID, ...featuresIds], {
read: true,
all: true,
})
Expand Down Expand Up @@ -328,7 +331,22 @@ export class AlertingAuthorization {
hasAllRequested: boolean;
authorizedRuleTypes: Set<RegistryAlertTypeWithAuth>;
}> {
const fIds = featuresIds ?? (await this.featuresIds);
const fIds = new Set(featuresIds ?? (await this.featuresIds));

/**
* Temporary hack to fix issues with the discover consumer.
* Issue: https://github.com/elastic/kibana/issues/184595.
* PR https://github.com/elastic/kibana/pull/183756 will
* remove the hack and fix it in a generic way.
*
* The discover consumer should be authorized
* as the stackAlerts consumer.
*/
if (fIds.has(DISCOVER_FEATURE_ID)) {
Copy link
Member

Choose a reason for hiding this comment

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

Will any of the callers be sensitive to this modification of the fIds Set? Looks like two calls take the set from params, so wondering if making this change could affect the callers. Or maybe it's supposed to?

If it's not supposed to, seems like it might be better to make a local copy of the set, to something like:

const fIds = new Set(featuresIds ?? (await this.featuresIds));

Copy link
Member Author

Choose a reason for hiding this comment

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

Good point Patrick! It is not supposed to change. Fixed in b0c35fe (#192321)

fIds.delete(DISCOVER_FEATURE_ID);
fIds.add(STACK_ALERTS_FEATURE_ID);
}

if (this.authorization && this.shouldCheckAuthorization()) {
const checkPrivileges = this.authorization.checkPrivilegesDynamicallyWithRequest(
this.request
Expand All @@ -347,11 +365,15 @@ export class AlertingAuthorization {
>();
const allPossibleConsumers = await this.allPossibleConsumers;
const addLegacyConsumerPrivileges = (legacyConsumer: string) =>
legacyConsumer === ALERTING_FEATURE_ID || isEmpty(featuresIds);
legacyConsumer === ALERTING_FEATURE_ID ||
legacyConsumer === DISCOVER_FEATURE_ID ||
isEmpty(featuresIds);

for (const feature of fIds) {
const featureDef = this.features
.getKibanaFeatures()
.find((kFeature) => kFeature.id === feature);

for (const ruleTypeId of featureDef?.alerting ?? []) {
const ruleTypeAuth = ruleTypesWithAuthorization.find((rtwa) => rtwa.id === ruleTypeId);
if (ruleTypeAuth) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ export function getAlertFormatters(fieldFormats: FieldFormatsRegistry) {
const producer = rowData?.find(({ field }) => field === ALERT_RULE_PRODUCER)?.value?.[0];
const consumer: AlertConsumers = observabilityFeatureIds.includes(producer)
? 'observability'
: producer && (value === 'alerts' || value === 'stackAlerts')
: producer && (value === 'alerts' || value === 'stackAlerts' || value === 'discover')
? producer
: value;
const consumerData = alertProducersData[consumer];
Expand Down
Binary file not shown.
18 changes: 18 additions & 0 deletions x-pack/test/rule_registry/common/lib/authentication/roles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,23 @@ export const logsOnlyAllSpacesAll: Role = {
},
};

export const stackAlertsOnlyAllSpacesAll: Role = {
name: 'stack_alerts_only_all_spaces_all',
privileges: {
elasticsearch: {
indices: [],
},
kibana: [
{
feature: {
stackAlerts: ['all'],
},
spaces: ['*'],
},
],
},
};

/**
* This role exists to test that the alert search strategy allows
* users who do not have access to security solutions the ability
Expand Down Expand Up @@ -494,6 +511,7 @@ export const allRoles = [
securitySolutionOnlyReadSpacesAll,
observabilityOnlyAllSpacesAll,
logsOnlyAllSpacesAll,
stackAlertsOnlyAllSpacesAll,
observabilityOnlyReadSpacesAll,
observabilityOnlyAllSpacesAllWithReadESIndices,
observabilityMinReadAlertsRead,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
observabilityMinReadAlertsAllSpacesAll,
observabilityOnlyAllSpacesAllWithReadESIndices,
securitySolutionOnlyAllSpacesAllWithReadESIndices,
stackAlertsOnlyAllSpacesAll,
} from './roles';
import { User } from './types';

Expand Down Expand Up @@ -176,6 +177,12 @@ export const logsOnlySpacesAll: User = {
roles: [logsOnlyAllSpacesAll.name],
};

export const stackAlertsOnlySpacesAll: User = {
username: 'stack_alerts_only_all_spaces_all',
password: 'stack_alerts_only_all_spaces_all',
roles: [stackAlertsOnlyAllSpacesAll.name],
};

export const obsOnlySpacesAllEsRead: User = {
username: 'obs_only_all_spaces_all_es_read',
password: 'obs_only_all_spaces_all_es_read',
Expand Down Expand Up @@ -290,6 +297,7 @@ export const allUsers = [
secOnlyReadSpacesAll,
obsOnlySpacesAll,
logsOnlySpacesAll,
stackAlertsOnlySpacesAll,
obsSecSpacesAll,
obsSecReadSpacesAll,
obsMinReadAlertsRead,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import {
obsOnlySpacesAll,
logsOnlySpacesAll,
secOnlySpacesAllEsReadAll,
stackAlertsOnlySpacesAll,
superUser,
} from '../../../common/lib/authentication/users';

type RuleRegistrySearchResponseWithErrors = RuleRegistrySearchResponse & {
Expand Down Expand Up @@ -346,6 +348,85 @@ export default ({ getService }: FtrProviderContext) => {
});
});

describe('discover', () => {
before(async () => {
await esArchiver.load('x-pack/test/functional/es_archives/observability/alerts');
});
after(async () => {
await esArchiver.unload('x-pack/test/functional/es_archives/observability/alerts');
});

it('should return alerts from .es-query rule type with consumer discover with access only to stack rules', async () => {
const result = await secureBsearch.send<RuleRegistrySearchResponse>({
supertestWithoutAuth,
auth: {
username: stackAlertsOnlySpacesAll.username,
password: stackAlertsOnlySpacesAll.password,
},
referer: 'test',
kibanaVersion,
internalOrigin: 'Kibana',
options: {
featureIds: ['discover'],
},
strategy: 'privateRuleRegistryAlertsSearchStrategy',
});

expect(result.rawResponse.hits.total).to.eql(1);

const consumers = result.rawResponse.hits.hits.map((hit) => {
return hit.fields?.['kibana.alert.rule.consumer'];
});

expect(consumers.every((consumer) => consumer === 'discover'));
});

it('should return alerts from .es-query rule type with consumer discover as superuser', async () => {
const result = await secureBsearch.send<RuleRegistrySearchResponse>({
supertestWithoutAuth,
auth: {
username: superUser.username,
password: superUser.password,
},
referer: 'test',
kibanaVersion,
internalOrigin: 'Kibana',
options: {
featureIds: ['discover'],
},
strategy: 'privateRuleRegistryAlertsSearchStrategy',
});

expect(result.rawResponse.hits.total).to.eql(1);

const consumers = result.rawResponse.hits.hits.map((hit) => {
return hit.fields?.['kibana.alert.rule.consumer'];
});

expect(consumers.every((consumer) => consumer === 'discover'));
});

it('should not return alerts from .es-query rule type with consumer discover without access to stack rules', async () => {
const result = await secureBsearch.send<RuleRegistrySearchResponseWithErrors>({
supertestWithoutAuth,
auth: {
username: logsOnlySpacesAll.username,
password: logsOnlySpacesAll.password,
},
referer: 'test',
kibanaVersion,
internalOrigin: 'Kibana',
options: {
featureIds: ['discover'],
},
strategy: 'privateRuleRegistryAlertsSearchStrategy',
});

expect(result.statusCode).to.be(500);
expect(result.message).to.be('Unauthorized to find alerts for any rule types');
});
});

describe('empty response', () => {
it('should return an empty response', async () => {
const result = await secureBsearch.send<RuleRegistrySearchResponse>({
Expand Down