All files / src/handlers/objects DeleteObjectHandler.ts

100% Statements 51/51
88.46% Branches 23/26
100% Functions 4/4
100% Lines 48/48

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                                                  2x 2x 2x 2x 2x 2x 2x                                                 2x             9x   9x   9x 9x   9x               8x 8x 1x   7x 7x 1x 1x               6x 6x 1x 1x       5x 5x 5x 5x 5x                     4x 4x 1x         1x 1x         3x 3x 3x 3x 1x       1x 1x       2x 1x   1x   1x 1x 1x                       2x                            
/* 
  Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
  
  Licensed under the Apache License, Version 2.0 (the "License").
  You may not use this file except in compliance with the License.
  You may obtain a copy of the License at
  
      http://www.apache.org/licenses/LICENSE-2.0
  
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
 
import { APIGatewayProxyEvent, Context } from 'aws-lambda';
import {
    AuditChangeResult,
    FlowAudit,
    FlowObject,
    Logger,
    LoggerFactory,
} from 'shared_types';
import { AsyncRequestHandler } from 'src/common/AsyncRequestHandler';
import RuleConfigError from 'src/common/RuleConfigError';
import { ServerlessResponse } from 'src/common/ServerlessResponse';
import { AuditsDataSourceService } from 'src/service/AuditsDataSourceService';
import { ObjectsDataSourceService } from 'src/service/ObjectsDataSourceService';
import { OpaPolicyService } from 'src/service/OpaPolicyService';
import { RulesDataSourceService } from 'src/service/RulesDataSourceService';
import { inject, injectable } from 'tsyringe';
 
/**
 * @api {delete} /objects/{id} Delete an object
 * @apiGroup Objects
 * @apiDescription Delete an object referencing a cloud resource or fixed resource
 * 
 *  @apiExample {curl} CURL Example:
 curl --location --request DELETE 'https://<rest_api_id>.execute-api.ap-southeast-2.amazonaws.com/prod/objects/object_id' 
* @apiParam {UUID} id The object's id.
* @apiSuccess (Success 200) object updated
* @apiError (Error 404) object not found
* @apiError (Error 400) Invalid object value
* @apiError (Error 502) Time out
* @apiError (Error 503) Internal error
* 
* @apiSuccessExample Success-Response: 
*      HTTP/1.1 200 OK
*  {
    "id": "object_id"
    }
* 
* @apiSampleRequest off
*/
@injectable()
export class DeleteObjectHandler
    implements AsyncRequestHandler<APIGatewayProxyEvent, ServerlessResponse> {
    private readonly logger: Logger;
 
    constructor(
        @inject('LoggerFactory') loggerFactory: LoggerFactory,
        @inject('ObjectsDataSourceService')
        private objectsDataSourceService: ObjectsDataSourceService,
        @inject('RulesDataSourceService')
        private ruleDataSourceService: RulesDataSourceService,
        @inject('AuditsDataSourceService')
        private auditsDataSourceService: AuditsDataSourceService,
        @inject('OpaPolicyService') private opaPolicyService: OpaPolicyService
    ) {
        this.logger = loggerFactory.getLogger('DeleteObjectHandler');
    }
 
    async handle(
        event: APIGatewayProxyEvent,
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        _context: Context
    ): Promise<ServerlessResponse> {
        this.logger.debug('Processing delete rule object request');
        if (!event.pathParameters) {
            return ServerlessResponse.ofError(new RuleConfigError(undefined, 400, false));
        }
        const id = event.pathParameters['id'];
        if (!id) {
            this.logger.info('Rule object id path parameter cannot be null or empty.');
            return ServerlessResponse.ofError(
                new RuleConfigError(
                    'Rule object id path parameter cannot be null or empty.',
                    400,
                    false
                )
            );
        }
        const originalTarget = await this.objectsDataSourceService.getObjectBy(id);
        if (!originalTarget) {
            this.logger.info(`Target ${id} does not exist`);
            return ServerlessResponse.ofError(
                new RuleConfigError(`Target ${id} does not exist`, 404, false)
            );
        }
        const requestorIdentity = event.requestContext.identity?.userArn ?? 'Unknown';
        const accountId = event.requestContext.accountId ?? '100000';
        this.logger.info('requesting decision from opa');
        try {
            const response = await this.opaPolicyService.requestDecision(
                {
                    requester: {
                        arn: requestorIdentity,
                        accountId: accountId,
                    },
                },
                { object: originalTarget },
                'DELETE'
            );
 
            this.logger.info(' opa decision response', response);
            if (response.status === 'NON_COMPLIANT') {
                return ServerlessResponse.ofObject(400, {
                    message: response.reasonPhrases,
                });
            }
        } catch (e) {
            this.logger.error('opa error', e);
            return ServerlessResponse.ofObject(500, {
                message: `Unable to determine user accessibility, ${e}`,
            });
        }
 
        try {
            this.logger.info(`deleting object ${id}`);
            const rules = await this.ruleDataSourceService.getRuleByReferences(id);
            if (rules.length > 0) {
                this.logger.error(
                    'Error while deleting rule target, which has existing reference',
                    originalTarget
                );
                const rulesIds = rules.map((r) => r.id);
                return ServerlessResponse.ofObject(400, {
                    message: `Object ${id} is referenced by rules ${rulesIds}`,
                });
            }
            await this.objectsDataSourceService.deleteObject(id);
            await this.auditEntry(requestorIdentity, 'SUCCESS', originalTarget);
 
            return ServerlessResponse.ofObject(200, { id: id });
        } catch (e) {
            this.logger.error('Error while deleting rule target', e, originalTarget);
            this.auditEntry(requestorIdentity, 'REJECTED', originalTarget, [e.message]);
            return ServerlessResponse.ofObject(500, {
                message: `Error while deleting rule object ${id}`,
            });
        }
    }
 
    async auditEntry(
        requestorIdentity: string,
        status: AuditChangeResult,
        object: FlowObject,
        reasons?: string[]
    ): Promise<FlowAudit> {
        return this.auditsDataSourceService.createAuditEntry({
            requestedBy: requestorIdentity,
            requestedTimestamp: new Date().toISOString(),
            requestedChange: {
                type: 'DELETE', //CREATE/UPDATE/DELETE
                changeContent: {
                    requestedObject: object,
                },
                changeResult: status, // SUCCESS, REJECTED
                reasonPhrase: reasons ?? [],
            },
        });
    }
}