All files / src/lib/services project-service.ts

91.74% Statements 111/121
68.75% Branches 11/16
92.31% Functions 24/26
91.38% Lines 106/116

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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    64x 64x 64x 64x 64x 64x                   64x                               64x 64x 64x 64x   64x   64x   64x             64x                                                                                               151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x       3x       12x             41x 41x   40x   40x         40x   41x             40x   40x             40x       1x 1x   1x   1x                         4x     4x     4x 5x                     8x   8x 1x   7x   6x       6x           6x 2x       4x 4x 2x   2x         2x         2x       4x 1x         3x         3x 1x         2x   2x           2x       3x 2x 1x       43x 43x 2x           12x       12x                         16x     16x   40x 16x           19x 16x 1x     15x   15x                                         3x   3x   2x   2x   2x                                   5x 8x 5x         5x             6x 2x       2x 2x                     3x 5x 3x 5x     3x         3x   2x         2x   2x                                                                                                
import User from '../types/user';
import { AccessService } from './access-service';
import NameExistsError from '../error/name-exists-error';
import InvalidOperationError from '../error/invalid-operation-error';
import { nameType } from '../routes/util';
import { projectSchema } from './project-schema';
import NotFoundError from '../error/notfound-error';
import {
    PROJECT_CREATED,
    PROJECT_DELETED,
    PROJECT_UPDATED,
    ProjectUserAddedEvent,
    ProjectUserRemovedEvent,
    ProjectUserUpdateRoleEvent,
} from '../types/events';
import { IUnleashStores } from '../types';
import { IUnleashConfig } from '../types/option';
import {
    FeatureToggle,
    IProject,
    IProjectOverview,
    IProjectWithCount,
    IUserWithRole,
    RoleName,
} from '../types/model';
import { IEnvironmentStore } from '../types/stores/environment-store';
import { IFeatureTypeStore } from '../types/stores/feature-type-store';
import { IFeatureToggleStore } from '../types/stores/feature-toggle-store';
import { IFeatureEnvironmentStore } from '../types/stores/feature-environment-store';
import { IProjectQuery, IProjectStore } from '../types/stores/project-store';
import { IRoleDescriptor } from '../types/stores/access-store';
import { IEventStore } from '../types/stores/event-store';
import FeatureToggleService from './feature-toggle-service';
import { MOVE_FEATURE_TOGGLE } from '../types/permissions';
import NoAccessError from '../error/no-access-error';
import IncompatibleProjectError from '../error/incompatible-project-error';
import { DEFAULT_PROJECT } from '../types/project';
import { IFeatureTagStore } from 'lib/types/stores/feature-tag-store';
import ProjectWithoutOwnerError from '../error/project-without-owner-error';
import { IUserStore } from 'lib/types/stores/user-store';
import { arraysHaveSameItems } from '../util/arraysHaveSameItems';
 
const getCreatedBy = (user: User) => user.email || user.username;
 
export interface UsersWithRoles {
    users: IUserWithRole[];
    roles: IRoleDescriptor[];
}
 
export default class ProjectService {
    private store: IProjectStore;
 
    private accessService: AccessService;
 
    private eventStore: IEventStore;
 
    private featureToggleStore: IFeatureToggleStore;
 
    private featureTypeStore: IFeatureTypeStore;
 
    private featureEnvironmentStore: IFeatureEnvironmentStore;
 
    private environmentStore: IEnvironmentStore;
 
    private logger: any;
 
    private featureToggleService: FeatureToggleService;
 
    private tagStore: IFeatureTagStore;
 
    private userStore: IUserStore;
 
    constructor(
        {
            projectStore,
            eventStore,
            featureToggleStore,
            featureTypeStore,
            environmentStore,
            featureEnvironmentStore,
            featureTagStore,
            userStore,
        }: Pick<
            IUnleashStores,
            | 'projectStore'
            | 'eventStore'
            | 'featureToggleStore'
            | 'featureTypeStore'
            | 'environmentStore'
            | 'featureEnvironmentStore'
            | 'featureTagStore'
            | 'userStore'
        >,
        config: IUnleashConfig,
        accessService: AccessService,
        featureToggleService: FeatureToggleService,
    ) {
        this.store = projectStore;
        this.environmentStore = environmentStore;
        this.featureEnvironmentStore = featureEnvironmentStore;
        this.accessService = accessService;
        this.eventStore = eventStore;
        this.featureToggleStore = featureToggleStore;
        this.featureTypeStore = featureTypeStore;
        this.featureToggleService = featureToggleService;
        this.tagStore = featureTagStore;
        this.userStore = userStore;
        this.logger = config.getLogger('services/project-service.js');
    }
 
