@guardian/cdk 63.3.1 → 63.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/constructs/loadbalancing/alb/application-listener.d.ts +2 -2
- package/lib/constructs/loadbalancing/alb/application-listener.d.ts.map +1 -1
- package/lib/constructs/loadbalancing/alb/application-listener.js +1 -1
- package/lib/constructs/loadbalancing/alb/application-listener.js.map +1 -1
- package/lib/experimental/constructs/riff-raff-deployment-id.d.ts +8 -0
- package/lib/experimental/constructs/riff-raff-deployment-id.d.ts.map +1 -0
- package/lib/experimental/constructs/riff-raff-deployment-id.js +21 -0
- package/lib/experimental/constructs/riff-raff-deployment-id.js.map +1 -0
- package/lib/experimental/patterns/ec2-app.d.ts.map +1 -1
- package/lib/experimental/patterns/ec2-app.js +2 -15
- package/lib/experimental/patterns/ec2-app.js.map +1 -1
- package/lib/experimental/patterns/gu-load-balanced-app.d.ts +351 -0
- package/lib/experimental/patterns/gu-load-balanced-app.d.ts.map +1 -0
- package/lib/experimental/patterns/gu-load-balanced-app.js +491 -0
- package/lib/experimental/patterns/gu-load-balanced-app.js.map +1 -0
- package/lib/patterns/ec2-app/base.d.ts +12 -5
- package/lib/patterns/ec2-app/base.d.ts.map +1 -1
- package/lib/patterns/ec2-app/base.js +5 -1
- package/lib/patterns/ec2-app/base.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Duration } from "aws-cdk-lib";
|
|
2
2
|
import type { BlockDevice, UpdatePolicy } from "aws-cdk-lib/aws-autoscaling";
|
|
3
|
-
import type { InstanceType, ISubnet, IVpc } from "aws-cdk-lib/aws-ec2";
|
|
4
|
-
import { UserData } from "aws-cdk-lib/aws-ec2";
|
|
3
|
+
import type { InstanceType, IPeer, ISubnet, IVpc } from "aws-cdk-lib/aws-ec2";
|
|
4
|
+
import { Port, UserData } from "aws-cdk-lib/aws-ec2";
|
|
5
5
|
import type { HealthCheck as ALBHealthCheck } from "aws-cdk-lib/aws-elasticloadbalancingv2";
|
|
6
6
|
import { Construct } from "constructs";
|
|
7
7
|
import { GuCertificate } from "../../constructs/acm";
|
|
@@ -88,9 +88,8 @@ export interface GuEc2AppProps extends AppIdentity {
|
|
|
88
88
|
/**
|
|
89
89
|
* Network access restrictions for your load balancer.
|
|
90
90
|
*
|
|
91
|
-
* Note, this merely provides defence in depth; you should
|
|
92
|
-
* access
|
|
93
|
-
* Auth for human access, or a suitable machine auth mechanism.
|
|
91
|
+
* Note, this merely provides defence in depth; you should NOT rely on network access restrictions alone for
|
|
92
|
+
* restricting access. Use Google Auth for human access, or a suitable machine auth mechanism.
|
|
94
93
|
*/
|
|
95
94
|
access: AppAccess;
|
|
96
95
|
/**
|
|
@@ -299,6 +298,14 @@ export interface GuEc2AppProps extends AppIdentity {
|
|
|
299
298
|
*/
|
|
300
299
|
instanceMetricGranularity: "1Minute" | "5Minute";
|
|
301
300
|
}
|
|
301
|
+
/**
|
|
302
|
+
* Use this to allow specific CIDR ranges to access a load balancer over HTTPS
|
|
303
|
+
*/
|
|
304
|
+
export declare function restrictedCidrRanges(ranges: IPeer[]): {
|
|
305
|
+
range: IPeer;
|
|
306
|
+
port: Port;
|
|
307
|
+
description: string;
|
|
308
|
+
}[];
|
|
302
309
|
/**
|
|
303
310
|
* Pattern which creates the resources needed to run an application on EC2
|
|
304
311
|
* behind a load balancer. For convenience, you may wish to use [[`GuPlayApp`]]
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.d.ts","sourceRoot":"","sources":["../../../src/patterns/ec2-app/base.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAqB,MAAM,aAAa,CAAC;AAC1D,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAQ7E,OAAO,KAAK,EAAE,YAAY,
|
|
1
|
+
{"version":3,"file":"base.d.ts","sourceRoot":"","sources":["../../../src/patterns/ec2-app/base.ts"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{ value: true });
|
|
3
|
-
exports.GuEc2App = void 0;
|
|
3
|
+
exports.GuEc2App = exports.restrictedCidrRanges = void 0;
|
|
4
4
|
/* eslint "@guardian/tsdoc-required/tsdoc-required": 2 -- to begin rolling this out for public APIs. */
|
|
5
5
|
const aws_cdk_lib_1 = require("aws-cdk-lib");
|
|
6
6
|
const aws_autoscaling_1 = require("aws-cdk-lib/aws-autoscaling");
|
|
@@ -23,6 +23,9 @@ const lambda_1 = require("../../constructs/lambda");
|
|
|
23
23
|
const loadbalancing_1 = require("../../constructs/loadbalancing");
|
|
24
24
|
const types_1 = require("../../types");
|
|
25
25
|
const cognito_1 = require("../../utils/cognito/cognito");
|
|
26
|
+
/**
|
|
27
|
+
* Use this to allow specific CIDR ranges to access a load balancer over HTTPS
|
|
28
|
+
*/
|
|
26
29
|
function restrictedCidrRanges(ranges) {
|
|
27
30
|
return ranges.map((range) => ({
|
|
28
31
|
range,
|
|
@@ -30,6 +33,7 @@ function restrictedCidrRanges(ranges) {
|
|
|
30
33
|
description: `Allow access on port 443 from ${range.uniqueId}`,
|
|
31
34
|
}));
|
|
32
35
|
}
|
|
36
|
+
exports.restrictedCidrRanges = restrictedCidrRanges;
|
|
33
37
|
/**
|
|
34
38
|
* Pattern which creates the resources needed to run an application on EC2
|
|
35
39
|
* behind a load balancer. For convenience, you may wish to use [[`GuPlayApp`]]
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.js","sourceRoot":"","sources":["../../../src/patterns/ec2-app/base.ts"],"names":[],"mappings":";;;AAAA,uGAAuG;AACvG,6CAA0D;AAE1D,iEAAsF;AACtF,yDAKiC;AAEjC,iDAAqD;AAErD,uFAA6F;AAC7F,uGAA2F;AAC3F,iDAA8D;AAC9D,uDAA+D;AAC/D,iDAAsD;AACtD,2CAAuC;AACvC,+CAAuF;AACvF,8CAAqD;AAErD,8DAA8E;AAE9E,4DAIqC;AAErC,gDAAkF;AAClF,8CAAsG;AAEtG,8CAAgF;AAChF,oDA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BAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;gBAClC,mBAAmB,EAAE,sBAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;gBACtC,oBAAoB,EAAE,sBAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;aACvC,CAAC,CAAC;YAEH,cAAc,CAAC,IAAI,CAAC,aAAa,CAAC,WAAW,CAAC,CAAC;YAE/C,QAAQ,CAAC,SAAS,CAAC,aAAa,EAAE;gBAChC,MAAM,EAAE,IAAI,8DAAyB,CAAC;oBACpC,QAAQ,EAAE,QAAQ;oBAClB,cAAc,EAAE,cAAc;oBAC9B,cAAc,EAAE,cAAc;oBAC9B,IAAI,EAAE,2CAAc,CAAC,OAAO,CAAC,CAAC,WAAW,CAAC,CAAC;oBAC3C,cAAc,EAAE,sBAAQ,CAAC,OAAO,CAAC,uBAAuB,CAAC;iBAC1D,CAAC;aACH,CAAC,CAAC;YAEH,qEAAqE;YACrE,MAAM,sBAAsB,GAAG,IAAI,gCAA0B,CAAC,KAAK,EAAE,YAAY,EAAE;gBACjF,GAAG;gBACH,GAAG;aACJ,CAAC,CAAC;YAEH,YAAY,CAAC,gBAAgB,CAAC,sBAAsB,CAAC,CAAC;SACvD;QAED,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAC;QACzC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;CACF;AA7UD,4BA6UC","sourcesContent":["/* eslint \"@guardian/tsdoc-required/tsdoc-required\": 2 -- to begin rolling this out for public APIs. */\nimport { Duration, SecretValue, Tags } from \"aws-cdk-lib\";\nimport type { BlockDevice, UpdatePolicy } from \"aws-cdk-lib/aws-autoscaling\";\nimport { AdditionalHealthCheckType, HealthChecks } from \"aws-cdk-lib/aws-autoscaling\";\nimport {\n ProviderAttribute,\n UserPool,\n UserPoolClientIdentityProvider,\n UserPoolIdentityProviderGoogle,\n} from \"aws-cdk-lib/aws-cognito\";\nimport type { InstanceType, IPeer, ISubnet, IVpc } from \"aws-cdk-lib/aws-ec2\";\nimport { Port, UserData } from \"aws-cdk-lib/aws-ec2\";\nimport type { HealthCheck as ALBHealthCheck } from \"aws-cdk-lib/aws-elasticloadbalancingv2\";\nimport { ApplicationProtocol, ListenerAction } from \"aws-cdk-lib/aws-elasticloadbalancingv2\";\nimport { AuthenticateCognitoAction } from \"aws-cdk-lib/aws-elasticloadbalancingv2-actions\";\nimport { Effect, PolicyStatement } from \"aws-cdk-lib/aws-iam\";\nimport { Architecture, Runtime } from \"aws-cdk-lib/aws-lambda\";\nimport { StringParameter } from \"aws-cdk-lib/aws-ssm\";\nimport { Construct } from \"constructs\";\nimport { AccessScope, MetadataKeys, NAMED_SSM_PARAMETER_PATHS } from \"../../constants\";\nimport { GuCertificate } from \"../../constructs/acm\";\nimport type { GuUserDataProps } from \"../../constructs/autoscaling\";\nimport { GuAutoScalingGroup, GuUserData } from \"../../constructs/autoscaling\";\nimport type { Http4xxAlarmProps, Http5xxAlarmProps, NoMonitoring } from \"../../constructs/cloudwatch\";\nimport {\n GuAlb4xxPercentageAlarm,\n GuAlb5xxPercentageAlarm,\n GuUnhealthyInstancesAlarm,\n} from \"../../constructs/cloudwatch\";\nimport type { GuStack } from \"../../constructs/core\";\nimport { AppIdentity, GuLoggingStreamNameParameter } from \"../../constructs/core\";\nimport { GuHttpsEgressSecurityGroup, GuSecurityGroup, GuVpc, SubnetType } from \"../../constructs/ec2\";\nimport type { GuInstanceRoleProps } from \"../../constructs/iam\";\nimport { GuGetPrivateConfigPolicy, GuInstanceRole } from \"../../constructs/iam\";\nimport { GuLambdaFunction } from \"../../constructs/lambda\";\nimport {\n GuApplicationLoadBalancer,\n GuApplicationTargetGroup,\n GuHttpsApplicationListener,\n} from \"../../constructs/loadbalancing\";\nimport type { WafProps } from \"../../constructs/loadbalancing\";\nimport { AppAccess } from \"../../types\";\nimport type { GuAsgCapacity, GuDomainName } from \"../../types\";\nimport type { AmigoProps } from \"../../types/amigo\";\nimport { getUserPoolDomainPrefix } from \"../../utils/cognito/cognito\";\n\n/**\n * To ship your application logs to ELK automatically, you must:\n *\n * 1. Set the `enabled` flag to true\n * 2. Include the `cdk-base` Amigo role in your AMI\n * 3. Log to `journald`. We recommend doing this by logging to `stdout` and\n * using `systemd` to start your app\n * 4. Confirm that your [[`systemdUnitName`]] is configured properly.\n *\n * Unless you have explicitly opted-out, appropriate IAM permissions for logging\n * to Kinesis will be configured automatically via the [[`GuEc2App`]] pattern.\n */\nexport interface ApplicationLoggingProps {\n /**\n * Enables forwarding of application logs to the Guardian ELK stack.\n *\n * Note, to work, you will need to also do the following non-CDK things:\n *\n * 1. Include the `cdk-base` Amigo role in your AMI.\n * 2. Log to `journald`. We recommend doing this by logging to `stdout` and\n * using `systemd` to start your app\n * 3. Confirm that your [[`systemdUnitName`]] is configured properly.\n *\n * Unless you have explicitly opted-out, appropriate IAM permissions for\n * logging to Kinesis will be configured automatically via the [[`GuEc2App`]]\n * pattern.\n *\n * @see https://github.com/guardian/amigo/tree/main/roles/cdk-base\n */\n enabled: boolean;\n /**\n * This needs to match the name of your SystemD unit.\n *\n * If your systemd unit is not `<app>.service` set this value.\n *\n * @defaultValue `<app>.service`\n */\n systemdUnitName?: string;\n}\n\n/**\n * @privateRemarks we should rename this to AlarmsProps.\n */\nexport interface Alarms {\n /**\n * Name of the target (SNS Topic) for alarm notifications.\n */\n snsTopicName: string;\n /**\n * Enable the 5xx alarm with settings.\n */\n http5xxAlarm: false | Http5xxAlarmProps;\n /**\n * Enable the 4xx alarm with settings.\n */\n http4xxAlarm?: false | Http4xxAlarmProps;\n /**\n * Enable the unhealthy instances alarm.\n */\n unhealthyInstancesAlarm: boolean;\n /**\n * Internal flag - users of this library should ignore this setting.\n */\n noMonitoring?: false;\n}\n\nexport interface GuEc2AppProps extends AppIdentity {\n /**\n * User data for the autoscaling group.\n */\n userData: GuUserDataProps | UserData;\n /**\n * Network access restrictions for your load balancer.\n *\n * Note, this merely provides defence in depth; you should, for example, limit\n * access to the VPN and then treat that as sufficient. Instead, use Google\n * Auth for human access, or a suitable machine auth mechanism.\n */\n access: AppAccess;\n /**\n * The port your application runs on.\n */\n applicationPort: number;\n /**\n * Configure IAM roles for autoscaling group EC2 instances.\n */\n roleConfiguration?: GuInstanceRoleProps;\n /**\n * Enable and configure alarms.\n */\n monitoringConfiguration: Alarms | NoMonitoring;\n /**\n * EC2 instance type. Note, ensure your code is built for the same\n * architecture family (arm64 - 'Graviton' instances - or x64).\n */\n instanceType: InstanceType;\n /**\n * Enable and configures application logs.\n */\n applicationLogging?: ApplicationLoggingProps;\n\n /**\n * Enable access logging for this load balancer.\n * Access logs are written to an S3 bucket within your AWS account.\n * The bucket is created by {@link https://github.com/guardian/aws-account-setup}.\n * The logs are queryable via the `gucdk_access_logs` Athena database.\n *\n * @defaultValue true\n */\n withAccessLogging?: boolean;\n\n /**\n * Add block devices (additional storage).\n */\n blockDevices?: BlockDevice[];\n /**\n * Autoscaling group min and max sizes.\n */\n scaling: GuAsgCapacity;\n /**\n * Specify certificate for the load balancer.\n */\n certificateProps?: GuDomainName;\n\n /**\n * Configure AMIgo image recipe. This is only necessary if you are using GuCDK to generate your riff-raff.yaml file.\n */\n imageRecipe?: string | AmigoProps;\n /**\n * Specify the VPC to use.\n *\n * @see https://github.com/guardian/aws-account-setup\n */\n vpc?: IVpc;\n /**\n * Specify private subnets if using a non-default VPC or (generally\n * discouraged) to limit to a subset of the available subnets.\n */\n privateSubnets?: ISubnet[];\n\n /**\n * Specify private subnets if using a non-default VPC or (generally\n * discouraged) to limit to a subset of the available subnets.\n */\n publicSubnets?: ISubnet[];\n\n /**\n * Configure Google Auth.\n */\n googleAuth?: {\n /**\n * Enables Google Auth (via Cognito). **Additional MANUAL steps required -\n * see below.**\n *\n * Limits access to members of the allowed Google groups.\n *\n * Note, this does not currently support simultaneous machine access, so\n * only set to true if you only require staff access to your service, or are\n * supporting machine access in some other way.\n *\n * MANUAL STEPS: to get this to work, we need a Google Project and\n * associated credentials. Full instructions can be found here:\n *\n * https://docs.google.com/document/d/1_k1FSE52AZHXufWLTiKTI3xy5cGpziyHazSHTKrYfco/edit?usp=sharing\n *\n * DevX hope to automate this process in the near future.\n */\n enabled: true;\n /**\n * The domain users will access your service.\n *\n * Set this to the same as for certificateProps.\n */\n domain: string;\n /**\n * Groups used for membership checks.\n *\n * If specified, cannot be empty. Users must be a member of at least one\n * group to gain access.\n *\n * WARNING: groups must be specified with the `guardian.co.uk` domain, even\n * if that is the non-idiomatic choice for daily use.\n *\n * @defaultValue [`engineering@guardian.co.uk`]\n */\n allowedGroups?: string[];\n /**\n * The number of minutes before the session expires.\n *\n * Set this value to a safe period of time that revoked users\n * sessions will continue to function.\n *\n * NOTE: This value cannot be larger than 60 minutes.\n *\n * @defaultValue 15\n */\n sessionTimeoutInMinutes?: number;\n /**\n * Secrets Manager path containing Google OAuth2 Client credentials.\n *\n * NOTE: you do not need to set this value, but you DO need to generate and\n * store the associated credentials in Secrets Manager.\n *\n * Credentials should be stored in Secrets Manager as JSON:\n *\n * ```json\n * {\n * \"clientId\": \"my-client-id\",\n * \"clientSecret\": \"my-client-secret\"\n * }\n * ```\n *\n * @see `googleAuth.enabled` for how to generate.\n *\n * @defaultValue /:STAGE/:stack/:app/google-auth-credentials\n */\n credentialsSecretsManagerPath?: string;\n\n /**\n * When using Auth in the ALB, which stage of cognito-lambda to use.\n *\n * For most applications this should always be PROD, even in the CODE environments.\n *\n * @defaultValue PROD\n */\n cognitoAuthStage?: string;\n };\n\n /**\n * Specify custom healthcheck\n */\n healthcheck?: ALBHealthCheck;\n\n /**\n * Set http put response hop limit for the launch template.\n * It can be necessary to raise this value from the default of 1\n * for example when sharing the instance profile with a docker container running on the instance.\n */\n instanceMetadataHopLimit?: number;\n\n /**\n * Specify an update policy for the ASG created by this pattern.\n *\n * @see https://docs.aws.amazon.com/cdk/api/latest/docs/aws-autoscaling-readme.html#update-policy\n *\n * @defaultValue UpdatePolicy.none() - Cloudformation does not attempt to rotate instances in the ASG\n * and must rely on riffraff to do so.\n */\n updatePolicy?: UpdatePolicy;\n\n /**\n * You can specify how long after an instance reaches the InService state it waits before contributing\n * usage data to the aggregated metrics. This specified time is called the default instance warmup.\n * This keeps dynamic scaling from being affected by metrics for individual instances that aren't yet\n * handling application traffic and that might be experiencing temporarily high usage of compute resources.\n *\n * @see https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-default-instance-warmup.html\n */\n defaultInstanceWarmup?: Duration;\n\n /**\n * You can specify if the arn of this load balancer should be exposed for protection via WAF\n *\n * If this value changes, it is only picked up on WAF configuration redeploy.\n *\n * NB this parameter setting _alone_ is not sufficient to protect the application.\n * You must also ensure that the application and stage combination is present in the WAF\n * configuration.\n *\n * See https://github.com/guardian/waf/tree/main/lib\n *\n * There is a \"gotcha\" when migrating to this functionality. You may not change only the Logical\n * ID of an SSM Parameter (see https://docs.aws.amazon.com/cdk/v2/guide/identifiers.html) and the\n * parameter name must be of the required form, meaning you cannot have an alternate name.\n *\n * You can either:\n *\n * Remove the old param and immediately redeploy with the new param (this does not affect\n * protection unless and until the WAF configuration is redeployed)\n *\n * OR\n *\n * Create an escape hatch by overriding the logical id (see \"ssm param escape hatch\" test for example)\n **/\n waf?: WafProps;\n\n /**\n * How often to send EC2 metrics, such as CPU usage.\n * By default, AWS will produce `5Minute` granular metrics.\n *\n * It is recommended to produce `1Minute` granular metrics in production,\n * especially when using ASG metrics to trigger horizontal scaling as it allows for earlier scaling.\n *\n * @see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/viewing_metrics_with_cloudwatch.html\n */\n instanceMetricGranularity: \"1Minute\" | \"5Minute\";\n}\n\nfunction restrictedCidrRanges(ranges: IPeer[]) {\n return ranges.map((range) => ({\n range,\n port: Port.tcp(443),\n description: `Allow access on port 443 from ${range.uniqueId}`,\n }));\n}\n\n/**\n * Pattern which creates the resources needed to run an application on EC2\n * behind a load balancer. For convenience, you may wish to use [[`GuPlayApp`]]\n * or [[`GuNodeApp`]], which extend this class.\n *\n * See props for further details.\n */\nexport class GuEc2App extends Construct {\n /*\n * These are public for now, as this allows users to\n * modify these constructs as desired to fit their\n * specific needs.\n * In the future, we might build functionality to better enable users\n * to access in-pattern constructs, but this would allow teams to be unblocked\n * in the short term.\n * */\n public readonly vpc: IVpc;\n public readonly certificate?: GuCertificate;\n public readonly loadBalancer: GuApplicationLoadBalancer;\n public readonly autoScalingGroup: GuAutoScalingGroup;\n public readonly listener: GuHttpsApplicationListener;\n public readonly targetGroup: GuApplicationTargetGroup;\n\n constructor(scope: GuStack, props: GuEc2AppProps) {\n const {\n access,\n withAccessLogging = true,\n app,\n // We should update this default once a significant number of apps have migrated to devx-logs\n applicationLogging = { enabled: false },\n applicationPort,\n blockDevices,\n certificateProps,\n instanceType,\n monitoringConfiguration,\n roleConfiguration = { withoutLogShipping: false, additionalPolicies: [] },\n scaling: { minimumInstances, maximumInstances = minimumInstances * 2 },\n userData: userDataLike,\n imageRecipe,\n vpc = GuVpc.fromIdParameter(scope, AppIdentity.suffixText({ app }, \"VPC\")),\n privateSubnets = GuVpc.subnetsFromParameter(scope, { type: SubnetType.PRIVATE, app }),\n publicSubnets = GuVpc.subnetsFromParameter(scope, { type: SubnetType.PUBLIC, app }),\n instanceMetadataHopLimit,\n updatePolicy,\n defaultInstanceWarmup,\n instanceMetricGranularity,\n waf,\n } = props;\n\n super(scope, app); // The assumption is `app` is unique\n\n // We should really prevent users from doing this via the type system,\n // but that requires a breaking change to the API\n if (applicationLogging.enabled && roleConfiguration.withoutLogShipping) {\n throw new Error(\n \"Application logging has been enabled (via the `applicationLogging` prop) but your `roleConfiguration` sets \" +\n \"`withoutLogShipping` to true. Please turn off application logging or remove `withoutLogShipping`\",\n );\n }\n\n const userData = userDataLike instanceof UserData ? userDataLike : new GuUserData(scope, { ...userDataLike, app });\n\n AppAccess.validate(access);\n\n const certificate =\n typeof certificateProps !== \"undefined\"\n ? new GuCertificate(scope, {\n app,\n domainName: certificateProps.domainName,\n hostedZoneId: certificateProps.hostedZoneId,\n })\n : undefined;\n\n const maybePrivateConfigPolicy =\n userData instanceof GuUserData && userData.configuration\n ? [new GuGetPrivateConfigPolicy(scope, \"GetPrivateConfigFromS3Policy\", userData.configuration)]\n : [];\n\n const mergedRoleConfiguration: GuInstanceRoleProps = {\n withoutLogShipping: roleConfiguration.withoutLogShipping,\n additionalPolicies: maybePrivateConfigPolicy.concat(roleConfiguration.additionalPolicies ?? []),\n };\n\n const autoScalingGroup = new GuAutoScalingGroup(scope, \"AutoScalingGroup\", {\n app,\n vpc,\n instanceType,\n minimumInstances,\n maximumInstances,\n role: new GuInstanceRole(scope, { app, ...mergedRoleConfiguration }),\n\n // TODO should this be defaulted at pattern or construct level?\n healthChecks: HealthChecks.withAdditionalChecks({\n additionalTypes: [AdditionalHealthCheckType.ELB],\n gracePeriod: Duration.minutes(2),\n }),\n\n userData: userData instanceof GuUserData ? userData.userData : userData,\n vpcSubnets: { subnets: privateSubnets },\n ...(blockDevices && { blockDevices }),\n imageRecipe,\n httpPutResponseHopLimit: instanceMetadataHopLimit,\n updatePolicy,\n defaultInstanceWarmup,\n instanceMetricGranularity,\n });\n\n // This allows automatic shipping of instance Cloud Init logs when using the\n // `cdk-base` Amigo role on your AMI.\n Tags.of(autoScalingGroup).add(\n MetadataKeys.LOG_KINESIS_STREAM_NAME,\n GuLoggingStreamNameParameter.getInstance(scope).valueAsString,\n );\n\n if (applicationLogging.enabled) {\n // This allows automatic shipping of application logs when using the\n // `cdk-base` Amigo role on your AMI.\n Tags.of(autoScalingGroup).add(\n MetadataKeys.SYSTEMD_UNIT,\n applicationLogging.systemdUnitName ? `${applicationLogging.systemdUnitName}.service` : `${app}.service`,\n );\n }\n\n const loadBalancer = new GuApplicationLoadBalancer(scope, \"LoadBalancer\", {\n app,\n vpc,\n // Setting internetFacing to true does not necessarily allow public access to the load balancer itself. That is handled by the listener's `open` prop.\n internetFacing: access.scope !== AccessScope.INTERNAL,\n vpcSubnets: {\n subnets: access.scope === AccessScope.INTERNAL ? privateSubnets : publicSubnets,\n },\n withAccessLogging,\n waf,\n });\n\n const targetGroup = new GuApplicationTargetGroup(scope, \"TargetGroup\", {\n app,\n vpc,\n protocol: ApplicationProtocol.HTTP,\n targets: [autoScalingGroup],\n port: applicationPort,\n healthCheck: props.healthcheck,\n });\n\n const listener = new GuHttpsApplicationListener(scope, \"Listener\", {\n app,\n loadBalancer,\n certificate,\n targetGroup,\n // When open=true, AWS will create a security group which allows all inbound traffic over HTTPS\n open: access.scope === AccessScope.PUBLIC && typeof certificate !== \"undefined\",\n });\n\n // Since AWS won't create a security group automatically when open=false, we need to add our own\n if (access.scope !== AccessScope.PUBLIC) {\n loadBalancer.addSecurityGroup(\n new GuSecurityGroup(scope, `${access.scope}IngressSecurityGroup`, {\n app,\n vpc,\n description: \"Allow restricted ingress from CIDR ranges\",\n allowAllOutbound: false,\n ingresses: restrictedCidrRanges(access.cidrRanges),\n }),\n );\n }\n\n if (!monitoringConfiguration.noMonitoring) {\n const { http5xxAlarm, http4xxAlarm, snsTopicName, unhealthyInstancesAlarm } = monitoringConfiguration;\n\n if (http4xxAlarm) {\n new GuAlb4xxPercentageAlarm(scope, {\n app,\n loadBalancer,\n snsTopicName,\n ...http4xxAlarm,\n });\n }\n if (http5xxAlarm) {\n new GuAlb5xxPercentageAlarm(scope, {\n app,\n loadBalancer,\n snsTopicName,\n ...http5xxAlarm,\n });\n }\n if (unhealthyInstancesAlarm) {\n new GuUnhealthyInstancesAlarm(scope, {\n app,\n targetGroup,\n snsTopicName,\n });\n }\n }\n\n if (props.googleAuth?.enabled) {\n const prefix = `/${scope.stage}/${scope.stack}/${app}`;\n\n const {\n allowedGroups = [\"engineering@guardian.co.uk\"],\n sessionTimeoutInMinutes = 15,\n credentialsSecretsManagerPath = `${prefix}/google-auth-credentials`,\n } = props.googleAuth;\n\n if (sessionTimeoutInMinutes > 60) {\n throw new Error(\"googleAuth.sessionTimeoutInMinutes must be <= 60!\");\n }\n\n if (allowedGroups.length < 1) {\n throw new Error(\"googleAuth.allowedGroups cannot be empty!\");\n }\n\n if (allowedGroups.find((group) => !group.endsWith(\"@guardian.co.uk\"))) {\n throw new Error(\"googleAuth.allowedGroups must use the @guardian.co.uk domain.\");\n }\n\n const deployToolsAccountId = StringParameter.fromStringParameterName(\n scope,\n \"deploy-tools-account-id-parameter\",\n NAMED_SSM_PARAMETER_PATHS.DeployToolsAccountId.path,\n );\n\n const cognitoAuthStage = props.googleAuth.cognitoAuthStage ?? \"PROD\";\n\n // See https://github.com/guardian/cognito-auth-lambdas for the source\n // code here. ARN format is:\n // arn:aws:lambda:aws-region:acct-id:function:helloworld.\n const gatekeeperFunctionArn = `arn:aws:lambda:eu-west-1:${deployToolsAccountId.stringValue}:function:deploy-${cognitoAuthStage}-gatekeeper-lambda`;\n\n // Note, handler and filename must match here:\n // https://github.com/guardian/cognito-auth-lambdas.\n const authLambda = new GuLambdaFunction(scope, \"auth-lambda\", {\n app: app,\n memorySize: 128,\n handler: \"bootstrap\",\n runtime: Runtime.PROVIDED_AL2023,\n fileName: `deploy/${cognitoAuthStage}/cognito-lambda/devx-cognito-lambda-amd64-v2.zip`,\n withoutFilePrefix: true,\n withoutArtifactUpload: true,\n bucketNamePath: NAMED_SSM_PARAMETER_PATHS.OrganisationDistributionBucket.path,\n architecture: Architecture.X86_64,\n environment: {\n ALLOWED_GROUPS: allowedGroups.join(\",\"),\n GATEKEEPER_FUNCTION_ARN: gatekeeperFunctionArn,\n },\n });\n\n Tags.of(authLambda).add(\"Owner\", \"DevX\");\n\n authLambda.addToRolePolicy(\n new PolicyStatement({\n effect: Effect.ALLOW,\n actions: [\"lambda:InvokeFunction\"],\n resources: [gatekeeperFunctionArn],\n }),\n );\n\n // Cognito user pool. We require both lambdas: pre-sign-up runs the first\n // time a user attempts to authenticate (before they exist in the User\n // Pool); pre-auth runs in subsequent authentication flows.\n const userPool = new UserPool(this, \"user-pool\", {\n lambdaTriggers: {\n preAuthentication: authLambda,\n preSignUp: authLambda,\n },\n });\n\n // These help ensure domain is deterministic but also unique. Key\n // assumption is that app/stack/stage combo are unique within Guardian.\n const domainPrefix = `com-gu-${app.toLowerCase()}-${scope.stage.toLowerCase()}`;\n\n const userPoolDomain = userPool.addDomain(\"domain\", {\n cognitoDomain: {\n domainPrefix: getUserPoolDomainPrefix(domainPrefix),\n },\n });\n\n const clientId = SecretValue.secretsManager(credentialsSecretsManagerPath, { jsonField: \"clientId\" });\n const clientSecret = SecretValue.secretsManager(credentialsSecretsManagerPath, { jsonField: \"clientSecret\" });\n\n const userPoolIdp = new UserPoolIdentityProviderGoogle(scope, \"google-idp\", {\n userPool: userPool,\n clientId: clientId.toString(),\n clientSecretValue: clientSecret,\n attributeMapping: {\n email: ProviderAttribute.GOOGLE_EMAIL,\n givenName: ProviderAttribute.GOOGLE_GIVEN_NAME,\n familyName: ProviderAttribute.GOOGLE_FAMILY_NAME,\n profilePicture: ProviderAttribute.GOOGLE_PICTURE,\n custom: {\n name: ProviderAttribute.GOOGLE_NAME,\n },\n },\n scopes: [\"openid\", \"email\", \"profile\"],\n });\n\n const userPoolClient = userPool.addClient(\"alb-client\", {\n supportedIdentityProviders: [UserPoolClientIdentityProvider.GOOGLE],\n generateSecret: true,\n oAuth: {\n callbackUrls: [`https://${props.googleAuth.domain}/oauth2/idpresponse`],\n },\n\n // Note: id and access validity token validity cannot be less than one\n // hour (this is the cognito cookie duration). To quickly invalidate\n // credentials, disable the user in Cognito. It might be that we want to\n // parameterise these going forward, but that would require Infosec\n // discussion.\n idTokenValidity: Duration.hours(1),\n accessTokenValidity: Duration.hours(1),\n refreshTokenValidity: Duration.days(7),\n });\n\n userPoolClient.node.addDependency(userPoolIdp);\n\n listener.addAction(\"CognitoAuth\", {\n action: new AuthenticateCognitoAction({\n userPool: userPool,\n userPoolClient: userPoolClient,\n userPoolDomain: userPoolDomain,\n next: ListenerAction.forward([targetGroup]),\n sessionTimeout: Duration.minutes(sessionTimeoutInMinutes),\n }),\n });\n\n // Need to give the ALB outbound access on 443 for the IdP endpoints.\n const idpEgressSecurityGroup = new GuHttpsEgressSecurityGroup(scope, \"ldp-access\", {\n app,\n vpc,\n });\n\n loadBalancer.addSecurityGroup(idpEgressSecurityGroup);\n }\n\n this.vpc = vpc;\n this.certificate = certificate;\n this.loadBalancer = loadBalancer;\n this.autoScalingGroup = autoScalingGroup;\n this.listener = listener;\n this.targetGroup = targetGroup;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"base.js","sourceRoot":"","sources":["../../../src/patterns/ec2-app/base.ts"],"names":[],"mappings":";;;AAAA,uGAAuG;AACvG,6CAA0D;AAE1D,iEAAsF;AACtF,yDAKiC;AAEjC,iDAAqD;AAErD,uFAA6F;AAC7F,uGAA2F;AAC3F,iDAA8D;AAC9D,uDAA+D;AAC/D,iDAAsD;AACtD,2CAAuC;AACvC,+CAAuF;AACvF,8CAAqD;AAErD,8DAA8E;AAE9E,4DAIqC;AAErC,gDAAkF;AAClF,8CAAsG;AAEtG,8CAAgF;AAChF,oDAA2D;AAC3D,kEAIwC;AAExC,uCAAwC;AAGxC,yDAAsE;AA2StE;;GAEG;AACH,SAAgB,oBAAoB,CAAC,MAAe;IAClD,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QAC5B,KAAK;QACL,IAAI,EAAE,cAAI,CAAC,GAAG,CAAC,GAAG,CAAC;QACnB,WAAW,EAAE,iCAAiC,KAAK,CAAC,QAAQ,EAAE;KAC/D,CAAC,CAAC,CAAC;AACN,CAAC;AAND,oDAMC;AAED;;;;;;GAMG;AACH,MAAa,QAAS,SAAQ,sBAAS;IAgBrC,YAAY,KAAc,EAAE,KAAoB;QAC9C,MAAM,EACJ,MAAM,EACN,iBAAiB,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,OAAO,CAAC,CAAC,WAAW,CAAC,CAAC;oBAC3C,cAAc,EAAE,sBAAQ,CAAC,OAAO,CAAC,uBAAuB,CAAC;iBAC1D,CAAC;aACH,CAAC,CAAC;YAEH,qEAAqE;YACrE,MAAM,sBAAsB,GAAG,IAAI,gCAA0B,CAAC,KAAK,EAAE,YAAY,EAAE;gBACjF,GAAG;gBACH,GAAG;aACJ,CAAC,CAAC;YAEH,YAAY,CAAC,gBAAgB,CAAC,sBAAsB,CAAC,CAAC;SACvD;QAED,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,CAAC;QACzC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;CACF;AA7UD,4BA6UC","sourcesContent":["/* eslint \"@guardian/tsdoc-required/tsdoc-required\": 2 -- to begin rolling this out for public APIs. */\nimport { Duration, SecretValue, Tags } from \"aws-cdk-lib\";\nimport type { BlockDevice, UpdatePolicy } from \"aws-cdk-lib/aws-autoscaling\";\nimport { AdditionalHealthCheckType, HealthChecks } from \"aws-cdk-lib/aws-autoscaling\";\nimport {\n ProviderAttribute,\n UserPool,\n UserPoolClientIdentityProvider,\n UserPoolIdentityProviderGoogle,\n} from \"aws-cdk-lib/aws-cognito\";\nimport type { InstanceType, IPeer, ISubnet, IVpc } from \"aws-cdk-lib/aws-ec2\";\nimport { Port, UserData } from \"aws-cdk-lib/aws-ec2\";\nimport type { HealthCheck as ALBHealthCheck } from \"aws-cdk-lib/aws-elasticloadbalancingv2\";\nimport { ApplicationProtocol, ListenerAction } from \"aws-cdk-lib/aws-elasticloadbalancingv2\";\nimport { AuthenticateCognitoAction } from \"aws-cdk-lib/aws-elasticloadbalancingv2-actions\";\nimport { Effect, PolicyStatement } from \"aws-cdk-lib/aws-iam\";\nimport { Architecture, Runtime } from \"aws-cdk-lib/aws-lambda\";\nimport { StringParameter } from \"aws-cdk-lib/aws-ssm\";\nimport { Construct } from \"constructs\";\nimport { AccessScope, MetadataKeys, NAMED_SSM_PARAMETER_PATHS } from \"../../constants\";\nimport { GuCertificate } from \"../../constructs/acm\";\nimport type { GuUserDataProps } from \"../../constructs/autoscaling\";\nimport { GuAutoScalingGroup, GuUserData } from \"../../constructs/autoscaling\";\nimport type { Http4xxAlarmProps, Http5xxAlarmProps, NoMonitoring } from \"../../constructs/cloudwatch\";\nimport {\n GuAlb4xxPercentageAlarm,\n GuAlb5xxPercentageAlarm,\n GuUnhealthyInstancesAlarm,\n} from \"../../constructs/cloudwatch\";\nimport type { GuStack } from \"../../constructs/core\";\nimport { AppIdentity, GuLoggingStreamNameParameter } from \"../../constructs/core\";\nimport { GuHttpsEgressSecurityGroup, GuSecurityGroup, GuVpc, SubnetType } from \"../../constructs/ec2\";\nimport type { GuInstanceRoleProps } from \"../../constructs/iam\";\nimport { GuGetPrivateConfigPolicy, GuInstanceRole } from \"../../constructs/iam\";\nimport { GuLambdaFunction } from \"../../constructs/lambda\";\nimport {\n GuApplicationLoadBalancer,\n GuApplicationTargetGroup,\n GuHttpsApplicationListener,\n} from \"../../constructs/loadbalancing\";\nimport type { WafProps } from \"../../constructs/loadbalancing\";\nimport { AppAccess } from \"../../types\";\nimport type { GuAsgCapacity, GuDomainName } from \"../../types\";\nimport type { AmigoProps } from \"../../types/amigo\";\nimport { getUserPoolDomainPrefix } from \"../../utils/cognito/cognito\";\n\n/**\n * To ship your application logs to ELK automatically, you must:\n *\n * 1. Set the `enabled` flag to true\n * 2. Include the `cdk-base` Amigo role in your AMI\n * 3. Log to `journald`. We recommend doing this by logging to `stdout` and\n * using `systemd` to start your app\n * 4. Confirm that your [[`systemdUnitName`]] is configured properly.\n *\n * Unless you have explicitly opted-out, appropriate IAM permissions for logging\n * to Kinesis will be configured automatically via the [[`GuEc2App`]] pattern.\n */\nexport interface ApplicationLoggingProps {\n /**\n * Enables forwarding of application logs to the Guardian ELK stack.\n *\n * Note, to work, you will need to also do the following non-CDK things:\n *\n * 1. Include the `cdk-base` Amigo role in your AMI.\n * 2. Log to `journald`. We recommend doing this by logging to `stdout` and\n * using `systemd` to start your app\n * 3. Confirm that your [[`systemdUnitName`]] is configured properly.\n *\n * Unless you have explicitly opted-out, appropriate IAM permissions for\n * logging to Kinesis will be configured automatically via the [[`GuEc2App`]]\n * pattern.\n *\n * @see https://github.com/guardian/amigo/tree/main/roles/cdk-base\n */\n enabled: boolean;\n /**\n * This needs to match the name of your SystemD unit.\n *\n * If your systemd unit is not `<app>.service` set this value.\n *\n * @defaultValue `<app>.service`\n */\n systemdUnitName?: string;\n}\n\n/**\n * @privateRemarks we should rename this to AlarmsProps.\n */\nexport interface Alarms {\n /**\n * Name of the target (SNS Topic) for alarm notifications.\n */\n snsTopicName: string;\n /**\n * Enable the 5xx alarm with settings.\n */\n http5xxAlarm: false | Http5xxAlarmProps;\n /**\n * Enable the 4xx alarm with settings.\n */\n http4xxAlarm?: false | Http4xxAlarmProps;\n /**\n * Enable the unhealthy instances alarm.\n */\n unhealthyInstancesAlarm: boolean;\n /**\n * Internal flag - users of this library should ignore this setting.\n */\n noMonitoring?: false;\n}\n\nexport interface GuEc2AppProps extends AppIdentity {\n /**\n * User data for the autoscaling group.\n */\n userData: GuUserDataProps | UserData;\n /**\n * Network access restrictions for your load balancer.\n *\n * Note, this merely provides defence in depth; you should NOT rely on network access restrictions alone for\n * restricting access. Use Google Auth for human access, or a suitable machine auth mechanism.\n */\n access: AppAccess;\n /**\n * The port your application runs on.\n */\n applicationPort: number;\n /**\n * Configure IAM roles for autoscaling group EC2 instances.\n */\n roleConfiguration?: GuInstanceRoleProps;\n /**\n * Enable and configure alarms.\n */\n monitoringConfiguration: Alarms | NoMonitoring;\n /**\n * EC2 instance type. Note, ensure your code is built for the same\n * architecture family (arm64 - 'Graviton' instances - or x64).\n */\n instanceType: InstanceType;\n /**\n * Enable and configures application logs.\n */\n applicationLogging?: ApplicationLoggingProps;\n\n /**\n * Enable access logging for this load balancer.\n * Access logs are written to an S3 bucket within your AWS account.\n * The bucket is created by {@link https://github.com/guardian/aws-account-setup}.\n * The logs are queryable via the `gucdk_access_logs` Athena database.\n *\n * @defaultValue true\n */\n withAccessLogging?: boolean;\n\n /**\n * Add block devices (additional storage).\n */\n blockDevices?: BlockDevice[];\n /**\n * Autoscaling group min and max sizes.\n */\n scaling: GuAsgCapacity;\n /**\n * Specify certificate for the load balancer.\n */\n certificateProps?: GuDomainName;\n\n /**\n * Configure AMIgo image recipe. This is only necessary if you are using GuCDK to generate your riff-raff.yaml file.\n */\n imageRecipe?: string | AmigoProps;\n /**\n * Specify the VPC to use.\n *\n * @see https://github.com/guardian/aws-account-setup\n */\n vpc?: IVpc;\n /**\n * Specify private subnets if using a non-default VPC or (generally\n * discouraged) to limit to a subset of the available subnets.\n */\n privateSubnets?: ISubnet[];\n\n /**\n * Specify private subnets if using a non-default VPC or (generally\n * discouraged) to limit to a subset of the available subnets.\n */\n publicSubnets?: ISubnet[];\n\n /**\n * Configure Google Auth.\n */\n googleAuth?: {\n /**\n * Enables Google Auth (via Cognito). **Additional MANUAL steps required -\n * see below.**\n *\n * Limits access to members of the allowed Google groups.\n *\n * Note, this does not currently support simultaneous machine access, so\n * only set to true if you only require staff access to your service, or are\n * supporting machine access in some other way.\n *\n * MANUAL STEPS: to get this to work, we need a Google Project and\n * associated credentials. Full instructions can be found here:\n *\n * https://docs.google.com/document/d/1_k1FSE52AZHXufWLTiKTI3xy5cGpziyHazSHTKrYfco/edit?usp=sharing\n *\n * DevX hope to automate this process in the near future.\n */\n enabled: true;\n /**\n * The domain users will access your service.\n *\n * Set this to the same as for certificateProps.\n */\n domain: string;\n /**\n * Groups used for membership checks.\n *\n * If specified, cannot be empty. Users must be a member of at least one\n * group to gain access.\n *\n * WARNING: groups must be specified with the `guardian.co.uk` domain, even\n * if that is the non-idiomatic choice for daily use.\n *\n * @defaultValue [`engineering@guardian.co.uk`]\n */\n allowedGroups?: string[];\n /**\n * The number of minutes before the session expires.\n *\n * Set this value to a safe period of time that revoked users\n * sessions will continue to function.\n *\n * NOTE: This value cannot be larger than 60 minutes.\n *\n * @defaultValue 15\n */\n sessionTimeoutInMinutes?: number;\n /**\n * Secrets Manager path containing Google OAuth2 Client credentials.\n *\n * NOTE: you do not need to set this value, but you DO need to generate and\n * store the associated credentials in Secrets Manager.\n *\n * Credentials should be stored in Secrets Manager as JSON:\n *\n * ```json\n * {\n * \"clientId\": \"my-client-id\",\n * \"clientSecret\": \"my-client-secret\"\n * }\n * ```\n *\n * @see `googleAuth.enabled` for how to generate.\n *\n * @defaultValue /:STAGE/:stack/:app/google-auth-credentials\n */\n credentialsSecretsManagerPath?: string;\n\n /**\n * When using Auth in the ALB, which stage of cognito-lambda to use.\n *\n * For most applications this should always be PROD, even in the CODE environments.\n *\n * @defaultValue PROD\n */\n cognitoAuthStage?: string;\n };\n\n /**\n * Specify custom healthcheck\n */\n healthcheck?: ALBHealthCheck;\n\n /**\n * Set http put response hop limit for the launch template.\n * It can be necessary to raise this value from the default of 1\n * for example when sharing the instance profile with a docker container running on the instance.\n */\n instanceMetadataHopLimit?: number;\n\n /**\n * Specify an update policy for the ASG created by this pattern.\n *\n * @see https://docs.aws.amazon.com/cdk/api/latest/docs/aws-autoscaling-readme.html#update-policy\n *\n * @defaultValue UpdatePolicy.none() - Cloudformation does not attempt to rotate instances in the ASG\n * and must rely on riffraff to do so.\n */\n updatePolicy?: UpdatePolicy;\n\n /**\n * You can specify how long after an instance reaches the InService state it waits before contributing\n * usage data to the aggregated metrics. This specified time is called the default instance warmup.\n * This keeps dynamic scaling from being affected by metrics for individual instances that aren't yet\n * handling application traffic and that might be experiencing temporarily high usage of compute resources.\n *\n * @see https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-default-instance-warmup.html\n */\n defaultInstanceWarmup?: Duration;\n\n /**\n * You can specify if the arn of this load balancer should be exposed for protection via WAF\n *\n * If this value changes, it is only picked up on WAF configuration redeploy.\n *\n * NB this parameter setting _alone_ is not sufficient to protect the application.\n * You must also ensure that the application and stage combination is present in the WAF\n * configuration.\n *\n * See https://github.com/guardian/waf/tree/main/lib\n *\n * There is a \"gotcha\" when migrating to this functionality. You may not change only the Logical\n * ID of an SSM Parameter (see https://docs.aws.amazon.com/cdk/v2/guide/identifiers.html) and the\n * parameter name must be of the required form, meaning you cannot have an alternate name.\n *\n * You can either:\n *\n * Remove the old param and immediately redeploy with the new param (this does not affect\n * protection unless and until the WAF configuration is redeployed)\n *\n * OR\n *\n * Create an escape hatch by overriding the logical id (see \"ssm param escape hatch\" test for example)\n **/\n waf?: WafProps;\n\n /**\n * How often to send EC2 metrics, such as CPU usage.\n * By default, AWS will produce `5Minute` granular metrics.\n *\n * It is recommended to produce `1Minute` granular metrics in production,\n * especially when using ASG metrics to trigger horizontal scaling as it allows for earlier scaling.\n *\n * @see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/viewing_metrics_with_cloudwatch.html\n */\n instanceMetricGranularity: \"1Minute\" | \"5Minute\";\n}\n\n/**\n * Use this to allow specific CIDR ranges to access a load balancer over HTTPS\n */\nexport function restrictedCidrRanges(ranges: IPeer[]) {\n return ranges.map((range) => ({\n range,\n port: Port.tcp(443),\n description: `Allow access on port 443 from ${range.uniqueId}`,\n }));\n}\n\n/**\n * Pattern which creates the resources needed to run an application on EC2\n * behind a load balancer. For convenience, you may wish to use [[`GuPlayApp`]]\n * or [[`GuNodeApp`]], which extend this class.\n *\n * See props for further details.\n */\nexport class GuEc2App extends Construct {\n /*\n * These are public for now, as this allows users to\n * modify these constructs as desired to fit their\n * specific needs.\n * In the future, we might build functionality to better enable users\n * to access in-pattern constructs, but this would allow teams to be unblocked\n * in the short term.\n * */\n public readonly vpc: IVpc;\n public readonly certificate?: GuCertificate;\n public readonly loadBalancer: GuApplicationLoadBalancer;\n public readonly autoScalingGroup: GuAutoScalingGroup;\n public readonly listener: GuHttpsApplicationListener;\n public readonly targetGroup: GuApplicationTargetGroup;\n\n constructor(scope: GuStack, props: GuEc2AppProps) {\n const {\n access,\n withAccessLogging = true,\n app,\n // We should update this default once a significant number of apps have migrated to devx-logs\n applicationLogging = { enabled: false },\n applicationPort,\n blockDevices,\n certificateProps,\n instanceType,\n monitoringConfiguration,\n roleConfiguration = { withoutLogShipping: false, additionalPolicies: [] },\n scaling: { minimumInstances, maximumInstances = minimumInstances * 2 },\n userData: userDataLike,\n imageRecipe,\n vpc = GuVpc.fromIdParameter(scope, AppIdentity.suffixText({ app }, \"VPC\")),\n privateSubnets = GuVpc.subnetsFromParameter(scope, { type: SubnetType.PRIVATE, app }),\n publicSubnets = GuVpc.subnetsFromParameter(scope, { type: SubnetType.PUBLIC, app }),\n instanceMetadataHopLimit,\n updatePolicy,\n defaultInstanceWarmup,\n instanceMetricGranularity,\n waf,\n } = props;\n\n super(scope, app); // The assumption is `app` is unique\n\n // We should really prevent users from doing this via the type system,\n // but that requires a breaking change to the API\n if (applicationLogging.enabled && roleConfiguration.withoutLogShipping) {\n throw new Error(\n \"Application logging has been enabled (via the `applicationLogging` prop) but your `roleConfiguration` sets \" +\n \"`withoutLogShipping` to true. Please turn off application logging or remove `withoutLogShipping`\",\n );\n }\n\n const userData = userDataLike instanceof UserData ? userDataLike : new GuUserData(scope, { ...userDataLike, app });\n\n AppAccess.validate(access);\n\n const certificate =\n typeof certificateProps !== \"undefined\"\n ? new GuCertificate(scope, {\n app,\n domainName: certificateProps.domainName,\n hostedZoneId: certificateProps.hostedZoneId,\n })\n : undefined;\n\n const maybePrivateConfigPolicy =\n userData instanceof GuUserData && userData.configuration\n ? [new GuGetPrivateConfigPolicy(scope, \"GetPrivateConfigFromS3Policy\", userData.configuration)]\n : [];\n\n const mergedRoleConfiguration: GuInstanceRoleProps = {\n withoutLogShipping: roleConfiguration.withoutLogShipping,\n additionalPolicies: maybePrivateConfigPolicy.concat(roleConfiguration.additionalPolicies ?? []),\n };\n\n const autoScalingGroup = new GuAutoScalingGroup(scope, \"AutoScalingGroup\", {\n app,\n vpc,\n instanceType,\n minimumInstances,\n maximumInstances,\n role: new GuInstanceRole(scope, { app, ...mergedRoleConfiguration }),\n\n // TODO should this be defaulted at pattern or construct level?\n healthChecks: HealthChecks.withAdditionalChecks({\n additionalTypes: [AdditionalHealthCheckType.ELB],\n gracePeriod: Duration.minutes(2),\n }),\n\n userData: userData instanceof GuUserData ? userData.userData : userData,\n vpcSubnets: { subnets: privateSubnets },\n ...(blockDevices && { blockDevices }),\n imageRecipe,\n httpPutResponseHopLimit: instanceMetadataHopLimit,\n updatePolicy,\n defaultInstanceWarmup,\n instanceMetricGranularity,\n });\n\n // This allows automatic shipping of instance Cloud Init logs when using the\n // `cdk-base` Amigo role on your AMI.\n Tags.of(autoScalingGroup).add(\n MetadataKeys.LOG_KINESIS_STREAM_NAME,\n GuLoggingStreamNameParameter.getInstance(scope).valueAsString,\n );\n\n if (applicationLogging.enabled) {\n // This allows automatic shipping of application logs when using the\n // `cdk-base` Amigo role on your AMI.\n Tags.of(autoScalingGroup).add(\n MetadataKeys.SYSTEMD_UNIT,\n applicationLogging.systemdUnitName ? `${applicationLogging.systemdUnitName}.service` : `${app}.service`,\n );\n }\n\n const loadBalancer = new GuApplicationLoadBalancer(scope, \"LoadBalancer\", {\n app,\n vpc,\n // Setting internetFacing to true does not necessarily allow public access to the load balancer itself. That is handled by the listener's `open` prop.\n internetFacing: access.scope !== AccessScope.INTERNAL,\n vpcSubnets: {\n subnets: access.scope === AccessScope.INTERNAL ? privateSubnets : publicSubnets,\n },\n withAccessLogging,\n waf,\n });\n\n const targetGroup = new GuApplicationTargetGroup(scope, \"TargetGroup\", {\n app,\n vpc,\n protocol: ApplicationProtocol.HTTP,\n targets: [autoScalingGroup],\n port: applicationPort,\n healthCheck: props.healthcheck,\n });\n\n const listener = new GuHttpsApplicationListener(scope, \"Listener\", {\n app,\n loadBalancer,\n certificate,\n targetGroup,\n // When open=true, AWS will create a security group which allows all inbound traffic over HTTPS\n open: access.scope === AccessScope.PUBLIC && typeof certificate !== \"undefined\",\n });\n\n // Since AWS won't create a security group automatically when open=false, we need to add our own\n if (access.scope !== AccessScope.PUBLIC) {\n loadBalancer.addSecurityGroup(\n new GuSecurityGroup(scope, `${access.scope}IngressSecurityGroup`, {\n app,\n vpc,\n description: \"Allow restricted ingress from CIDR ranges\",\n allowAllOutbound: false,\n ingresses: restrictedCidrRanges(access.cidrRanges),\n }),\n );\n }\n\n if (!monitoringConfiguration.noMonitoring) {\n const { http5xxAlarm, http4xxAlarm, snsTopicName, unhealthyInstancesAlarm } = monitoringConfiguration;\n\n if (http4xxAlarm) {\n new GuAlb4xxPercentageAlarm(scope, {\n app,\n loadBalancer,\n snsTopicName,\n ...http4xxAlarm,\n });\n }\n if (http5xxAlarm) {\n new GuAlb5xxPercentageAlarm(scope, {\n app,\n loadBalancer,\n snsTopicName,\n ...http5xxAlarm,\n });\n }\n if (unhealthyInstancesAlarm) {\n new GuUnhealthyInstancesAlarm(scope, {\n app,\n targetGroup,\n snsTopicName,\n });\n }\n }\n\n if (props.googleAuth?.enabled) {\n const prefix = `/${scope.stage}/${scope.stack}/${app}`;\n\n const {\n allowedGroups = [\"engineering@guardian.co.uk\"],\n sessionTimeoutInMinutes = 15,\n credentialsSecretsManagerPath = `${prefix}/google-auth-credentials`,\n } = props.googleAuth;\n\n if (sessionTimeoutInMinutes > 60) {\n throw new Error(\"googleAuth.sessionTimeoutInMinutes must be <= 60!\");\n }\n\n if (allowedGroups.length < 1) {\n throw new Error(\"googleAuth.allowedGroups cannot be empty!\");\n }\n\n if (allowedGroups.find((group) => !group.endsWith(\"@guardian.co.uk\"))) {\n throw new Error(\"googleAuth.allowedGroups must use the @guardian.co.uk domain.\");\n }\n\n const deployToolsAccountId = StringParameter.fromStringParameterName(\n scope,\n \"deploy-tools-account-id-parameter\",\n NAMED_SSM_PARAMETER_PATHS.DeployToolsAccountId.path,\n );\n\n const cognitoAuthStage = props.googleAuth.cognitoAuthStage ?? \"PROD\";\n\n // See https://github.com/guardian/cognito-auth-lambdas for the source\n // code here. ARN format is:\n // arn:aws:lambda:aws-region:acct-id:function:helloworld.\n const gatekeeperFunctionArn = `arn:aws:lambda:eu-west-1:${deployToolsAccountId.stringValue}:function:deploy-${cognitoAuthStage}-gatekeeper-lambda`;\n\n // Note, handler and filename must match here:\n // https://github.com/guardian/cognito-auth-lambdas.\n const authLambda = new GuLambdaFunction(scope, \"auth-lambda\", {\n app: app,\n memorySize: 128,\n handler: \"bootstrap\",\n runtime: Runtime.PROVIDED_AL2023,\n fileName: `deploy/${cognitoAuthStage}/cognito-lambda/devx-cognito-lambda-amd64-v2.zip`,\n withoutFilePrefix: true,\n withoutArtifactUpload: true,\n bucketNamePath: NAMED_SSM_PARAMETER_PATHS.OrganisationDistributionBucket.path,\n architecture: Architecture.X86_64,\n environment: {\n ALLOWED_GROUPS: allowedGroups.join(\",\"),\n GATEKEEPER_FUNCTION_ARN: gatekeeperFunctionArn,\n },\n });\n\n Tags.of(authLambda).add(\"Owner\", \"DevX\");\n\n authLambda.addToRolePolicy(\n new PolicyStatement({\n effect: Effect.ALLOW,\n actions: [\"lambda:InvokeFunction\"],\n resources: [gatekeeperFunctionArn],\n }),\n );\n\n // Cognito user pool. We require both lambdas: pre-sign-up runs the first\n // time a user attempts to authenticate (before they exist in the User\n // Pool); pre-auth runs in subsequent authentication flows.\n const userPool = new UserPool(this, \"user-pool\", {\n lambdaTriggers: {\n preAuthentication: authLambda,\n preSignUp: authLambda,\n },\n });\n\n // These help ensure domain is deterministic but also unique. Key\n // assumption is that app/stack/stage combo are unique within Guardian.\n const domainPrefix = `com-gu-${app.toLowerCase()}-${scope.stage.toLowerCase()}`;\n\n const userPoolDomain = userPool.addDomain(\"domain\", {\n cognitoDomain: {\n domainPrefix: getUserPoolDomainPrefix(domainPrefix),\n },\n });\n\n const clientId = SecretValue.secretsManager(credentialsSecretsManagerPath, { jsonField: \"clientId\" });\n const clientSecret = SecretValue.secretsManager(credentialsSecretsManagerPath, { jsonField: \"clientSecret\" });\n\n const userPoolIdp = new UserPoolIdentityProviderGoogle(scope, \"google-idp\", {\n userPool: userPool,\n clientId: clientId.toString(),\n clientSecretValue: clientSecret,\n attributeMapping: {\n email: ProviderAttribute.GOOGLE_EMAIL,\n givenName: ProviderAttribute.GOOGLE_GIVEN_NAME,\n familyName: ProviderAttribute.GOOGLE_FAMILY_NAME,\n profilePicture: ProviderAttribute.GOOGLE_PICTURE,\n custom: {\n name: ProviderAttribute.GOOGLE_NAME,\n },\n },\n scopes: [\"openid\", \"email\", \"profile\"],\n });\n\n const userPoolClient = userPool.addClient(\"alb-client\", {\n supportedIdentityProviders: [UserPoolClientIdentityProvider.GOOGLE],\n generateSecret: true,\n oAuth: {\n callbackUrls: [`https://${props.googleAuth.domain}/oauth2/idpresponse`],\n },\n\n // Note: id and access validity token validity cannot be less than one\n // hour (this is the cognito cookie duration). To quickly invalidate\n // credentials, disable the user in Cognito. It might be that we want to\n // parameterise these going forward, but that would require Infosec\n // discussion.\n idTokenValidity: Duration.hours(1),\n accessTokenValidity: Duration.hours(1),\n refreshTokenValidity: Duration.days(7),\n });\n\n userPoolClient.node.addDependency(userPoolIdp);\n\n listener.addAction(\"CognitoAuth\", {\n action: new AuthenticateCognitoAction({\n userPool: userPool,\n userPoolClient: userPoolClient,\n userPoolDomain: userPoolDomain,\n next: ListenerAction.forward([targetGroup]),\n sessionTimeout: Duration.minutes(sessionTimeoutInMinutes),\n }),\n });\n\n // Need to give the ALB outbound access on 443 for the IdP endpoints.\n const idpEgressSecurityGroup = new GuHttpsEgressSecurityGroup(scope, \"ldp-access\", {\n app,\n vpc,\n });\n\n loadBalancer.addSecurityGroup(idpEgressSecurityGroup);\n }\n\n this.vpc = vpc;\n this.certificate = certificate;\n this.loadBalancer = loadBalancer;\n this.autoScalingGroup = autoScalingGroup;\n this.listener = listener;\n this.targetGroup = targetGroup;\n }\n}\n"]}
|