-
Notifications
You must be signed in to change notification settings - Fork 8.2k
/
alerting_authorization.ts
506 lines (466 loc) · 17.1 KB
/
alerting_authorization.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
/*
* 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 Boom from '@hapi/boom';
import { map, mapValues, fromPairs, has } from 'lodash';
import { KibanaRequest } from 'src/core/server';
import { JsonObject } from '@kbn/utility-types';
import { KueryNode } from '@kbn/es-query';
import { ALERTS_FEATURE_ID, RuleTypeRegistry } from '../types';
import { SecurityPluginSetup } from '../../../security/server';
import { RegistryRuleType } from '../rule_type_registry';
import { PluginStartContract as FeaturesPluginStart } from '../../../features/server';
import { AlertingAuthorizationAuditLogger, ScopeType } from './audit_logger';
import { Space } from '../../../spaces/server';
import {
asFiltersByRuleTypeAndConsumer,
asFiltersBySpaceId,
AlertingAuthorizationFilterOpts,
} from './alerting_authorization_kuery';
export enum AlertingAuthorizationEntity {
Rule = 'rule',
Alert = 'alert',
}
export enum ReadOperations {
Get = 'get',
GetRuleState = 'getRuleState',
GetAlertSummary = 'getAlertSummary',
Find = 'find',
}
export enum WriteOperations {
Create = 'create',
Delete = 'delete',
Update = 'update',
UpdateApiKey = 'updateApiKey',
Enable = 'enable',
Disable = 'disable',
MuteAll = 'muteAll',
UnmuteAll = 'unmuteAll',
MuteAlert = 'muteAlert',
UnmuteAlert = 'unmuteAlert',
}
export interface EnsureAuthorizedOpts {
ruleTypeId: string;
consumer: string;
operation: ReadOperations | WriteOperations;
entity: AlertingAuthorizationEntity;
}
interface HasPrivileges {
read: boolean;
all: boolean;
}
type AuthorizedConsumers = Record<string, HasPrivileges>;
export interface RegistryAlertTypeWithAuth extends RegistryRuleType {
authorizedConsumers: AuthorizedConsumers;
}
type IsAuthorizedAtProducerLevel = boolean;
export interface ConstructorOptions {
ruleTypeRegistry: RuleTypeRegistry;
request: KibanaRequest;
features: FeaturesPluginStart;
getSpace: (request: KibanaRequest) => Promise<Space | undefined>;
getSpaceId: (request: KibanaRequest) => string | undefined;
auditLogger: AlertingAuthorizationAuditLogger;
authorization?: SecurityPluginSetup['authz'];
}
export class AlertingAuthorization {
private readonly ruleTypeRegistry: RuleTypeRegistry;
private readonly request: KibanaRequest;
private readonly authorization?: SecurityPluginSetup['authz'];
private readonly auditLogger: AlertingAuthorizationAuditLogger;
private readonly featuresIds: Promise<Set<string>>;
private readonly allPossibleConsumers: Promise<AuthorizedConsumers>;
private readonly spaceId: string | undefined;
constructor({
ruleTypeRegistry,
request,
authorization,
features,
auditLogger,
getSpace,
getSpaceId,
}: ConstructorOptions) {
this.request = request;
this.authorization = authorization;
this.ruleTypeRegistry = ruleTypeRegistry;
this.auditLogger = auditLogger;
this.spaceId = getSpaceId(request);
this.featuresIds = getSpace(request)
.then((maybeSpace) => new Set(maybeSpace?.disabledFeatures ?? []))
.then(
(disabledFeatures) =>
new Set(
features
.getKibanaFeatures()
.filter(
({ id, alerting }) =>
// ignore features which are disabled in the user's space
!disabledFeatures.has(id) &&
// ignore features which don't grant privileges to alerting
(alerting?.length ?? 0 > 0)
)
.map((feature) => feature.id)
)
)
.catch(() => {
// failing to fetch the space means the user is likely not privileged in the
// active space at all, which means that their list of features should be empty
return new Set();
});
this.allPossibleConsumers = this.featuresIds.then((featuresIds) => {
return featuresIds.size
? asAuthorizedConsumers([ALERTS_FEATURE_ID, ...featuresIds], {
read: true,
all: true,
})
: {};
});
}
private shouldCheckAuthorization(): boolean {
return this.authorization?.mode?.useRbacForRequest(this.request) ?? false;
}
public getSpaceId(): string | undefined {
return this.spaceId;
}
/*
* This method exposes the private 'augmentRuleTypesWithAuthorization' to be
* used by the RAC/Alerts client
*/
public async getAugmentedRuleTypesWithAuthorization(
featureIds: readonly string[],
operations: Array<ReadOperations | WriteOperations>,
authorizationEntity: AlertingAuthorizationEntity
): Promise<{
username?: string;
hasAllRequested: boolean;
authorizedRuleTypes: Set<RegistryAlertTypeWithAuth>;
}> {
return this.augmentRuleTypesWithAuthorization(
this.ruleTypeRegistry.list(),
operations,
authorizationEntity,
new Set(featureIds)
);
}
public async ensureAuthorized({ ruleTypeId, consumer, operation, entity }: EnsureAuthorizedOpts) {
const { authorization } = this;
const isAvailableConsumer = has(await this.allPossibleConsumers, consumer);
if (authorization && this.shouldCheckAuthorization()) {
const ruleType = this.ruleTypeRegistry.get(ruleTypeId);
const requiredPrivilegesByScope = {
consumer: authorization.actions.alerting.get(ruleTypeId, consumer, entity, operation),
producer: authorization.actions.alerting.get(
ruleTypeId,
ruleType.producer,
entity,
operation
),
};
// Skip authorizing consumer if consumer is the Rules Management consumer (`alerts`)
// This means that rules and their derivative alerts created in the Rules Management UI
// will only be subject to checking if user has access to the rule producer.
const shouldAuthorizeConsumer = consumer !== ALERTS_FEATURE_ID;
const checkPrivileges = authorization.checkPrivilegesDynamicallyWithRequest(this.request);
const { hasAllRequested, username, privileges } = await checkPrivileges({
kibana:
shouldAuthorizeConsumer && consumer !== ruleType.producer
? [
// check for access at consumer level
requiredPrivilegesByScope.consumer,
// check for access at producer level
requiredPrivilegesByScope.producer,
]
: [
// skip consumer privilege checks under `alerts` as all rule types can
// be created under `alerts` if you have producer level privileges
requiredPrivilegesByScope.producer,
],
});
if (!isAvailableConsumer) {
/**
* Under most circumstances this would have been caught by `checkPrivileges` as
* a user can't have Privileges to an unknown consumer, but super users
* don't actually get "privilege checked" so the made up consumer *will* return
* as Privileged.
* This check will ensure we don't accidentally let these through
*/
throw Boom.forbidden(
this.auditLogger.logAuthorizationFailure(
username,
ruleTypeId,
ScopeType.Consumer,
consumer,
operation,
entity
)
);
}
if (hasAllRequested) {
this.auditLogger.logAuthorizationSuccess(
username,
ruleTypeId,
ScopeType.Consumer,
consumer,
operation,
entity
);
} else {
const authorizedPrivileges = map(
privileges.kibana.filter((privilege) => privilege.authorized),
'privilege'
);
const unauthorizedScopes = mapValues(
requiredPrivilegesByScope,
(privilege) => !authorizedPrivileges.includes(privilege)
);
const [unauthorizedScopeType, unauthorizedScope] =
shouldAuthorizeConsumer && unauthorizedScopes.consumer
? [ScopeType.Consumer, consumer]
: [ScopeType.Producer, ruleType.producer];
throw Boom.forbidden(
this.auditLogger.logAuthorizationFailure(
username,
ruleTypeId,
unauthorizedScopeType,
unauthorizedScope,
operation,
entity
)
);
}
} else if (!isAvailableConsumer) {
throw Boom.forbidden(
this.auditLogger.logAuthorizationFailure(
'',
ruleTypeId,
ScopeType.Consumer,
consumer,
operation,
entity
)
);
}
}
public async getFindAuthorizationFilter(
authorizationEntity: AlertingAuthorizationEntity,
filterOpts: AlertingAuthorizationFilterOpts
): Promise<{
filter?: KueryNode | JsonObject;
ensureRuleTypeIsAuthorized: (ruleTypeId: string, consumer: string, auth: string) => void;
logSuccessfulAuthorization: () => void;
}> {
return this.getAuthorizationFilter(authorizationEntity, filterOpts, ReadOperations.Find);
}
public async getAuthorizationFilter(
authorizationEntity: AlertingAuthorizationEntity,
filterOpts: AlertingAuthorizationFilterOpts,
operation: WriteOperations | ReadOperations
): Promise<{
filter?: KueryNode | JsonObject;
ensureRuleTypeIsAuthorized: (ruleTypeId: string, consumer: string, auth: string) => void;
logSuccessfulAuthorization: () => void;
}> {
if (this.authorization && this.shouldCheckAuthorization()) {
const { username, authorizedRuleTypes } = await this.augmentRuleTypesWithAuthorization(
this.ruleTypeRegistry.list(),
[operation],
authorizationEntity
);
if (!authorizedRuleTypes.size) {
throw Boom.forbidden(
this.auditLogger.logUnscopedAuthorizationFailure(username!, 'find', authorizationEntity)
);
}
const authorizedRuleTypeIdsToConsumers = new Set<string>(
[...authorizedRuleTypes].reduce<string[]>((ruleTypeIdConsumerPairs, ruleType) => {
for (const consumer of Object.keys(ruleType.authorizedConsumers)) {
ruleTypeIdConsumerPairs.push(`${ruleType.id}/${consumer}/${authorizationEntity}`);
}
return ruleTypeIdConsumerPairs;
}, [])
);
const authorizedEntries: Map<string, Set<string>> = new Map();
return {
filter: asFiltersByRuleTypeAndConsumer(
authorizedRuleTypes,
filterOpts,
this.spaceId
) as JsonObject,
ensureRuleTypeIsAuthorized: (ruleTypeId: string, consumer: string, authType: string) => {
if (!authorizedRuleTypeIdsToConsumers.has(`${ruleTypeId}/${consumer}/${authType}`)) {
throw Boom.forbidden(
this.auditLogger.logAuthorizationFailure(
username!,
ruleTypeId,
ScopeType.Consumer,
consumer,
'find',
authorizationEntity
)
);
} else {
if (authorizedEntries.has(ruleTypeId)) {
authorizedEntries.get(ruleTypeId)!.add(consumer);
} else {
authorizedEntries.set(ruleTypeId, new Set([consumer]));
}
}
},
logSuccessfulAuthorization: () => {
if (authorizedEntries.size) {
this.auditLogger.logBulkAuthorizationSuccess(
username!,
[...authorizedEntries.entries()].reduce<Array<[string, string]>>(
(authorizedPairs, [alertTypeId, consumers]) => {
for (const consumer of consumers) {
authorizedPairs.push([alertTypeId, consumer]);
}
return authorizedPairs;
},
[]
),
ScopeType.Consumer,
'find',
authorizationEntity
);
}
},
};
}
return {
filter: asFiltersBySpaceId(filterOpts, this.spaceId) as JsonObject,
ensureRuleTypeIsAuthorized: (ruleTypeId: string, consumer: string, authType: string) => {},
logSuccessfulAuthorization: () => {},
};
}
public async filterByRuleTypeAuthorization(
ruleTypes: Set<RegistryRuleType>,
operations: Array<ReadOperations | WriteOperations>,
authorizationEntity: AlertingAuthorizationEntity
): Promise<Set<RegistryAlertTypeWithAuth>> {
const { authorizedRuleTypes } = await this.augmentRuleTypesWithAuthorization(
ruleTypes,
operations,
authorizationEntity
);
return authorizedRuleTypes;
}
private async augmentRuleTypesWithAuthorization(
ruleTypes: Set<RegistryRuleType>,
operations: Array<ReadOperations | WriteOperations>,
authorizationEntity: AlertingAuthorizationEntity,
featuresIds?: Set<string>
): Promise<{
username?: string;
hasAllRequested: boolean;
authorizedRuleTypes: Set<RegistryAlertTypeWithAuth>;
}> {
const fIds = featuresIds ?? (await this.featuresIds);
if (this.authorization && this.shouldCheckAuthorization()) {
const checkPrivileges = this.authorization.checkPrivilegesDynamicallyWithRequest(
this.request
);
// add an empty `authorizedConsumers` array on each ruleType
const ruleTypesWithAuthorization = this.augmentWithAuthorizedConsumers(ruleTypes, {});
// map from privilege to ruleType which we can refer back to when analyzing the result
// of checkPrivileges
const privilegeToRuleType = new Map<
string,
[RegistryAlertTypeWithAuth, string, HasPrivileges, IsAuthorizedAtProducerLevel]
>();
// as we can't ask ES for the user's individual privileges we need to ask for each feature
// and ruleType in the system whether this user has this privilege
for (const ruleType of ruleTypesWithAuthorization) {
for (const feature of fIds) {
for (const operation of operations) {
privilegeToRuleType.set(
this.authorization!.actions.alerting.get(
ruleType.id,
feature,
authorizationEntity,
operation
),
[ruleType, feature, hasPrivilegeByOperation(operation), ruleType.producer === feature]
);
}
}
}
const { username, hasAllRequested, privileges } = await checkPrivileges({
kibana: [...privilegeToRuleType.keys()],
});
return {
username,
hasAllRequested,
authorizedRuleTypes: hasAllRequested
? // has access to all features
this.augmentWithAuthorizedConsumers(ruleTypes, await this.allPossibleConsumers)
: // only has some of the required privileges
privileges.kibana.reduce((authorizedRuleTypes, { authorized, privilege }) => {
if (authorized && privilegeToRuleType.has(privilege)) {
const [
ruleType,
feature,
hasPrivileges,
isAuthorizedAtProducerLevel,
] = privilegeToRuleType.get(privilege)!;
ruleType.authorizedConsumers[feature] = mergeHasPrivileges(
hasPrivileges,
ruleType.authorizedConsumers[feature]
);
if (isAuthorizedAtProducerLevel) {
// granting privileges under the producer automatically authorized the Rules Management UI as well
ruleType.authorizedConsumers[ALERTS_FEATURE_ID] = mergeHasPrivileges(
hasPrivileges,
ruleType.authorizedConsumers[ALERTS_FEATURE_ID]
);
}
authorizedRuleTypes.add(ruleType);
}
return authorizedRuleTypes;
}, new Set<RegistryAlertTypeWithAuth>()),
};
} else {
return {
hasAllRequested: true,
authorizedRuleTypes: this.augmentWithAuthorizedConsumers(
new Set([...ruleTypes].filter((ruleType) => fIds.has(ruleType.producer))),
await this.allPossibleConsumers
),
};
}
}
private augmentWithAuthorizedConsumers(
ruleTypes: Set<RegistryRuleType>,
authorizedConsumers: AuthorizedConsumers
): Set<RegistryAlertTypeWithAuth> {
return new Set(
Array.from(ruleTypes).map((ruleType) => ({
...ruleType,
authorizedConsumers: { ...authorizedConsumers },
}))
);
}
}
function mergeHasPrivileges(left: HasPrivileges, right?: HasPrivileges): HasPrivileges {
return {
read: (left.read || right?.read) ?? false,
all: (left.all || right?.all) ?? false,
};
}
function hasPrivilegeByOperation(operation: ReadOperations | WriteOperations): HasPrivileges {
const read = Object.values(ReadOperations).includes((operation as unknown) as ReadOperations);
const all = Object.values(WriteOperations).includes((operation as unknown) as WriteOperations);
return {
read: read || all,
all,
};
}
function asAuthorizedConsumers(
consumers: string[],
hasPrivileges: HasPrivileges
): AuthorizedConsumers {
return fromPairs(consumers.map((feature) => [feature, hasPrivileges]));
}