    async getProjects(query?: IProjectQuery): Promise<IProjectWithCount[]> {
        return this.store.getProjectsWithCounts(query);
    }
 
    async getProject(id: string): Promise<IProject> {
        return this.store.get(id);
    }
 
    async createProject(
        newProject: Pick<IProject, 'id'>,
        user: User,
    ): Promise<IProject> {
        const data = await projectSchema.validateAsync(newProject);
        await this.validateUniqueId(data.id);
 
        await this.store.create(data);
 
        const enabledEnvironments = await this.environmentStore.getAll({
            enabled: true,
        });
 
        // TODO: Only if enabled!
        await Promise.all(
            enabledEnvironments.map(async (e) => {
                await this.featureEnvironmentStore.connectProject(
                    e.name,
                    data.id,
                );
            }),
        );
 
        await this.accessService.createDefaultProjectRoles(user, data.id);
 
        await this.eventStore.store({
            type: PROJECT_CREATED,
            createdBy: getCreatedBy(user),
            data,
            project: newProject.id,
        });
 
        return data;
    }
 
    async updateProject(updatedProject: IProject, user: User): Promise<void> {
        const preData = await this.store.get(updatedProject.id);
        const project = await projectSchema.validateAsync(updatedProject);
 
        await this.store.update(project);
 
        await this.eventStore.store({
            type: PROJECT_UPDATED,
            project: project.id,
            createdBy: getCreatedBy(user),
            data: project,
            preData,
        });
    }
 
    async checkProjectsCompatibility(
        feature: FeatureToggle,
        newProjectId: string,
    ): Promise<boolean> {
        const featureEnvs = await this.featureEnvironmentStore.getAll({
            feature_name: feature.name,
        });
        const newEnvs = await this.store.getEnvironmentsForProject(
            newProjectId,
        );
        return arraysHaveSameItems(
            featureEnvs.map((env) => env.environment),
            newEnvs,
        );
    }
 
    async changeProject(
        newProjectId: string,
        featureName: string,
        user: User,
        currentProjectId: string,
    ): Promise<any> {
        const feature = await this.featureToggleStore.get(featureName);
 
        if (feature.project !== currentProjectId) {
            throw new NoAccessError(MOVE_FEATURE_TOGGLE);
        }
        const project = await this.getProject(newProjectId);
 
        Iif (!project) {
            throw new NotFoundError(`Project ${newProjectId} not found`);
        }
 
        const authorized = await this.accessService.hasPermission(
            user,
            MOVE_FEATURE_TOGGLE,
            newProjectId,
        );
 
        if (!authorized) {
            throw new NoAccessError(MOVE_FEATURE_TOGGLE);
        }
 
        const isCompatibleWithTargetProject =
            await this.checkProjectsCompatibility(feature, newProjectId);
        if (!isCompatibleWithTargetProject) {
            throw new IncompatibleProjectError(newProjectId);
        }
        const updatedFeature = await this.featureToggleService.changeProject(
            featureName,
            newProjectId,
            user.username,
        );
        await this.featureToggleService.updateFeatureStrategyProject(
            featureName,
            newProjectId,
        );
 
        return updatedFeature;
    }
 
    async deleteProject(id: string, user: User): Promise<void> {
        if (id === DEFAULT_PROJECT) {
            throw new InvalidOperationError(
                'You can not delete the default project!',
            );
        }
 
        const toggles = await this.featureToggleStore.getAll({
            project: id,
            archived: false,
        });
 
        if (toggles.length > 0) {
            throw new InvalidOperationError(
                'You can not delete a project with active feature toggles',
            );
        }
 
        await this.store.delete(id);
 
        await this.eventStore.store({
            type: PROJECT_DELETED,
            createdBy: getCreatedBy(user),
            project: id,
        });
 
        await this.accessService.removeDefaultProjectRoles(user, id);
    }
 
    async validateId(id: string): Promise<boolean> {
        await nameType.validateAsync(id);
        await this.validateUniqueId(id);
        return true;
    }
 
    async validateUniqueId(id: string): Promise<void> {
        const exists = await this.store.hasProject(id);
        if (exists) {
            throw new NameExistsError('A project with this id already exists.');
        }
    }
 
