# All files / src pdk-nag.ts

62% Statements 31/50
41.07% Branches 23/56
72.22% Functions 13/18
60.41% Lines 29/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
    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

    1x

    1x

    1x

    1x
    1x

    1x
    3x

    3x
    3x
    3x
    3x

    3x

    3x

    6x

    3x

    16x

    3x

    3x

    3x

    3x

    20x

    15x
    19x

    15x

    16x

    1x

    3x
    3x

    3x

     /*! Copyright [Amazon.com](http://amazon.com/), Inc. or its affiliates. All Rights Reserved.
    SPDX-License-Identifier: Apache-2.0 */
    import {
      App,
      AppProps,
      Aspects,
      IAspect,
      Stack,
      Stage,
      StageSynthesisOptions,
    } from "aws-cdk-lib";
    import { CloudAssembly } from "aws-cdk-lib/cx-api";
    import {
      AwsSolutionsChecks,
      NagPack,
      NagPackSuppression,
      NagSuppressions,
    } from "cdk-nag";
    import { IConstruct } from "constructs";

    const CDK_NAG_MESSAGE_TYPES = {
      ERROR: "aws:cdk:error",
      WARNING: "aws:cdk:warning",
    };
    const CDK_NAG_MESSAGE_TYPES_SET = new Set(Object.values(CDK_NAG_MESSAGE_TYPES));
    const DEFAULT_NAG_PACKS = [
      new AwsSolutionsChecks({
        verbose: true,
        reports: true,
      }),
    ];

    /**
     * Message instance.
     */
    export interface Message {
      /**
       * Message description.
       */
      readonly messageDescription: string;

      /**
       * Message type as returned from cdk-nag.
       */
      readonly messageType: string;
    }

    /**
     * Nag result.
     */
    export interface NagResult {
      /**
       * Resource which triggered the message.
       */
      readonly resource: string;

      /**
       * List of messages.
       */
      readonly messages: Message[];
    }

    /**
     * @inheritDoc
     */
    export interface PDKNagAppProps extends AppProps {
      /**
       * Determines whether any errors encountered should trigger a test failure.
       *
       * @default false
       */
      readonly failOnError?: boolean;

      /**
       * Determines whether any warnings encountered should trigger a test failure.
       *
       * @default false
       */
      readonly failOnWarning?: boolean;

      /**
       * Custom nag packs to execute.
       *
       * @default DEFAULT_NAG_PACKS
       */
      readonly nagPacks?: NagPack[];
    }

    /**
     * @inheritDoc
     */
    export class PDKNagApp extends App {
      private readonly _nagResults: NagResult[] = [];
      private readonly failOnError: boolean;
      private readonly failOnWarning: boolean;
      public readonly nagPacks: NagPack[];

      constructor(props?: PDKNagAppProps) {
        super(props);
        this.failOnError = props?.failOnError ?? false;
        this.failOnWarning = props?.failOnWarning ?? false;
        this.nagPacks = props?.nagPacks ?? DEFAULT_NAG_PACKS;
      }

      synth(options?: StageSynthesisOptions): CloudAssembly {
        const assembly = super.synth(options);

        const typesToFail = new Set(
          [
            this.failOnError && CDK_NAG_MESSAGE_TYPES.ERROR,
            this.failOnWarning && CDK_NAG_MESSAGE_TYPES.WARNING,
          ].filter((t) => t)
        );
        Iif (
          this._nagResults.find((r) =>
            r.messages.find((m) => typesToFail.has(m.messageType))
          )
        ) {
          throw new Error(JSON.stringify(this._nagResults, undefined, 2));
        }

        return assembly;
      }

      addNagResult(result: NagResult) {
        this._nagResults.push(result);
      }

      /**
       * Returns a list of NagResult.
       *
       * Note: app.synth() must be called before this to retrieve results.
       */
      public nagResults(): NagResult[] {
        return this._nagResults;
      }
    }

    class PDKNagAspect implements IAspect {
      private readonly app: PDKNagApp;

      constructor(app: PDKNagApp) {
        this.app = app;
      }

      visit(node: IConstruct): void {
        this.app.nagPacks.forEach((nagPack) => nagPack.visit(node));

        const results = node.node.metadata.filter((m) =>
          CDK_NAG_MESSAGE_TYPES_SET.has(m.type)
        );
        results.length > 0 &&
          this.app.addNagResult({
            resource: node.node.path,
            messages: results.map((m) => ({
              messageDescription: m.data,
              messageType: m.type,
            })),
          });
      }
    }

    /**
     * Helper for create a Nag Enabled App.
     */
    export class PDKNag {
      /**
       * Returns an instance of an App with Nag enabled.
       *
       * @param props props to initialize the app with.
       */
      public static app(props?: PDKNagAppProps): PDKNagApp {
        const app = new PDKNagApp(props);
        Aspects.of(app).add(new PDKNagAspect(app));

        return app;
      }

      /**
       * Wrapper around NagSuppressions which does not throw.
       *
       * @param stack stack instance
       * @param path resource path
       * @param suppressions list of suppressions to apply.
       * @param applyToChildren whether to apply to children.
       */
      public static addResourceSuppressionsByPathNoThrow(
        stack: Stack,
        path: string,
        suppressions: NagPackSuppression[],
        applyToChildren: boolean = false
      ): void {
        try {
          NagSuppressions.addResourceSuppressionsByPath(
            stack,
            path,
            suppressions,
            applyToChildren
          );
        } catch (e) {
          // Do Nothing
        }
      }

      /**
       * Returns a prefix comprising of a delimited set of Stack Ids.
       *
       * For example: StackA/NestedStackB/
       *
       * @param stack stack instance.
       */
      public static getStackPrefix(stack: Stack): string {
        if (stack.nested) {
          return `${PDKNag.getStackPrefix(stack.nestedStackParent!)}${
            stack.node.id
          }/`;
        } else {
          const stageName = Stage.of(stack)?.stageName;
          const stagePrefix = stageName && `${stageName}-`;
          let stackName = stack.stackName;

          stackName =
            stagePrefix && stackName.startsWith(stagePrefix)
              ? `${stageName}/${stackName.slice(stagePrefix.length)}`
              : stackName;
          return `${stackName}/`;
        }
      }

      /**
       * Returns a stack partition regex.
       *
       * @param stack stack instance.
       */
      public static getStackPartitionRegex(stack: Stack): string {
        if (stack.nested) {
          return PDKNag.getStackPartitionRegex(stack.nestedStackParent!);
        } else {
          return stack.partition.startsWith("${Token")
            ? "<AWS::Partition>"
            : `(<AWS::Partition>|${stack.partition})`;
        }
      }

      /**
       * Returns a stack region regex.
       *
       * @param stack stack instance.
       */
      public static getStackRegionRegex(stack: Stack): string {
        if (stack.nested) {
          return PDKNag.getStackRegionRegex(stack.nestedStackParent!);
        } else {
          return stack.region.startsWith("${Token")
            ? "<AWS::Region>"
            : `(<AWS::Region>|${stack.region})`;
        }
      }

      /**
       * Returns a stack account regex.
       *
       * @param stack stack instance.
       */
      public static getStackAccountRegex(stack: Stack): string {
        if (stack.nested) {
          return PDKNag.getStackAccountRegex(stack.nestedStackParent!);
        } else {
          return stack.account.startsWith("${Token")
            ? "<AWS::AccountId>"
            : `(<AWS::AccountId>|${stack.account})`;
        }
      }
    }