All files / lib opa-cluster.ts

35.19% Statements 19/54
0% Branches 0/2
0% Functions 0/2
35.19% Lines 19/54

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 295                              1x   1x 1x 1x 1x 1x       1x 1x 1x   1x 1x 1x 1x 1x 1x 1x         1x                           1x 1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
/* 
  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 * as certificateMgr from "aws-cdk-lib/aws-certificatemanager";
import * as ec2 from "aws-cdk-lib/aws-ec2";
import { SubnetType } from "aws-cdk-lib/aws-ec2";
import * as ecr_assets from "aws-cdk-lib/aws-ecr-assets";
import * as ecs from "aws-cdk-lib/aws-ecs";
import { FargatePlatformVersion } from "aws-cdk-lib/aws-ecs";
import {
  ApplicationLoadBalancedFargateService,
  ApplicationLoadBalancedServiceRecordType,
} from "aws-cdk-lib/aws-ecs-patterns";
import * as elbv2 from "aws-cdk-lib/aws-elasticloadbalancingv2";
import * as iam from "aws-cdk-lib/aws-iam";
import * as logs from "aws-cdk-lib/aws-logs";
import * as route53 from "aws-cdk-lib/aws-route53";
import * as s3 from "aws-cdk-lib/aws-s3";
import * as s3deploy from "aws-cdk-lib/aws-s3-deployment";
import * as cdk from "aws-cdk-lib";
import { CfnOutput, Stack, Token } from "aws-cdk-lib";
import { Construct } from "constructs";
import * as path from "path";
import { FirewallConfigSecureBucket } from "./firewall-config-secure-bucket";
export interface OpaECSClusterProps {
  vpc: ec2.IVpc;
}
 
const ulimits: ecs.Ulimit[] = [
  {
    name: ecs.UlimitName.NOFILE,
    softLimit: 131072,
    hardLimit: 131072,
  },
  {
    name: ecs.UlimitName.NPROC,
    softLimit: 8192,
    hardLimit: 8192,
  },
];
 
// TODO: this is a region aware account as listed above, since we are assume only on ap-southeast-2 for alpha, it's good for now
const CLOUD_WATCH_ACCOUNT = "783225319266";
export class OpaECSCluster extends Construct {
  opaALBDnsName: string;
  loadBalancedFargateService: ApplicationLoadBalancedFargateService;
  constructor(scope: Construct, id: string, props: OpaECSClusterProps) {
    super(scope, id);
    const cluster = new ecs.Cluster(this, "OpaCluster", { vpc: props.vpc });
 
    const policyBucket = new FirewallConfigSecureBucket(
      this,
      "policy-bucket",
      {}
    );
    const asset = new ecr_assets.DockerImageAsset(
      this,
      "ObjectExtensionOpaImage",
      {
        directory: path.join(__dirname, "../opa/"),
      }
    );
 
    const certificateArn = this.node.tryGetContext("certificateArn");
 
    const cert = certificateMgr.Certificate.fromCertificateArn(
      this,
      "elb-cert",
      certificateArn
    );
    const lbProps = {
      vpc: props.vpc,
      internetFacing: false,
      vpcSubnets: {
        subnetType: SubnetType.PRIVATE_WITH_EGRESS,
        onePerAz: true,
      },
    };
    const lb = new elbv2.ApplicationLoadBalancer(this, "LB", lbProps);
 
    const sidecarAsset = ecs.ContainerImage.fromAsset(
      path.join(__dirname, "../ecs_sidecar/"),
      {
        buildArgs: {
          PORT: "443",
          UPSTREAM_PORT: "8080",
        },
      }
    );
    const loadBalancedFargateService =
      new ApplicationLoadBalancedFargateService(this, "Service", {
        cluster,
        memoryLimitMiB: 1024,
        cpu: 512,
        serviceName: "object-extension-opa-service",
        certificate: cert,
        // loadBalancer: loadBalancer,
        protocol: elbv2.ApplicationProtocol.HTTPS,
        // The following 3 parameters are workaround to avoid creating a record and init a new cert
        domainName: "www.dummy.com",
        taskSubnets: { subnetType: SubnetType.PRIVATE_WITH_EGRESS },
        domainZone: {} as route53.IHostedZone,
        recordType: ApplicationLoadBalancedServiceRecordType.NONE,
        openListener: false,
        loadBalancer: lb,
        targetProtocol: elbv2.ApplicationProtocol.HTTPS,
        publicLoadBalancer: false,
        taskImageOptions: {
          image: sidecarAsset,
          enableLogging: true,
          containerPort: 443,
          logDriver: ecs.LogDriver.awsLogs({
            logRetention: logs.RetentionDays.TEN_YEARS,
            streamPrefix: `nginx`,
          }),
        },
        desiredCount: 2,
        platformVersion: FargatePlatformVersion.VERSION1_4,
      });
    const listener: elbv2.CfnListener = loadBalancedFargateService.listener.node
      .defaultChild as elbv2.CfnListener;
    listener.addOverride("Properties.SslPolicy", elbv2.SslPolicy.TLS12_EXT);
    const opaContainer = loadBalancedFargateService.taskDefinition.addContainer(
      "opa",
      {
        containerName: "opa",
        portMappings: [{ containerPort: 8080 }],
        image: ecs.ContainerImage.fromEcrRepository(
          asset.repository,
          asset.assetHash
        ),
        logging: ecs.LogDriver.awsLogs({
          logRetention: logs.RetentionDays.TEN_YEARS,
          streamPrefix: `opa`,
        }),
        environment: {
          BUNDLE_BUCKET: policyBucket.bucket.bucketName,
        },
      }
    );
    opaContainer.addUlimits(...ulimits);
 
    loadBalancedFargateService.targetGroup.configureHealthCheck({
      port: "443",
      path: "/health",
    });
 
    // * A region must be specified on the stack containing the load balancer; you cannot enable logging on
    // * environment-agnostic stacks. See https://docs.aws.amazon.com/cdk/latest/guide/environments.html
    const region = Stack.of(this).region;
    if (Token.isUnresolved(region)) {
      cdk.Annotations.of(this).addWarning(
        "Region is not specified can not enable ELBv2 access logging"
      );
    } else {
      const albAccessLogBucket = this.createElbAccessLogBucket(
        cdk.RemovalPolicy.RETAIN
      );
      loadBalancedFargateService.loadBalancer.logAccessLogs(albAccessLogBucket);
    }
 
    asset.repository.grantPull(
      loadBalancedFargateService.taskDefinition.taskRole
    );
 
    policyBucket.bucket.grantRead(
      loadBalancedFargateService.taskDefinition.taskRole
    );
    policyBucket.encryptionKey.grantEncryptDecrypt(
      loadBalancedFargateService.taskDefinition.taskRole
    );
 
    new s3deploy.BucketDeployment(this, "DeployBundles", {
      sources: [s3deploy.Source.asset("./opa/build/default.zip")],
      destinationBucket: policyBucket.bucket,
      destinationKeyPrefix: "bundles",
    });
 
    // loadBalancedFargateService.node.addDependency(props.policyBucket);
    this.opaALBDnsName =
      loadBalancedFargateService.loadBalancer.loadBalancerDnsName;
    new CfnOutput(this, "OPA-alb-url", {
      value: loadBalancedFargateService.loadBalancer.loadBalancerDnsName,
    });
 
    new CfnOutput(this, "OPA-policy-bucket", {
      value: policyBucket.bucket.bucketName,
    });
    this.loadBalancedFargateService = loadBalancedFargateService;
  }
 
  private createElbAccessLogBucket(removalPolicy: cdk.RemovalPolicy) {
    const elbAccessLogBucket = new s3.Bucket(
      this,
      "opa-alb-elbAccessLogBucket",
      {
        removalPolicy: removalPolicy,
        //only support s3 managed https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-access-logs.html
        encryption: s3.BucketEncryption.S3_MANAGED,
        blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
        accessControl: s3.BucketAccessControl.LOG_DELIVERY_WRITE,
        versioned: true,
        serverAccessLogsPrefix: "access-log",
        autoDeleteObjects: removalPolicy == cdk.RemovalPolicy.DESTROY,
      }
    );
 
    elbAccessLogBucket.addToResourcePolicy(
      new iam.PolicyStatement({
        sid: "HttpsOnly",
        resources: [`${elbAccessLogBucket.bucketArn}/*`],
        actions: ["*"],
        principals: [new iam.AnyPrincipal()],
        effect: iam.Effect.DENY,
        conditions: {
          Bool: {
            "aws:SecureTransport": "false",
          },
        },
      })
    );
    // https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-access-logs.html?icmpid=docs_elbv2_console
    elbAccessLogBucket.addToResourcePolicy(
      new iam.PolicyStatement({
        effect: iam.Effect.ALLOW,
        actions: ["s3:PutObject"],
        principals: [new iam.AccountPrincipal(CLOUD_WATCH_ACCOUNT)],
        resources: [
          `arn:aws:s3:::${elbAccessLogBucket.bucketName}/AWSLogs/${
            Stack.of(this).account
          }/*`,
        ],
      })
    );
 
    elbAccessLogBucket.addToResourcePolicy(
      new iam.PolicyStatement({
        effect: iam.Effect.ALLOW,
        actions: ["s3:PutObject"],
        principals: [new iam.ServicePrincipal("delivery.logs.amazonaws.com")],
        resources: [
          `arn:aws:s3:::${elbAccessLogBucket.bucketName}/AWSLogs/${
            Stack.of(this).account
          }/*`,
        ],
        conditions: {
          StringEquals: {
            "s3:x-amz-acl": "bucket-owner-full-control",
          },
        },
      })
    );
 
    elbAccessLogBucket.addToResourcePolicy(
      new iam.PolicyStatement({
        effect: iam.Effect.ALLOW,
        actions: ["s3:PutObject"],
        principals: [new iam.ServicePrincipal("logdelivery.elb.amazonaws.com")],
        resources: [
          `arn:aws:s3:::${elbAccessLogBucket.bucketName}/AWSLogs/${
            Stack.of(this).account
          }/*`,
        ],
        conditions: {
          StringEquals: {
            "s3:x-amz-acl": "bucket-owner-full-control",
          },
        },
      })
    );
 
    elbAccessLogBucket.addToResourcePolicy(
      new iam.PolicyStatement({
        effect: iam.Effect.ALLOW,
        actions: ["s3:GetBucketAcl"],
        principals: [new iam.ServicePrincipal("delivery.logs.amazonaws.com")],
        resources: [`arn:aws:s3:::${elbAccessLogBucket.bucketName}`],
      })
    );
    return elbAccessLogBucket;
  }
}