All files / src/code_scanner sonar-code-scanner.ts

96.66% Statements 29/30
70% Branches 7/10
80% Functions 4/5
96.55% Lines 28/29

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 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294                                4x 4x 4x           4x 4x 4x 4x 4x 4x 4x                                                                                                                                                                                 4x                             4x 3x   4x 3x           4x   3x   3x   3x           3x                                                                                         3x               3x               3x                 3x                           3x         3x               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 { PDKNag } from "@aws-prototyping-sdk/pdk-nag";
import { CfnOutput, Stack } from "aws-cdk-lib";
import {
  BuildEnvironmentVariableType,
  BuildSpec,
  LinuxBuildImage,
  Project,
} from "aws-cdk-lib/aws-codebuild";
import { EventField, RuleTargetInput } from "aws-cdk-lib/aws-events";
import { CodeBuildProject } from "aws-cdk-lib/aws-events-targets";
import { Effect, PolicyStatement } from "aws-cdk-lib/aws-iam";
import { Secret } from "aws-cdk-lib/aws-secretsmanager";
import { NagSuppressions } from "cdk-nag";
import { Construct } from "constructs";
import {
  createSonarqubeProject,
  generateSonarqubeReports,
  sonarqubeScanner,
} from "./sonarqube-commands";
 
export interface SonarCodeScannerConfig {
  /**
   * path to a file containing the cfn nag suppression rules.
   */
  readonly cfnNagIgnorePath?: string;
 
  /**
   * directory containing the synthesized cdk resources.
   */
  readonly cdkOutDir?: string;
 
  /**
   * glob patterns to exclude from sonar scan.
   */
  readonly excludeGlobsForScan?: string[];
 
  /**
   * glob patterns to include from sonar scan.
   */
  readonly includeGlobsForScan?: string[];
 
  /**
   * endpoint of the sonarqube instance i.e: https://<your-sonarqube-endpoint>.
   *
   * Note: Ensure a trailing '/' is not included.
   */
  readonly sonarqubeEndpoint: string;
 
  /**
   * Default profile/gate name i.e: your org profile.
   *
   * Note: These need to be set up in Sonarqube manually.
   */
  readonly sonarqubeDefaultProfileOrGateName: string;
 
  /**
   * Specific profile/gate name i.e: language specific.
   *
   * Note: These need to be set up in Sonarqube manually.
   */
  readonly sonarqubeSpecificProfileOrGateName?: string;
 
  /**
   * Group name in Sonarqube with access to administer this project.
   */
  readonly sonarqubeAuthorizedGroup: string;
 
  /**
   * Name of the project to create in Sonarqube.
   */
  readonly sonarqubeProjectName: string;
 
  /**
   * Tags to associate with this project.
   */
  readonly sonarqubeTags?: string[];
 
  /**
   * Hook which allows custom commands to be executed before the process commences the archival process.
   */
  readonly preArchiveCommands?: string[];
}
 
/**
 * SonarCodeScanners properties.
 */
export interface SonarCodeScannerProps extends SonarCodeScannerConfig {
  /**
   * ARN for the CodeBuild task responsible for executing the synth command.
   */
  readonly synthBuildArn: string;
 
  /**
   * S3 bucket ARN containing the built artifacts from the synth build.
   */
  readonly artifactBucketArn: string;
 
  /**
   * Artifact bucket key ARN used to encrypt the artifacts.
   */
  readonly artifactBucketKeyArn?: string;
}
 
const unpackSourceAndArtifacts = (includeGlobsForScan?: string[]) => [
  'export BUILT_ARTIFACT_URI=`aws codebuild batch-get-builds --ids $SYNTH_BUILD_ID | jq -r \'.builds[0].secondaryArtifacts[] | select(.artifactIdentifier == "Synth__") | .location\' | awk \'{sub("arn:aws:s3:::","s3://")}1\' $1`',
  "export SYNTH_SOURCE_URI=`aws codebuild batch-get-builds --ids $SYNTH_BUILD_ID | jq -r '.builds[0].sourceVersion' | awk '{sub(\"arn:aws:s3:::\",\"s3://\")}1' $1`",
  "aws s3 cp $SYNTH_SOURCE_URI source.zip",
  "aws s3 cp $BUILT_ARTIFACT_URI built.zip",
  "unzip source.zip -d src",
  "unzip built.zip -d built",
  "rm source.zip built.zip",
  `rsync -a built/* src --include="*/" ${
    includeGlobsForScan
      ? includeGlobsForScan.map((g) => `--include ${g}`).join(" ")
      : ""
  } --include="**/coverage/**" --include="**/cdk.out/**" --exclude="**/node_modules/**/*" --exclude="**/.env/**" --exclude="*" --prune-empty-dirs`,
];
 
const owaspScan = () =>
  `npx owasp-dependency-check --format HTML --out src/reports --exclude '**/.git/**/*' --scan src --enableExperimental --bin /tmp/dep-check --disableRetireJS`;
 
