-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
secure_spaces_client_wrapper.ts
405 lines (358 loc) · 12.8 KB
/
secure_spaces_client_wrapper.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
/*
* 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 type { KibanaRequest, SavedObjectsClientContract } from 'src/core/server';
import type {
GetAllSpacesOptions,
GetAllSpacesPurpose,
GetSpaceResult,
ISpacesClient,
LegacyUrlAliasTarget,
Space,
} from '../../../spaces/server';
import type { AuditLogger } from '../audit';
import { SavedObjectAction, savedObjectEvent, SpaceAuditAction, spaceAuditEvent } from '../audit';
import type { AuthorizationServiceSetup } from '../authorization';
import type { SecurityPluginSetup } from '../plugin';
import type { EnsureAuthorizedDependencies, EnsureAuthorizedOptions } from '../saved_objects';
import { ensureAuthorized, isAuthorizedForObjectInAllSpaces } from '../saved_objects';
import type { LegacySpacesAuditLogger } from './legacy_audit_logger';
const PURPOSE_PRIVILEGE_MAP: Record<
GetAllSpacesPurpose,
(authorization: SecurityPluginSetup['authz']) => string[]
> = {
any: (authorization) => [authorization.actions.login],
copySavedObjectsIntoSpace: (authorization) => [
authorization.actions.ui.get('savedObjectsManagement', 'copyIntoSpace'),
],
findSavedObjects: (authorization) => {
return [authorization.actions.login, authorization.actions.savedObject.get('config', 'find')];
},
shareSavedObjectsIntoSpace: (authorization) => [
authorization.actions.ui.get('savedObjectsManagement', 'shareIntoSpace'),
],
};
/** @internal */
export const LEGACY_URL_ALIAS_TYPE = 'legacy-url-alias';
export class SecureSpacesClientWrapper implements ISpacesClient {
private readonly useRbac = this.authorization.mode.useRbacForRequest(this.request);
constructor(
private readonly spacesClient: ISpacesClient,
private readonly request: KibanaRequest,
private readonly authorization: AuthorizationServiceSetup,
private readonly auditLogger: AuditLogger,
private readonly legacyAuditLogger: LegacySpacesAuditLogger,
private readonly errors: SavedObjectsClientContract['errors']
) {}
public async getAll({
purpose = 'any',
includeAuthorizedPurposes,
}: GetAllSpacesOptions = {}): Promise<GetSpaceResult[]> {
const allSpaces = await this.spacesClient.getAll({ purpose, includeAuthorizedPurposes });
if (!this.useRbac) {
allSpaces.forEach(({ id }) =>
this.auditLogger.log(
spaceAuditEvent({
action: SpaceAuditAction.FIND,
savedObject: { type: 'space', id },
})
)
);
return allSpaces;
}
const spaceIds = allSpaces.map((space: Space) => space.id);
const checkPrivileges = this.authorization.checkPrivilegesWithRequest(this.request);
// Collect all privileges which need to be checked
const allPrivileges = Object.entries(PURPOSE_PRIVILEGE_MAP).reduce(
(acc, [getSpacesPurpose, privilegeFactory]) =>
!includeAuthorizedPurposes && getSpacesPurpose !== purpose
? acc
: { ...acc, [getSpacesPurpose]: privilegeFactory(this.authorization) },
{} as Record<GetAllSpacesPurpose, string[]>
);
// Check all privileges against all spaces
const { username, privileges } = await checkPrivileges.atSpaces(spaceIds, {
kibana: Object.values(allPrivileges).flat(),
});
// Determine which purposes the user is authorized for within each space.
// Remove any spaces for which user is fully unauthorized.
const checkHasAllRequired = (space: Space, actions: string[]) =>
actions.every((action) =>
privileges.kibana.some(
({ resource, privilege, authorized }) =>
resource === space.id && privilege === action && authorized
)
);
const authorizedSpaces: GetSpaceResult[] = allSpaces
.map((space: Space) => {
if (!includeAuthorizedPurposes) {
// Check if the user is authorized for a single purpose
const requiredActions = PURPOSE_PRIVILEGE_MAP[purpose](this.authorization);
return checkHasAllRequired(space, requiredActions) ? space : null;
}
// Check if the user is authorized for each purpose
let hasAnyAuthorization = false;
const authorizedPurposes = Object.entries(PURPOSE_PRIVILEGE_MAP).reduce(
(acc, [purposeKey, privilegeFactory]) => {
const requiredActions = privilegeFactory(this.authorization);
const hasAllRequired = checkHasAllRequired(space, requiredActions);
hasAnyAuthorization = hasAnyAuthorization || hasAllRequired;
return { ...acc, [purposeKey]: hasAllRequired };
},
{} as Record<GetAllSpacesPurpose, boolean>
);
if (!hasAnyAuthorization) {
return null;
}
return { ...space, authorizedPurposes };
})
.filter(this.filterUnauthorizedSpaceResults);
if (authorizedSpaces.length === 0) {
const error = Boom.forbidden();
this.legacyAuditLogger.spacesAuthorizationFailure(username, 'getAll');
this.auditLogger.log(
spaceAuditEvent({
action: SpaceAuditAction.FIND,
error,
})
);
throw error; // Note: there is a catch for this in `SpacesSavedObjectsClient.find`; if we get rid of this error, remove that too
}
const authorizedSpaceIds = authorizedSpaces.map((space) => space.id);
this.legacyAuditLogger.spacesAuthorizationSuccess(username, 'getAll', authorizedSpaceIds);
authorizedSpaces.forEach(({ id }) =>
this.auditLogger.log(
spaceAuditEvent({
action: SpaceAuditAction.FIND,
savedObject: { type: 'space', id },
})
)
);
return authorizedSpaces;
}
public async get(id: string) {
if (this.useRbac) {
try {
await this.ensureAuthorizedAtSpace(
id,
this.authorization.actions.login,
'get',
`Unauthorized to get ${id} space`
);
} catch (error) {
this.auditLogger.log(
spaceAuditEvent({
action: SpaceAuditAction.GET,
savedObject: { type: 'space', id },
error,
})
);
throw error;
}
}
const space = this.spacesClient.get(id);
this.auditLogger.log(
spaceAuditEvent({
action: SpaceAuditAction.GET,
savedObject: { type: 'space', id },
})
);
return space;
}
public async create(space: Space) {
if (this.useRbac) {
try {
await this.ensureAuthorizedGlobally(
this.authorization.actions.space.manage,
'create',
'Unauthorized to create spaces'
);
} catch (error) {
this.auditLogger.log(
spaceAuditEvent({
action: SpaceAuditAction.CREATE,
savedObject: { type: 'space', id: space.id },
error,
})
);
throw error;
}
}
this.auditLogger.log(
spaceAuditEvent({
action: SpaceAuditAction.CREATE,
outcome: 'unknown',
savedObject: { type: 'space', id: space.id },
})
);
return this.spacesClient.create(space);
}
public async update(id: string, space: Space) {
if (this.useRbac) {
try {
await this.ensureAuthorizedGlobally(
this.authorization.actions.space.manage,
'update',
'Unauthorized to update spaces'
);
} catch (error) {
this.auditLogger.log(
spaceAuditEvent({
action: SpaceAuditAction.UPDATE,
savedObject: { type: 'space', id },
error,
})
);
throw error;
}
}
this.auditLogger.log(
spaceAuditEvent({
action: SpaceAuditAction.UPDATE,
outcome: 'unknown',
savedObject: { type: 'space', id },
})
);
return this.spacesClient.update(id, space);
}
public async delete(id: string) {
if (this.useRbac) {
try {
await this.ensureAuthorizedGlobally(
this.authorization.actions.space.manage,
'delete',
'Unauthorized to delete spaces'
);
} catch (error) {
this.auditLogger.log(
spaceAuditEvent({
action: SpaceAuditAction.DELETE,
savedObject: { type: 'space', id },
error,
})
);
throw error;
}
}
this.auditLogger.log(
spaceAuditEvent({
action: SpaceAuditAction.DELETE,
outcome: 'unknown',
savedObject: { type: 'space', id },
})
);
return this.spacesClient.delete(id);
}
public async disableLegacyUrlAliases(aliases: LegacyUrlAliasTarget[]) {
if (this.useRbac) {
try {
const [uniqueSpaces, uniqueTypes, typesAndSpacesMap] = aliases.reduce(
([spaces, types, typesAndSpaces], { targetSpace, targetType }) => {
const spacesForType = typesAndSpaces.get(targetType) ?? new Set();
return [
spaces.add(targetSpace),
types.add(targetType),
typesAndSpaces.set(targetType, spacesForType.add(targetSpace)),
];
},
[new Set<string>(), new Set<string>(), new Map<string, Set<string>>()]
);
const action = 'bulk_update';
const { typeActionMap } = await this.ensureAuthorizedForSavedObjects(
Array.from(uniqueTypes),
[action],
Array.from(uniqueSpaces),
{ requireFullAuthorization: false }
);
const unauthorizedTypes = new Set<string>();
for (const type of uniqueTypes) {
const spaces = Array.from(typesAndSpacesMap.get(type)!);
if (!isAuthorizedForObjectInAllSpaces(type, action, typeActionMap, spaces)) {
unauthorizedTypes.add(type);
}
}
if (unauthorizedTypes.size > 0) {
const targetTypes = Array.from(unauthorizedTypes).sort().join(',');
const msg = `Unable to disable aliases for ${targetTypes}`;
throw this.errors.decorateForbiddenError(new Error(msg));
}
} catch (error) {
aliases.forEach((alias) => {
const id = getAliasId(alias);
this.auditLogger.log(
savedObjectEvent({
action: SavedObjectAction.UPDATE,
savedObject: { type: LEGACY_URL_ALIAS_TYPE, id },
error,
})
);
});
throw error;
}
}
aliases.forEach((alias) => {
const id = getAliasId(alias);
this.auditLogger.log(
savedObjectEvent({
action: SavedObjectAction.UPDATE,
outcome: 'unknown',
savedObject: { type: LEGACY_URL_ALIAS_TYPE, id },
})
);
});
return this.spacesClient.disableLegacyUrlAliases(aliases);
}
private async ensureAuthorizedForSavedObjects<T extends string>(
types: string[],
actions: T[],
namespaces: string[],
options?: EnsureAuthorizedOptions
) {
const ensureAuthorizedDependencies: EnsureAuthorizedDependencies = {
actions: this.authorization.actions,
errors: this.errors,
checkSavedObjectsPrivilegesAsCurrentUser: this.authorization.checkSavedObjectsPrivilegesWithRequest(
this.request
),
};
return ensureAuthorized(ensureAuthorizedDependencies, types, actions, namespaces, options);
}
private async ensureAuthorizedGlobally(action: string, method: string, forbiddenMessage: string) {
const checkPrivileges = this.authorization.checkPrivilegesWithRequest(this.request);
const { username, hasAllRequested } = await checkPrivileges.globally({ kibana: action });
if (hasAllRequested) {
this.legacyAuditLogger.spacesAuthorizationSuccess(username, method);
} else {
this.legacyAuditLogger.spacesAuthorizationFailure(username, method);
throw Boom.forbidden(forbiddenMessage);
}
}
private async ensureAuthorizedAtSpace(
spaceId: string,
action: string,
method: string,
forbiddenMessage: string
) {
const checkPrivileges = this.authorization.checkPrivilegesWithRequest(this.request);
const { username, hasAllRequested } = await checkPrivileges.atSpace(spaceId, {
kibana: action,
});
if (hasAllRequested) {
this.legacyAuditLogger.spacesAuthorizationSuccess(username, method, [spaceId]);
} else {
this.legacyAuditLogger.spacesAuthorizationFailure(username, method, [spaceId]);
throw Boom.forbidden(forbiddenMessage);
}
}
private filterUnauthorizedSpaceResults(value: GetSpaceResult | null): value is GetSpaceResult {
return value !== null;
}
}
/** @internal This is only exported for testing purposes. */
export function getAliasId({ targetSpace, targetType, sourceId }: LegacyUrlAliasTarget) {
return `${targetSpace}:${targetType}:${sourceId}`;
}