    // RBAC methods
    async getUsersWithAccess(projectId: string): Promise<UsersWithRoles> {
        const [roles, users] = await this.accessService.getProjectRoleUsers(
            projectId,
        );
 
        return {
            roles,
            users,
        };
    }
 
    // TODO: Remove the optional nature of createdBy - this in place to make sure enterprise is compatible
    async addUser(
        projectId: string,
        roleId: number,
        userId: number,
        createdBy?: string,
    ): Promise<void> {
        const [roles, users] = await this.accessService.getProjectRoleUsers(
            projectId,
        );
        const user = await this.userStore.get(userId);
 
        const role = roles.find((r) => r.id === roleId);
        Iif (!role) {
            throw new NotFoundError(
                `Could not find roleId=${roleId} on project=${projectId}`,
            );
        }
 
        const alreadyHasAccess = users.some((u) => u.id === userId);
        if (alreadyHasAccess) {
            throw new Error(`User already has access to project=${projectId}`);
        }
 
        await this.accessService.addUserToRole(userId, role.id, projectId);
 
        await this.eventStore.store(
            new ProjectUserAddedEvent({
                project: projectId,
                createdBy,
                data: {
                    roleId,
                    userId,
                    roleName: role.name,
                    email: user.email,
                },
            }),
        );
    }
 
    // TODO: Remove the optional nature of createdBy - this in place to make sure enterprise is compatible
    async removeUser(
        projectId: string,
        roleId: number,
        userId: number,
        createdBy?: string,
    ): Promise<void> {
        const role = await this.findProjectRole(projectId, roleId);
 
        await this.validateAtLeastOneOwner(projectId, role);
 
        await this.accessService.removeUserFromRole(userId, role.id, projectId);
 
        const user = await this.userStore.get(userId);
 
        await this.eventStore.store(
            new ProjectUserRemovedEvent({
                project: projectId,
                createdBy,
                preData: {
                    roleId,
                    userId,
                    roleName: role.name,
                    email: user.email,
                },
            }),
        );
    }
 
    async findProjectRole(
        projectId: string,
        roleId: number,
    ): Promise<IRoleDescriptor> {
        const roles = await this.accessService.getRolesForProject(projectId);
        const role = roles.find((r) => r.id === roleId);
        Iif (!role) {
            throw new NotFoundError(
                `Couldn't find roleId=${roleId} on project=${projectId}`,
            );
        }
        return role;
    }
 
    async validateAtLeastOneOwner(
        projectId: string,
        currentRole: IRoleDescriptor,
    ): Promise<void> {
        if (currentRole.name === RoleName.OWNER) {
            const users = await this.accessService.getProjectUsersForRole(
                currentRole.id,
                projectId,
            );
            if (users.length < 2) {
                throw new ProjectWithoutOwnerError();
            }
        }
    }
 
    async changeRole(
        projectId: string,
        roleId: number,
        userId: number,
        createdBy: string,
    ): Promise<void> {
        const usersWithRoles = await this.getUsersWithAccess(projectId);
        const user = usersWithRoles.users.find((u) => u.id === userId);
        const currentRole = usersWithRoles.roles.find(
            (r) => r.id === user.roleId,
        );
 
        Iif (currentRole.id === roleId) {
            // Nothing to do....
            return;
        }
 
        await this.validateAtLeastOneOwner(projectId, currentRole);
 
        await this.accessService.updateUserProjectRole(
            userId,
            roleId,
            projectId,
        );
        const role = await this.findProjectRole(projectId, roleId);
 
        await this.eventStore.store(
            new ProjectUserUpdateRoleEvent({
                project: projectId,
                createdBy,
                preData: {
                    userId,
                    roleId: currentRole.id,
                    roleName: currentRole.name,
                    email: user.email,
                },
                data: {
                    userId,
                    roleId,
                    roleName: role.name,
                    email: user.email,
                },
            }),
        );
    }
 
    async getMembers(projectId: string): Promise<number> {
        return this.store.getMembers(projectId);
    }
 
    async getProjectOverview(
        projectId: string,
        archived: boolean = false,
    ): Promise<IProjectOverview> {
        const project = await this.store.get(projectId);
        const environments = await this.store.getEnvironmentsForProject(
            projectId,
        );
        const features = await this.featureToggleService.getFeatureOverview(
            projectId,
            archived,
        );
        const members = await this.store.getMembers(projectId);
        return {
            name: project.name,
            environments,
            description: project.description,
            health: project.health,
            features,
            members,
            version: 1,
        };
    }
}