# All files / src pdk-pipeline.ts

100% Statements 38/38
80.76% Branches 21/26
100% Functions 7/7
100% Lines 38/38

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

    4x
    4x
    4x
    4x
    4x

    4x

    4x
    4x
    4x

    4x

    4x

    4x

    6x

    6x

    6x

    6x

    6x

    6x

    6x

    6x

    6x

    6x

    6x

    6x
    6x
    6x

    6x

    6x
    6x

    6x

    6x

    6x

    6x

    6x

    6x

    6x

    18x

    36x

     /*! Copyright [Amazon.com](http://amazon.com/), Inc. or its affiliates. All Rights Reserved.
    SPDX-License-Identifier: Apache-2.0 */
    import { Aspects, CfnOutput, RemovalPolicy, Stage } from "aws-cdk-lib";
    import { Repository } from "aws-cdk-lib/aws-codecommit";
    import { Pipeline } from "aws-cdk-lib/aws-codepipeline";
    import { Key } from "aws-cdk-lib/aws-kms";
    import {
      BlockPublicAccess,
      Bucket,
      BucketEncryption,
      ObjectOwnership,
    } from "aws-cdk-lib/aws-s3";
    import {
      AddStageOpts,
      CodePipeline,
      CodePipelineProps,
      CodePipelineSource,
      ShellStep,
      ShellStepProps,
      StageDeployment,
    } from "aws-cdk-lib/pipelines";
    import { NagSuppressions } from "cdk-nag";
    import { Construct } from "constructs";
    import {
      SonarCodeScanner,
      SonarCodeScannerConfig,
    } from "./code_scanner/sonar-code-scanner";

    export * from "./code_scanner/sonar-code-scanner";

    const DEFAULT_BRANCH_NAME = "mainline";

    /**
     * Properties to configure the PDKPipeline.
     *
     * Note: Due to limitations with JSII and generic support it should be noted that
     * the synth, synthShellStepPartialProps.input and
     * synthShellStepPartialProps.primaryOutputDirectory properties will be ignored
     * if passed in to this construct.
     *
     * synthShellStepPartialProps.commands is marked as a required field, however
     * if you pass in [] the default commands of this construct will be retained.
     */
    export interface PDKPipelineProps extends CodePipelineProps {
      /**
       * Name of the CodeCommit repository to create.
       */
      readonly repositoryName: string;

      /**
       * Output directory for cdk synthesized artifacts i.e: packages/infra/cdk.out.
       */
      readonly primarySynthDirectory: string;

      /**
       * PDKPipeline by default assumes a NX Monorepo structure for it's codebase and
       * uses sane defaults for the install and run commands. To override these defaults
       * and/or provide additional inputs, specify env settings, etc you can provide
       * a partial ShellStepProps.
       */
      readonly synthShellStepPartialProps?: ShellStepProps;

      /**
       * Branch to trigger the pipeline execution.
       *
       * @default mainline
       */
      readonly defaultBranchName?: string;

      /**
       * Configuration for enabling Sonarqube code scanning on a successful synth.
       *
       * @default undefined
       */
      readonly sonarCodeScannerConfig?: SonarCodeScannerConfig;

      /**
       * Possible values for a resource's Removal Policy
       * The removal policy controls what happens to the resource if it stops being managed by CloudFormation.
       */
      readonly codeCommitRemovalPolicy?: RemovalPolicy;
    }

    /**
     * An extension to CodePipeline which configures sane defaults for a NX Monorepo
     * codebase. In addition to this, it also creates a CodeCommit repository with
     * automated PR builds and approvals.
     */
    export class PDKPipeline extends Construct {
      readonly codePipeline: CodePipeline;
      readonly codeRepository: Repository;
      private readonly sonarCodeScannerConfig?: SonarCodeScannerConfig;

      public constructor(scope: Construct, id: string, props: PDKPipelineProps) {
        super(scope, id);

        this.node.setContext(
          "@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy",
          true
        );

        const codeRepository = new Repository(this, "CodeRepository", {
          repositoryName: props.repositoryName,
        });
        codeRepository.applyRemovalPolicy(
          props.codeCommitRemovalPolicy ?? RemovalPolicy.RETAIN
        );

        const accessLogsBucket = new Bucket(this, "AccessLogsBucket", {
          versioned: false,
          enforceSSL: true,
          autoDeleteObjects: true,
          removalPolicy: RemovalPolicy.DESTROY,
          encryption: BucketEncryption.S3_MANAGED,
          objectOwnership: ObjectOwnership.BUCKET_OWNER_ENFORCED,
          publicReadAccess: false,
          blockPublicAccess: BlockPublicAccess.BLOCK_ALL,
        });

        const artifactBucket = new Bucket(this, "ArtifactsBucket", {
          enforceSSL: true,
          autoDeleteObjects: true,
          removalPolicy: RemovalPolicy.DESTROY,
          encryption: props.crossAccountKeys
            ? BucketEncryption.KMS
            : BucketEncryption.S3_MANAGED,
          encryptionKey: props.crossAccountKeys
            ? new Key(this, "ArtifactKey", {
                enableKeyRotation: true,
                removalPolicy: RemovalPolicy.DESTROY,
              })
            : undefined,
          objectOwnership: ObjectOwnership.BUCKET_OWNER_ENFORCED,
          publicReadAccess: false,
          blockPublicAccess: BlockPublicAccess.BLOCK_ALL,
          serverAccessLogsPrefix: "access-logs",
          serverAccessLogsBucket: accessLogsBucket,
        });

        const codePipeline = new Pipeline(this, "CodePipeline", {
          enableKeyRotation: props.crossAccountKeys,
          restartExecutionOnUpdate: true,
          crossAccountKeys: props.crossAccountKeys,
          artifactBucket,
        });

        // ignore input and primaryOutputDirectory
        const {
          input,
          primaryOutputDirectory,
          commands,
          ...synthShellStepPartialProps
        } = props.synthShellStepPartialProps || {};

        const synthShellStep = new ShellStep("Synth", {
          input: CodePipelineSource.codeCommit(
            codeRepository,
            props.defaultBranchName || DEFAULT_BRANCH_NAME
          ),
          installCommands: [
            "npm install -g aws-cdk",
            "yarn install --frozen-lockfile || npx projen && yarn install --frozen-lockfile",
          ],
          commands:
            commands && commands.length > 0
              ? commands
              : ["npx nx run-many --target=build --all"],
          primaryOutputDirectory: props.primarySynthDirectory,
          ...(synthShellStepPartialProps || {}),
        });

        synthShellStep.addOutputDirectory(".");

        const codePipelineProps: CodePipelineProps = {
          codePipeline,
          ...props,
          crossAccountKeys: undefined,
          synth: synthShellStep,
        };

        this.codePipeline = new CodePipeline(this, id, codePipelineProps);
        this.codeRepository = codeRepository;
        this.sonarCodeScannerConfig = props.sonarCodeScannerConfig
          ? {
              cdkOutDir: props.primarySynthDirectory,
              ...props.sonarCodeScannerConfig,
            }
          : undefined;

        new CfnOutput(this, "CodeRepositoryGRCUrl", {
          value: this.codeRepository.repositoryCloneUrlGrc,
        });
      }

      /**
       * @inheritDoc
       */
      addStage(stage: Stage, options?: AddStageOpts): StageDeployment {
        // Add any root Aspects to the stage level as currently this doesn't happen automatically
        Aspects.of(stage.node.root).all.forEach((aspect) =>
          Aspects.of(stage).add(aspect)
        );
        return this.codePipeline.addStage(stage, options);
      }

      buildPipeline() {
        this.codePipeline.buildPipeline();

        this.sonarCodeScannerConfig &&
          new SonarCodeScanner(this, "SonarCodeScanner", {
            artifactBucketArn: this.codePipeline.pipeline.artifactBucket.bucketArn,
            artifactBucketKeyArn:
              this.codePipeline.pipeline.artifactBucket.encryptionKey?.keyArn,
            synthBuildArn: this.codePipeline.synthProject.projectArn,
            ...this.sonarCodeScannerConfig,
          });

        this.suppressCDKViolations();
      }

      suppressCDKViolations() {
        this.suppressRules(
          ["AwsSolutions-IAM5", "AwsPrototyping-IAMNoWildcardPermissions"],
          "Wildcards are needed for dynamically created resources."
        );

        this.suppressRules(
          [
            "AwsSolutions-CB4",
            "AwsPrototyping-CodeBuildProjectKMSEncryptedArtifacts",
          ],
          "Encryption of Codebuild is not required."
        );

        this.suppressRules(
          ["AwsSolutions-S1", "AwsPrototyping-S3BucketLoggingEnabled"],
          "Access Log buckets should not have s3 bucket logging"
        );
      }

      private suppressRules(rules: string[], reason: string) {
        NagSuppressions.addResourceSuppressions(
          this,
          rules.map((r) => ({
            id: r,
            reason,
          })),
          true
        );
      }
    }