/
access-service.ts
823 lines (733 loc) · 24.9 KB
/
access-service.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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
import * as permissions from '../types/permissions';
import { IUser } from '../types/user';
import {
IAccessInfo,
IAccessStore,
IGroupWithProjectRoles,
IProjectRoleUsage,
IRole,
IRoleDescriptor,
IRoleWithPermissions,
IUserPermission,
IUserRole,
IUserWithProjectRoles,
} from '../types/stores/access-store';
import { Logger } from '../logger';
import { IAccountStore, IUnleashStores } from '../types/stores';
import {
IAvailablePermissions,
ICustomRole,
IPermission,
IRoleData,
IUserWithRole,
RoleName,
} from '../types/model';
import { IRoleStore } from '../types/stores/role-store';
import NameExistsError from '../error/name-exists-error';
import { IEnvironmentStore } from '../features/project-environments/environment-store-type';
import RoleInUseError from '../error/role-in-use-error';
import { roleSchema } from '../schema/role-schema';
import {
ALL_ENVS,
ALL_PROJECTS,
CUSTOM_ROOT_ROLE_TYPE,
CUSTOM_PROJECT_ROLE_TYPE,
ROOT_ROLE_TYPES,
} from '../util/constants';
import { DEFAULT_PROJECT } from '../types/project';
import InvalidOperationError from '../error/invalid-operation-error';
import BadDataError from '../error/bad-data-error';
import { IGroup } from '../types/group';
import { GroupService } from './group-service';
import {
IFlagResolver,
IUnleashConfig,
IUserAccessOverview,
ROLE_CREATED,
ROLE_DELETED,
ROLE_UPDATED,
} from '../types';
import EventService from './event-service';
const { ADMIN } = permissions;
const PROJECT_ADMIN = [
permissions.UPDATE_PROJECT,
permissions.DELETE_PROJECT,
permissions.CREATE_FEATURE,
permissions.UPDATE_FEATURE,
permissions.DELETE_FEATURE,
];
/** @deprecated prefer to use NamePermissionRef */
export type IdPermissionRef = Pick<IPermission, 'id' | 'environment'>;
export type NamePermissionRef = Pick<IPermission, 'name' | 'environment'>;
export type PermissionRef = IdPermissionRef | NamePermissionRef;
export interface IRoleCreation {
name: string;
description: string;
type?: 'root-custom' | 'custom';
permissions?: PermissionRef[];
createdBy?: string;
}
export interface IRoleValidation {
name: string;
description?: string;
permissions?: PermissionRef[];
}
export interface IRoleUpdate {
id: number;
name: string;
description: string;
type?: 'root-custom' | 'custom';
permissions?: PermissionRef[];
createdBy?: string;
}
export interface AccessWithRoles {
roles: IRoleDescriptor[];
groups: IGroupWithProjectRoles[];
users: IUserWithProjectRoles[];
}
const isProjectPermission = (permission) => PROJECT_ADMIN.includes(permission);
export class AccessService {
private store: IAccessStore;
private accountStore: IAccountStore;
private roleStore: IRoleStore;
private groupService: GroupService;
private environmentStore: IEnvironmentStore;
private logger: Logger;
private flagResolver: IFlagResolver;
private eventService: EventService;
constructor(
{
accessStore,
accountStore,
roleStore,
environmentStore,
}: Pick<
IUnleashStores,
'accessStore' | 'accountStore' | 'roleStore' | 'environmentStore'
> & { groupStore?: any }, // TODO remove groupStore later, kept for backward compatibility with enterprise
{
getLogger,
flagResolver,
}: Pick<IUnleashConfig, 'getLogger' | 'flagResolver'>,
groupService: GroupService,
eventService: EventService,
) {
this.store = accessStore;
this.accountStore = accountStore;
this.roleStore = roleStore;
this.groupService = groupService;
this.environmentStore = environmentStore;
this.logger = getLogger('/services/access-service.ts');
this.flagResolver = flagResolver;
this.eventService = eventService;
}
/**
* Used to check if a user has access to the requested resource
*
* @param user
* @param permission
* @param projectId
*/
async hasPermission(
user: Pick<IUser, 'id' | 'permissions' | 'isAPI'>,
permission: string | string[],
projectId?: string,
environment?: string,
): Promise<boolean> {
const permissionsArray = Array.isArray(permission)
? permission
: [permission];
const permissionLogInfo =
permissionsArray.length === 1
? `permission=${permissionsArray[0]}`
: `permissions=[${permissionsArray.join(',')}]`;
this.logger.info(
`Checking ${permissionLogInfo}, userId=${user.id}, projectId=${projectId}, environment=${environment}`,
);
try {
const userP = await this.getPermissionsForUser(user);
return userP
.filter(
(p) =>
!p.project ||
p.project === projectId ||
p.project === ALL_PROJECTS,
)
.filter(
(p) =>
!p.environment ||
p.environment === environment ||
p.environment === ALL_ENVS,
)
.some(
(p) =>
permissionsArray.includes(p.permission) ||
p.permission === ADMIN,
);
} catch (e) {
this.logger.error(
`Error checking ${permissionLogInfo}, userId=${user.id} projectId=${projectId}`,
e,
);
return Promise.resolve(false);
}
}
async getPermissionsForUser(
user: Pick<IUser, 'id' | 'isAPI' | 'permissions'>,
): Promise<IUserPermission[]> {
if (user.isAPI) {
return user.permissions?.map((p) => ({
permission: p,
}));
}
return this.store.getPermissionsForUser(user.id);
}
async getPermissions(): Promise<IAvailablePermissions> {
const bindablePermissions = await this.store.getAvailablePermissions();
const environments = await this.environmentStore.getAll();
const rootPermissions = bindablePermissions.filter(
({ type }) => type === 'root',
);
const projectPermissions = bindablePermissions.filter((x) => {
return x.type === 'project';
});
const environmentPermissions = bindablePermissions.filter((perm) => {
return perm.type === 'environment';
});
const allEnvironmentPermissions = environments.map((env) => {
return {
name: env.name,
permissions: environmentPermissions.map((permission) => {
return { environment: env.name, ...permission };
}),
};
});
return {
root: rootPermissions,
project: projectPermissions,
environments: allEnvironmentPermissions,
};
}
async addUserToRole(
userId: number,
roleId: number,
projectId: string,
): Promise<void> {
return this.store.addUserToRole(userId, roleId, projectId);
}
async addGroupToRole(
groupId: number,
roleId: number,
createdBy: string,
projectId: string,
): Promise<void> {
return this.store.addGroupToRole(groupId, roleId, createdBy, projectId);
}
async addRoleAccessToProject(
users: IAccessInfo[],
groups: IAccessInfo[],
projectId: string,
roleId: number,
createdBy: string,
): Promise<void> {
return this.store.addRoleAccessToProject(
users,
groups,
projectId,
roleId,
createdBy,
);
}
async addAccessToProject(
roles: number[],
groups: number[],
users: number[],
projectId: string,
createdBy: string,
): Promise<void> {
if (roles.length === 0) {
throw new BadDataError(
"You can't grant access without any roles. The roles array you sent was empty.",
);
}
return this.store.addAccessToProject(
roles,
groups,
users,
projectId,
createdBy,
);
}
async setProjectRolesForUser(
projectId: string,
userId: number,
roles: number[],
): Promise<void> {
await this.store.setProjectRolesForUser(projectId, userId, roles);
}
async getProjectRolesForUser(
projectId: string,
userId: number,
): Promise<number[]> {
return this.store.getProjectRolesForUser(projectId, userId);
}
async setProjectRolesForGroup(
projectId: string,
groupId: number,
roles: number[],
createdBy: string,
): Promise<void> {
await this.store.setProjectRolesForGroup(
projectId,
groupId,
roles,
createdBy,
);
}
async getProjectRolesForGroup(
projectId: string,
groupId: number,
): Promise<number[]> {
return this.store.getProjectRolesForGroup(projectId, groupId);
}
async getRoleByName(roleName: string): Promise<IRole> {
return this.roleStore.getRoleByName(roleName);
}
async removeUserAccess(projectId: string, userId: number): Promise<void> {
await this.store.removeUserAccess(projectId, userId);
}
async removeGroupAccess(projectId: string, groupId: number): Promise<void> {
await this.store.removeGroupAccess(projectId, groupId);
}
async setUserRootRole(
userId: number,
role: number | RoleName,
): Promise<void> {
const newRootRole = await this.resolveRootRole(role);
if (newRootRole) {
try {
await this.store.removeRolesOfTypeForUser(
userId,
ROOT_ROLE_TYPES,
);
await this.store.addUserToRole(
userId,
newRootRole.id,
DEFAULT_PROJECT,
);
} catch (error) {
const message = `Could not add role=${newRootRole.name} to userId=${userId}`;
this.logger.error(message, error);
throw new Error(message);
}
} else {
throw new BadDataError(`Could not find rootRole=${role}`);
}
}
async getRootRoleForUser(userId: number): Promise<IRole> {
const rootRole = await this.store.getRootRoleForUser(userId);
if (!rootRole) {
const defaultRole = await this.getPredefinedRole(RoleName.VIEWER);
return defaultRole;
}
return rootRole;
}
async removeUserFromRole(
userId: number,
roleId: number,
projectId: string,
): Promise<void> {
return this.store.removeUserFromRole(userId, roleId, projectId);
}
async removeGroupFromRole(
groupId: number,
roleId: number,
projectId: string,
): Promise<void> {
return this.store.removeGroupFromRole(groupId, roleId, projectId);
}
async updateUserProjectRole(
userId: number,
roleId: number,
projectId: string,
): Promise<void> {
return this.store.updateUserProjectRole(userId, roleId, projectId);
}
async updateGroupProjectRole(
userId: number,
roleId: number,
projectId: string,
): Promise<void> {
return this.store.updateGroupProjectRole(userId, roleId, projectId);
}
//This actually only exists for testing purposes
async addPermissionToRole(
roleId: number,
permission: string,
environment?: string,
): Promise<void> {
if (isProjectPermission(permission) && !environment) {
throw new Error(
`ProjectId cannot be empty for permission=${permission}`,
);
}
return this.store.addPermissionsToRole(
roleId,
[{ name: permission }],
environment,
);
}
//This actually only exists for testing purposes
async removePermissionFromRole(
roleId: number,
permission: string,
environment?: string,
): Promise<void> {
if (isProjectPermission(permission) && !environment) {
throw new Error(
`ProjectId cannot be empty for permission=${permission}`,
);
}
return this.store.removePermissionFromRole(
roleId,
permission,
environment,
);
}
async getRoles(): Promise<IRole[]> {
return this.roleStore.getRoles();
}
async getRole(id: number): Promise<IRoleWithPermissions> {
const role = await this.store.get(id);
const rolePermissions = await this.store.getPermissionsForRole(role.id);
return {
...role,
permissions: rolePermissions,
};
}
async getRoleData(roleId: number): Promise<IRoleData> {
const [role, rolePerms, users] = await Promise.all([
this.store.get(roleId),
this.store.getPermissionsForRole(roleId),
this.getUsersForRole(roleId),
]);
return { role, permissions: rolePerms, users };
}
async getProjectRoles(): Promise<IRole[]> {
return this.roleStore.getProjectRoles();
}
async getRolesForProject(projectId: string): Promise<IRole[]> {
return this.roleStore.getRolesForProject(projectId);
}
async getRolesForUser(userId: number): Promise<IRole[]> {
return this.store.getRolesForUserId(userId);
}
async wipeUserPermissions(userId: number): Promise<Array<void>> {
return Promise.all([
this.store.unlinkUserRoles(userId),
this.store.unlinkUserGroups(userId),
this.store.clearUserPersonalAccessTokens(userId),
this.store.clearPublicSignupUserTokens(userId),
]);
}
async getUsersForRole(roleId: number): Promise<IUser[]> {
const userIdList = await this.store.getUserIdsForRole(roleId);
if (userIdList.length > 0) {
return this.accountStore.getAllWithId(userIdList);
}
return [];
}
async getGroupsForRole(roleId: number): Promise<IGroup[]> {
const groupdIdList = await this.store.getGroupIdsForRole(roleId);
if (groupdIdList.length > 0) {
return this.groupService.getAllWithId(groupdIdList);
}
return [];
}
async getProjectUsersForRole(
roleId: number,
projectId?: string,
): Promise<IUserWithRole[]> {
const userRoleList = await this.store.getProjectUsersForRole(
roleId,
projectId,
);
if (userRoleList.length > 0) {
const userIdList = userRoleList.map((u) => u.userId);
const users = await this.accountStore.getAllWithId(userIdList);
return users.map((user) => {
const role = userRoleList.find((r) => r.userId === user.id)!;
return {
...user,
addedAt: role.addedAt!,
roleId,
};
});
}
return [];
}
async getProjectUsers(projectId: string): Promise<IUserWithProjectRoles[]> {
const projectUsers = await this.store.getProjectUsers(projectId);
if (projectUsers.length > 0) {
const users = await this.accountStore.getAllWithId(
projectUsers.map((u) => u.id),
);
return users.flatMap((user) => {
return projectUsers
.filter((u) => u.id === user.id)
.map((groupUser) => ({
...user,
...groupUser,
}));
});
}
return [];
}
async getProjectRoleAccess(projectId: string): Promise<AccessWithRoles> {
const roles = await this.roleStore.getProjectRoles();
const users = await this.getProjectUsers(projectId);
const groups = await this.groupService.getProjectGroups(projectId);
return {
roles,
groups,
users,
};
}
async getProjectRoleUsage(roleId: number): Promise<IProjectRoleUsage[]> {
return this.store.getProjectUserAndGroupCountsForRole(roleId);
}
async createDefaultProjectRoles(
owner: IUser,
projectId: string,
): Promise<void> {
if (!projectId) {
throw new Error('ProjectId cannot be empty');
}
const ownerRole = await this.roleStore.getRoleByName(RoleName.OWNER);
// TODO: remove this when all users is guaranteed to have a unique id.
if (owner.id) {
this.logger.info(
`Making ${owner.id} admin of ${projectId} via roleId=${ownerRole.id}`,
);
await this.store.addUserToRole(owner.id, ownerRole.id, projectId);
}
}
async removeDefaultProjectRoles(
owner: IUser,
projectId: string,
): Promise<void> {
this.logger.info(`Removing project roles for ${projectId}`);
return this.roleStore.removeRolesForProject(projectId);
}
async getRootRoleForAllUsers(): Promise<IUserRole[]> {
return this.roleStore.getRootRoleForAllUsers();
}
async getRootRoles(): Promise<IRole[]> {
return this.roleStore.getRootRoles();
}
public async resolveRootRole(
rootRole: number | RoleName,
): Promise<IRole | undefined> {
const rootRoles = await this.getRootRoles();
let role: IRole | undefined;
if (typeof rootRole === 'number') {
role = rootRoles.find((r) => r.id === rootRole);
} else {
role = rootRoles.find((r) => r.name === rootRole);
}
return role;
}
/*
This method is intended to give a predicable way to fetch
pre-defined roles defined in the RoleName enum. This method
should not be used to fetch custom root or project roles.
*/
async getPredefinedRole(roleName: RoleName): Promise<IRole> {
const roles = await this.roleStore.getRoles();
const role = roles.find((r) => r.name === roleName);
if (!role) {
throw new BadDataError(
`Could not find pre-defined role with name ${RoleName}`,
);
}
return role;
}
async getAllRoles(): Promise<ICustomRole[]> {
return this.roleStore.getAll();
}
async createRole(role: IRoleCreation): Promise<ICustomRole> {
// CUSTOM_PROJECT_ROLE_TYPE is assumed by default for backward compatibility
const roleType =
role.type === CUSTOM_ROOT_ROLE_TYPE
? CUSTOM_ROOT_ROLE_TYPE
: CUSTOM_PROJECT_ROLE_TYPE;
if (
roleType === CUSTOM_ROOT_ROLE_TYPE &&
this.flagResolver.isEnabled('customRootRolesKillSwitch')
) {
throw new InvalidOperationError(
'Custom root roles are not enabled.',
);
}
const baseRole = {
...(await this.validateRole(role)),
roleType,
};
const rolePermissions = role.permissions;
const newRole = await this.roleStore.create(baseRole);
if (rolePermissions) {
if (roleType === CUSTOM_ROOT_ROLE_TYPE) {
// this branch uses named permissions
await this.store.addPermissionsToRole(
newRole.id,
rolePermissions,
);
} else {
// this branch uses id permissions
await this.store.addEnvironmentPermissionsToRole(
newRole.id,
rolePermissions,
);
}
}
const addedPermissions = await this.store.getPermissionsForRole(
newRole.id,
);
this.eventService.storeEvent({
type: ROLE_CREATED,
createdBy: role.createdBy || 'unknown',
data: {
...newRole,
permissions: this.sanitizePermissions(addedPermissions),
},
});
return newRole;
}
async updateRole(role: IRoleUpdate): Promise<ICustomRole> {
const roleType =
role.type === CUSTOM_ROOT_ROLE_TYPE
? CUSTOM_ROOT_ROLE_TYPE
: CUSTOM_PROJECT_ROLE_TYPE;
if (
roleType === CUSTOM_ROOT_ROLE_TYPE &&
this.flagResolver.isEnabled('customRootRolesKillSwitch')
) {
throw new InvalidOperationError(
'Custom root roles are not enabled.',
);
}
await this.validateRole(role, role.id);
const existingRole = await this.roleStore.get(role.id);
const baseRole = {
id: role.id,
name: role.name,
description: role.description,
roleType,
};
const rolePermissions = role.permissions;
const updatedRole = await this.roleStore.update(baseRole);
const existingPermissions = await this.store.getPermissionsForRole(
role.id,
);
if (rolePermissions) {
await this.store.wipePermissionsFromRole(updatedRole.id);
if (roleType === CUSTOM_ROOT_ROLE_TYPE) {
await this.store.addPermissionsToRole(
updatedRole.id,
rolePermissions,
);
} else {
await this.store.addEnvironmentPermissionsToRole(
updatedRole.id,
rolePermissions,
);
}
}
const updatedPermissions = await this.store.getPermissionsForRole(
role.id,
);
this.eventService.storeEvent({
type: ROLE_UPDATED,
createdBy: role.createdBy || 'unknown',
data: {
...updatedRole,
permissions: this.sanitizePermissions(updatedPermissions),
},
preData: {
...existingRole,
permissions: this.sanitizePermissions(existingPermissions),
},
});
return updatedRole;
}
sanitizePermissions(
permissions: IPermission[],
): { name: string; environment?: string }[] {
return permissions.map(({ name, environment }) => {
const sanitizedEnvironment =
environment && environment !== null && environment !== ''
? environment
: undefined;
return { name, environment: sanitizedEnvironment };
});
}
async deleteRole(id: number, deletedBy = 'unknown'): Promise<void> {
await this.validateRoleIsNotBuiltIn(id);
const roleUsers = await this.getUsersForRole(id);
const roleGroups = await this.getGroupsForRole(id);
if (roleUsers.length > 0 || roleGroups.length > 0) {
throw new RoleInUseError(
`Role is in use by users(${roleUsers.length}) or groups(${roleGroups.length}). You cannot delete a role that is in use without first removing the role from the users and groups.`,
);
}
const existingRole = await this.roleStore.get(id);
const existingPermissions = await this.store.getPermissionsForRole(id);
await this.roleStore.delete(id);
this.eventService.storeEvent({
type: ROLE_DELETED,
createdBy: deletedBy,
preData: {
...existingRole,
permissions: this.sanitizePermissions(existingPermissions),
},
});
return;
}
async validateRoleIsUnique(
roleName: string,
existingId?: number,
): Promise<void> {
const exists = await this.roleStore.nameInUse(roleName, existingId);
if (exists) {
throw new NameExistsError(
`There already exists a role with the name ${roleName}`,
);
}
return Promise.resolve();
}
async validateRoleIsNotBuiltIn(roleId: number): Promise<void> {
const role = await this.store.get(roleId);
if (
role.type !== CUSTOM_PROJECT_ROLE_TYPE &&
role.type !== CUSTOM_ROOT_ROLE_TYPE
) {
throw new InvalidOperationError(
'You cannot change built in roles.',
);
}
}
async validateRole(
role: IRoleValidation,
existingId?: number,
): Promise<IRoleCreation> {
const cleanedRole = await roleSchema.validateAsync(role);
if (existingId) {
await this.validateRoleIsNotBuiltIn(existingId);
}
await this.validateRoleIsUnique(role.name, existingId);
return cleanedRole;
}
async getUserAccessOverview(): Promise<IUserAccessOverview[]> {
return this.store.getUserAccessOverview();
}
}