const cfnNagScan = (cdkOutDir?: string, cfnNagIgnorePath?: string) =>
  cdkOutDir
    ? `cfn_nag ${
        cfnNagIgnorePath ? `--deny-list-path=${cfnNagIgnorePath}` : ""
      } built/${cdkOutDir}/**/*.template.json --output-format=json > src/reports/cfn-nag-report.json`
    : 'echo "skipping cfn_nag as no cdkOutDir was specified.';
 
export class SonarCodeScanner extends Construct {
  constructor(scope: Construct, id: string, props: SonarCodeScannerProps) {
    super(scope, id);
 
    const sonarQubeToken = new Secret(this, "SonarQubeToken");
 
    const synthBuildProject = Project.fromProjectArn(
      this,
      "SynthBuildProject",
      props.synthBuildArn
    );
 
    const validationProject = new Project(this, "ValidationProject", {
      environment: {
        buildImage: LinuxBuildImage.STANDARD_5_0,
      },
      environmentVariables: {
        SONARQUBE_TOKEN: {
          type: BuildEnvironmentVariableType.SECRETS_MANAGER,
          value: sonarQubeToken.secretArn,
        },
        SONARQUBE_ENDPOINT: {
          type: BuildEnvironmentVariableType.PLAINTEXT,
          value: props.sonarqubeEndpoint,
        },
        PROJECT_NAME: {
          type: BuildEnvironmentVariableType.PLAINTEXT,
          value: props.sonarqubeProjectName,
        },
      },
      buildSpec: BuildSpec.fromObject({
        version: "0.2",
        env: {
          shell: "bash",
        },
        phases: {
          install: {
            commands: ["npm install -g aws-cdk", "gem install cfn-nag"],
          },
          build: {
            commands: [
              "export RESOLVED_SOURCE_VERSION=`aws codebuild batch-get-builds --ids $SYNTH_BUILD_ID | jq -r '.builds[0].resolvedSourceVersion'`",
              ...unpackSourceAndArtifacts(props.includeGlobsForScan),
              ...createSonarqubeProject(props),
              "mkdir -p src/reports",
              owaspScan(),
              cfnNagScan(props.cdkOutDir, props.cfnNagIgnorePath),
              "cd src",
              sonarqubeScanner(props.excludeGlobsForScan),
              ...generateSonarqubeReports(),
              ...(props.preArchiveCommands || []),
            ],
          },
        },
      }),
    });
 
    validationProject.addToRolePolicy(
      new PolicyStatement({
        actions: ["codebuild:BatchGetBuilds"],
        effect: Effect.ALLOW,
        resources: [synthBuildProject.projectArn],
      })
    );
 
    validationProject.addToRolePolicy(
      new PolicyStatement({
        actions: ["s3:GetObject*"],
        effect: Effect.ALLOW,
        resources: [props.artifactBucketArn, `${props.artifactBucketArn}/**`],
      })
    );
 
    props.artifactBucketKeyArn &&
      validationProject.addToRolePolicy(
        new PolicyStatement({
          actions: ["kms:Decrypt", "kms:DescribeKey"],
          effect: Effect.ALLOW,
          resources: [props.artifactBucketKeyArn],
        })
      );
 
    synthBuildProject.onBuildSucceeded("OnSynthSuccess", {
      target: new CodeBuildProject(validationProject, {
        event: RuleTargetInput.fromObject({
          environmentVariablesOverride: [
            {
              name: "SYNTH_BUILD_ID",
              type: "PLAINTEXT",
              value: EventField.fromPath("$.detail.build-id"),
            },
          ],
        }),
      }),
    });
 
    new CfnOutput(this, "SonarqubeSecretArn", {
      exportName: "SonarqubeSecretArn",
      value: sonarQubeToken.secretArn,
    });
 
    NagSuppressions.addResourceSuppressions(sonarQubeToken, [
      {
        id: "AwsSolutions-SMG4",
        reason:
          "Key rotation is not possible as a user token needs to be generated from Sonarqube",
      },
    ]);
 
    const stack = Stack.of(this);
    NagSuppressions.addResourceSuppressions(
      validationProject.role!,
      [
        {
          id: "AwsSolutions-IAM5",
          reason:
            "Validation CodeBuild project requires access to the ArtifactsBucket and ability to create logs.",
          appliesTo: [
            {
              regex: `/^Resource::arn:${PDKNag.getStackPartitionRegex(
                stack
              )}:logs:${PDKNag.getStackRegionRegex(
                stack
              )}:${PDKNag.getStackAccountRegex(
                stack
              )}:log-group:/aws/codebuild/<.*SonarCodeScannerValidationProject.*>:\\*$/g`,
            },
            {
              regex: `/^Resource::arn:${PDKNag.getStackPartitionRegex(
                stack
              )}:codebuild:${PDKNag.getStackRegionRegex(
                stack
              )}:${PDKNag.getStackAccountRegex(
                stack
              )}:report-group/<.*SonarCodeScannerValidationProject.*>-\\*$/g`,
            },
            {
              regex: `/^Action::s3:GetObject\\*$/g`,
            },
            {
              regex: "/^Resource::<ArtifactsBucket.*.Arn>/\\*\\*$/g",
            },
          ],
        },
      ],
      true
    );
  }
}