aws-sdk#SecurityHub TypeScript Examples

The following examples show how to use aws-sdk#SecurityHub. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: handlers.ts    From aws-resource-providers with MIT License 6 votes vote down vote up
@handlerEvent(Action.Create)
    @commonAws({ service: SecurityHub, debug: true })
    public async create(action: Action, args: HandlerArgs<ResourceModel>, service: SecurityHub, model: ResourceModel): Promise<ResourceModel> {
        const { logicalResourceIdentifier } = args.request;

        if (model.arn) {
            throw new exceptions.InvalidRequest('Read only property [Arn] cannot be provided by the user.');
        }

        const request: SecurityHub.CreateActionTargetRequest = {
            Id: model.id,
            Name: model.name,
            Description: model.description,
        };

        try {
            args.logger.log({ action, message: 'before createActionTarget', request });
            const response = await service.createActionTarget(request).promise();
            args.logger.log({ action, message: 'after invoke createActionTarget', response });

            model.arn = response.ActionTargetArn;
            args.logger.log({ action, message: 'done', model });
            return Promise.resolve(model);
        } catch (err) {
            console.log(err);
            if (err?.code === 'ResourceConflictException') {
                throw new exceptions.AlreadyExists(this.typeName, logicalResourceIdentifier);
            } else {
                // Raise the original exception
                throw err;
            }
        }
    }
Example #2
Source File: handlers.ts    From aws-resource-providers with MIT License 6 votes vote down vote up
@handlerEvent(Action.Update)
    @commonAws({ service: SecurityHub, debug: true })
    public async update(action: Action, args: HandlerArgs<ResourceModel>, service: SecurityHub, model: ResourceModel): Promise<ResourceModel> {
        const { logicalResourceIdentifier, previousResourceState } = args.request;
        const { arn, id } = previousResourceState;
        if (!model.arn && !model.id) {
            throw new exceptions.NotFound(this.typeName, logicalResourceIdentifier);
        } else if (model.arn !== arn) {
            args.logger.log(this.typeName, `[NEW ${model.arn}] [${logicalResourceIdentifier}]`, `does not match identifier from saved resource [OLD ${arn}].`);
            throw new exceptions.NotUpdatable('Read only property [Arn] cannot be updated.');
        } else if (model.id !== id) {
            args.logger.log(this.typeName, `[NEW ${model.id}] [${logicalResourceIdentifier}]`, `does not match identifier from saved resource [OLD ${id}].`);
            throw new exceptions.NotUpdatable('Read only property [Id] cannot be updated.');
        }
        try {
            const request: SecurityHub.UpdateActionTargetRequest = {
                ActionTargetArn: model.arn,
                Name: model.name,
                Description: model.description,
            };
            args.logger.log({ action, message: 'before invoke updateActionTarget', request });
            const response = await service.updateActionTarget(request).promise();
            args.logger.log({ action, message: 'after invoke updateActionTarget', response });

            args.logger.log({ action, message: 'done', model });
            return Promise.resolve(model);
        } catch (err) {
            if (err?.code === 'ResourceNotFoundException') {
                throw new exceptions.NotFound(this.typeName, arn || logicalResourceIdentifier);
            } else {
                // Raise the original exception
                throw err;
            }
        }
    }
Example #3
Source File: handlers.ts    From aws-resource-providers with MIT License 6 votes vote down vote up
@handlerEvent(Action.Delete)
    @commonAws({ service: SecurityHub, debug: true })
    public async delete(action: Action, args: HandlerArgs<ResourceModel>, service: SecurityHub, model: ResourceModel): Promise<null> {
        const { logicalResourceIdentifier } = args.request;
        if (!model.arn) {
            throw new exceptions.NotFound(this.typeName, logicalResourceIdentifier);
        }

        const request: SecurityHub.DeleteActionTargetRequest = {
            ActionTargetArn: model.arn,
        };

        try {
            args.logger.log({ action, message: 'before invoke deleteActionTarget', request });
            const response = await service.deleteActionTarget(request).promise();
            args.logger.log({ action, message: 'after invoke deleteActionTarget', response });

            args.logger.log({ action, message: 'done' });
            return Promise.resolve(null);
        } catch (err) {
            if (err?.code === 'ResourceNotFoundException') {
                throw new exceptions.NotFound(this.typeName, model.arn || logicalResourceIdentifier);
            } else {
                // Raise the original exception
                throw err;
            }
        }
    }
Example #4
Source File: handlers.ts    From aws-resource-providers with MIT License 6 votes vote down vote up
@handlerEvent(Action.Read)
    @commonAws({ service: SecurityHub, debug: true })
    public async read(action: Action, args: HandlerArgs<ResourceModel>, service: SecurityHub, model: ResourceModel): Promise<ResourceModel> {
        const { logicalResourceIdentifier } = args.request;
        if (!model.arn) {
            throw new exceptions.NotFound(this.typeName, logicalResourceIdentifier);
        }
        const request: SecurityHub.DescribeActionTargetsRequest = {
            ActionTargetArns: [model.arn],
            MaxResults: 1,
        };
        try {
            args.logger.log({ action, message: 'before invoke describeActionTargets', request });
            const response = await service.describeActionTargets(request).promise();
            args.logger.log({ action, message: 'after invoke describeActionTargets', response });

            const targets = response.ActionTargets;

            if (!targets.length) {
                throw new exceptions.NotFound(this.typeName, model.arn || logicalResourceIdentifier);
            }

            model.name = targets[0].Name;
            model.description = targets[0].Description;

            args.logger.log({ action, message: 'done', model });
            return Promise.resolve(model);
        } catch (err) {
            if (err?.code === 'ResourceNotFoundException') {
                throw new exceptions.NotFound(this.typeName, model.arn || logicalResourceIdentifier);
            } else {
                // Raise the original exception
                throw err;
            }
        }
    }
