import * as cdk from "@aws-cdk/core";
import * as iam from "@aws-cdk/aws-iam";
import * as s3 from "@aws-cdk/aws-s3";

/**
 * Interface for enabling flow logs.
 */
export interface FlowLogsProps {
  /**
   * The ID of the VPC that we want to instrument. (The VPC that Autohost is running in.)
   */
  readonly vpcID: string;
}

/**
 * FlowLogs allows us to capture logs on the traffic in our VPC.
 * It creates an S3 bucket that will store the logs.
 *
 * For now, we have to create the flow logs through the AWS console because Cloudformation
 * does not support custom formats. (We need to use custom formats to include additional
 * fields that the default format does not have.)
 */
export class FlowLogs extends cdk.Construct {
  constructor(scope: cdk.Construct, id: string, props: FlowLogsProps) {
    super(scope, id);
    const stack = cdk.Stack.of(this);
    const accountID = stack.account;

    // The S3 bucket that will store the traffic logs.
    // Files will be automatically deleted after about 6 months.
    const bucket = new s3.Bucket(this, "Bucket", {
      bucketName: `flow-logs-${accountID}`,
      lifecycleRules: [
        {
          expiration: cdk.Duration.days(31 * 6) // approx 6 months,
        }
      ]
    });

    // Add the bucket policy needed to allow the Flow Logs service to write to the bucket.
    // https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs-s3.html#flow-logs-s3-permissions
    bucket.addToResourcePolicy(
      new iam.PolicyStatement({
        effect: iam.Effect.ALLOW,
        principals: [new iam.ServicePrincipal("delivery.logs.amazonaws.com")],
        actions: ["s3:PutObject"],
        resources: [bucket.arnForObjects("*")],
        conditions: {
          StringEquals: {
            "s3:x-amz-acl": "bucket-owner-full-control"
          }
        }
      })
    );
    bucket.addToResourcePolicy(
      new iam.PolicyStatement({
        effect: iam.Effect.ALLOW,
        principals: [new iam.ServicePrincipal("delivery.logs.amazonaws.com")],
        actions: ["s3:GetBucketAcl"],
        resources: [bucket.bucketArn]
      })
    );
  }
}
