All files / src/validators CreateTargetInputValidator.ts

100% Statements 56/56
100% Branches 32/32
100% Functions 6/6
100% Lines 53/53

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                              5x 5x   5x 5x         5x 21x   21x 21x       21x   21x 21x     16x 3x     16x 1x     16x 10x 10x 2x       16x 3x 3x 1x       16x 7x     9x       9x 2x 2x   7x 7x 6x 6x 1x 1x       1x 1x         3x 1x   2x 2x       10x 10x 10x 10x 9x 8x 8x   1x 1x     1x 1x   10x        
/* 
  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 { ARN, parse } from "@aws-sdk/util-arn-parser";
import { Logger, LoggerFactory, TargetDefinitionResolver } from "shared_types";
import { FlowTargetInput } from "src/types/FlowTarget";
import { inject, injectable } from "tsyringe";
import { InputValidator, REGEX_DESCRIPTION, REGEX_ID } from './InputValidator';
type TagValuePair = { key: string, value: string };
type ValidationResult = { isValid: boolean, message: string };
 
@injectable()
export class CreateTargetInputValidator extends InputValidator<FlowTargetInput> {
    DEFAULT_SUPPORT_TYPES = ['autoscaling', 'ec2'];
 
    SUPPORTED_RESOURCE_REGX = /(security-group|instance|vpc|subnet)\/(.+)/;
    PORT_RANGE_REGX = /\[(\d+):(\d.+)\]/;
    logger: Logger;
    constructor(
        @inject('LoggerFactory') loggerFactory: LoggerFactory,
        @inject('TargetDefinitionResolver') private targetDefinitionResolver: TargetDefinitionResolver
    ) {
        super();
        this.logger = loggerFactory.getLogger('CreateTargetInputValidator');
    }
    protected async validate(input: FlowTargetInput): Promise<void> {
        if(!input.description || !this.isValidDescriptionName(input.description)) {
            this.errors.push(`Invalid target : description violated restriction, expecting ${REGEX_DESCRIPTION}`);
        }
 
        if (input.id && !this.isValidId(input.id)) {
            this.errors.push(`id should be matching ${REGEX_ID}`);
        }
 
        if (input.type === 'Arn') {
            const arnValidationResult = this.validateArn(input.value);
            if (!arnValidationResult.isValid) {
                this.errors.push(`Invalid target : ${arnValidationResult.message}.`);
            }
        }
 
        if (input.type === 'Tagged') {
            const valid = this.isValidTagValue(input.value);
            if (!valid) {
                this.errors.push(`Invalid target : ${input.value} is not a valid tag value.`);
            }
        }
 
        if(this.errors.length > 0) {
            return;
        }
 
        await this.validateObjectReference(input);
    }
 
    private async validateObjectReference(input: FlowTargetInput) {
        if (input.type === 'Tagged') {
            this.logger.info('Input type is Tagged skip resolution on creation/updating');
            return;
        }
        try {
            const result = await this.targetDefinitionResolver.resolveTarget(input);
            this.logger.info('resolved outcome', result);
            if (result.addresses.length === 0) {
                this.logger.error('can not resolve target to IP addresses');
                this.errors.push('can not resolve target to IP addresses');
            }
        }
        catch (e) {
            this.logger.error('can not resolve target', input, e);
            this.errors.push('can not resolve target', e);
        }
    }
 
    isValidTagValue(value: unknown): boolean {
        if (!Array.isArray(value)) {
            return false;
        }
        const listOfTags: TagValuePair[] = (value as TagValuePair[]);
        return listOfTags.some(t => !this.isBlank(t.key) && !this.isBlank(t.value));
    }
 
    private validateArn(inputArn: string): ValidationResult {
        let isValid = false;
        let message = '';
        try {
            const arn: ARN = parse(inputArn);
            if (this.DEFAULT_SUPPORT_TYPES.includes(arn.service)) {
                const match = arn.resource.match(this.SUPPORTED_RESOURCE_REGX);
                isValid = arn.service == 'autoscaling' || (arn.service === 'ec2' && match != null && match[1] != null)
            } else {
                isValid = false;
                message = `${arn.service} is not a supported arn type`;
            }
        } catch (e) {
            message = `${inputArn} is not a valid arn`
            isValid = false;
        }
        return { isValid, message };
    }
 
}