Example #5
Source File: handlers.test.ts    From aws-resource-providers with MIT License 4 votes vote down vote up
describe('when calling handler', () => {
    let testEntrypointPayload: any;
    let spySession: jest.SpyInstance;
    let spySessionClient: jest.SpyInstance;
    let securityhub: AwsServiceMockBuilder<SecurityHub>;
    let fixtureMap: Map<Action, Record<string, any>>;

    beforeAll(() => {
        fixtureMap = new Map<Action, Record<string, any>>();
        fixtureMap.set(Action.Create, createFixture);
        fixtureMap.set(Action.Read, readFixture);
        fixtureMap.set(Action.Update, updateFixture);
        fixtureMap.set(Action.Delete, deleteFixture);
    });

    beforeEach(async () => {
        securityhub = on(SecurityHub, { snapshot: false });
        securityhub.mock('describeActionTargets').resolve({
            ActionTargets: [
                {
                    ActionTargetArn: IDENTIFIER,
                    Name: 'test',
                    Description: 'test',
                },
            ],
        });
        securityhub.mock('createActionTarget').resolve({
            ActionTargetArn: IDENTIFIER,
        });
        securityhub.mock('updateActionTarget').resolve({});
        securityhub.mock('deleteActionTarget').resolve({});
        spySession = jest.spyOn(SessionProxy, 'getSession');
        spySessionClient = jest.spyOn<any, any>(SessionProxy.prototype, 'client');
        spySessionClient.mockReturnValue(securityhub.instance);
        testEntrypointPayload = {
            credentials: { accessKeyId: '', secretAccessKey: '', sessionToken: '' },
            region: 'us-east-1',
            action: 'CREATE',
        };
    });

    afterEach(() => {
        jest.clearAllMocks();
        jest.restoreAllMocks();
    });

    test('create operation successful - security hub action target', async () => {
        const request = fixtureMap.get(Action.Create);
        const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Create, request }, null);
        expect(progress).toMatchObject({ status: OperationStatus.Success, message: '', callbackDelaySeconds: 0 });
        expect(progress.resourceModel.serialize()).toMatchObject({
            ...request.desiredResourceState,
            Arn: IDENTIFIER,
        });
    });

    test('create operation fail already exists - security hub action target', async () => {
        const mockCreate = securityhub.mock('createActionTarget').reject({
            ...new Error(),
            code: 'ResourceConflictException',
        });
        const request = fixtureMap.get(Action.Create);
        const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Create, request }, null);
        expect(progress).toMatchObject({ status: OperationStatus.Failed, errorCode: exceptions.AlreadyExists.name });
        expect(mockCreate.mock).toHaveBeenCalledTimes(1);
    });

    test('update operation successful - security hub action target', async () => {
        const request = fixtureMap.get(Action.Update);
        const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Update, request }, null);
        expect(progress).toMatchObject({ status: OperationStatus.Success, message: '', callbackDelaySeconds: 0 });
        expect(progress.resourceModel.serialize()).toMatchObject(request.desiredResourceState);
    });

    test('update operation fail not found - security hub action target', async () => {
        const mockGet = securityhub.mock('updateActionTarget').reject({
            ...new Error(),
            code: 'ResourceNotFoundException',
        });
        const request = fixtureMap.get(Action.Update);
        const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Update, request }, null);
        expect(progress).toMatchObject({ status: OperationStatus.Failed, errorCode: exceptions.NotFound.name });
        expect(mockGet.mock).toHaveBeenCalledTimes(1);
    });

    test('delete operation successful - security hub action target', async () => {
        const request = fixtureMap.get(Action.Delete);
        const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Delete, request }, null);
        expect(progress).toMatchObject({ status: OperationStatus.Success, message: '', callbackDelaySeconds: 0 });
        expect(progress.resourceModel).toBeNull();
    });

    test('delete operation fail not found - security hub action target', async () => {
        const mockGet = securityhub.mock('deleteActionTarget').reject({
            ...new Error(),
            code: 'ResourceNotFoundException',
        });
        const request = fixtureMap.get(Action.Delete);
        const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Delete, request }, null);
        expect(progress).toMatchObject({ status: OperationStatus.Failed, errorCode: exceptions.NotFound.name });
        expect(mockGet.mock).toHaveBeenCalledTimes(1);
    });

    test('read operation successful - security hub action target', async () => {
        const request = fixtureMap.get(Action.Read);
        const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Read, request }, null);
        expect(progress).toMatchObject({ status: OperationStatus.Success, message: '', callbackDelaySeconds: 0 });
        expect(progress.resourceModel.serialize()).toMatchObject(request.desiredResourceState);
    });

    test('read operation  fail not found - security hub action target', async () => {
        const mockGet = securityhub.mock('describeActionTargets').reject({
            ...new Error(),
            code: 'ResourceNotFoundException',
        });
        const request = fixtureMap.get(Action.Read);
        const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Read, request }, null);
        expect(progress).toMatchObject({ status: OperationStatus.Failed, errorCode: exceptions.NotFound.name });
        expect(mockGet.mock).toHaveBeenCalledTimes(1);
    });

    test('all operations fail without session - security hub action target', async () => {
        expect.assertions(fixtureMap.size);
        spySession.mockReturnValue(null);
        for (const [action, request] of fixtureMap) {
            const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action, request }, null);
            expect(progress.errorCode).toBe(exceptions.InvalidCredentials.name);
        }
    });
});