All files App.ts

100% Statements 30/30
95.45% Branches 21/22
100% Functions 3/3
100% Lines 30/30

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                                        1x 1x 1x                                                             1x   1x           7x   7x 7x 7x 7x 7x 2x   5x   5x 2x         2x 2x     7x   7x                           5x 5x 5x 5x                     5x 5x   5x             5x   5x 3x     3x    
/* 
  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 {
    CloudFormationCustomResourceEvent,
    CloudFormationCustomResourceFailedResponse,
    CloudFormationCustomResourceSuccessResponse,
} from 'aws-lambda';
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import * as moment from 'moment';
import { v4 as uuidv4 } from 'uuid';
 
export interface MetricsPayloadData {
    Region: string;
    Type: string;
}
 
export interface MetricPayload {
    Solution: string;
    Version: string;
    UUID: string;
    TimeStamp: string;
    Data: MetricsPayloadData;
}
 
export interface CustomerResourceProperties {
    sendAnonymousMetric: 'Yes' | 'No';
    UUID: string;
    enabledOpa: boolean;
    importedVpc: boolean;
    crossAccount: boolean;
    privateEndpoint: boolean;
}
 
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type CloudFormationCustomResourceEventResource = Record<
    string | 'ServiceToken',
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    any | string
>;
 
const SOLUTION_BUILDERS_ENDPOINT = 'https://metrics.awssolutionsbuilder.com/generic';
 
export async function lambdaHandler(
    event: CloudFormationCustomResourceEvent
): Promise<
    | CloudFormationCustomResourceSuccessResponse
    | CloudFormationCustomResourceFailedResponse
> {
    console.log(`${JSON.stringify(event)}`);
 
    let cfnResponseStatus: 'SUCCESS' | 'FAILED' = 'SUCCESS';
    let reason = '';
    const { RequestType, ResourceProperties } = event;
    console.log('Resource properties', ResourceProperties);
    if (ResourceProperties.sendAnonymousMetric != 'Yes') {
        console.log('Sending anonymous data has been disabled. Exiting.');
    } else {
        console.log('Sending anonymous data.');
 
        await sendAnonymousMetric(ResourceProperties, RequestType).catch((err) => {
            console.error(
                `Error occurred at ${event.RequestType}::operational-metrics-collector`,
                err
            );
 
            cfnResponseStatus = 'FAILED';
            reason = err.message ?? 'Custom resource error occurred.';
        });
    }
    console.log('response status', cfnResponseStatus);
 
    return {
        RequestId: event.RequestId,
        LogicalResourceId: event.LogicalResourceId,
        PhysicalResourceId: 'operational-metrics-collector-cr',
        StackId: event.StackId,
        Status: cfnResponseStatus,
        Reason: reason,
    };
}
 
async function sendAnonymousMetric(
    requestProperties: CloudFormationCustomResourceEventResource,
    requestType: string
): Promise<AxiosResponse> {
    const { SOLUTION_ID, AWS_REGION, SOLUTION_VERSION } = process.env;
    const uuid = requestProperties.UUID ?? uuidv4();
    console.log('request uuid', uuid);
    const payload: MetricPayload = {
        Solution: SOLUTION_ID ?? '',
        Version: SOLUTION_VERSION ?? '1.0.0',
        UUID: uuid,
        TimeStamp: moment.utc().format('YYYY-MM-DD HH:mm:ss.S'),
        Data: {
            Region: AWS_REGION ?? '',
            Type: requestType,
            ...requestProperties,
        },
    };
    console.log('payload', payload);
    const payloadStr = JSON.stringify(payload);
 
    const config: AxiosRequestConfig = {
        headers: {
            'content-type': 'application/json',
            'content-length': payloadStr.length,
        },
    };
 
    console.info('Sending anonymous metric', payloadStr);
 
    const response = await axios.post(SOLUTION_BUILDERS_ENDPOINT, payloadStr, config);
    console.info(
        `Anonymous metric response: ${response.statusText} (${response.status})`
    );
    return response;
}