diff --git a/LICENSE b/LICENSE index 0ba95e8..3fc33ae 100644 --- a/LICENSE +++ b/LICENSE @@ -19,3 +19,207 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/README.md b/README.md index 88bd647..17ce07c 100644 --- a/README.md +++ b/README.md @@ -112,7 +112,11 @@ This code is dual licensed under the MIT license and the OGL (Open Government License). Any new work added to this repository must conform to the conditions of these licenses. In particular this means that this project may not depend on GPL-licensed or AGPL-licensed libraries, as these would violate the terms of those -libraries' licenses. +libraries' licenses. + +These files derive from https://github.com/cdklabs/cdk-nag and remain under Apache 2.0 licence +`packages/cdkConstructs/src/nag/rules/APIGWStructuredLogging.ts` +`packages/cdkConstructs/tests/nag/ApiGWStructuredLogging.test.ts` The contents of this repository are protected by Crown Copyright (C). diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..a051536 --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,7 @@ +The following files are licenced under Apache 2.0 and have been copied and modified with minor fixes from https://github.com/cdklabs/cdk-nag. + +`packages/cdkConstructs/src/nag/rules/APIGWStructuredLogging.ts` +`packages/cdkConstructs/tests/nag/ApiGWStructuredLogging.test.ts` + +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: Apache-2.0 diff --git a/packages/cdkConstructs/src/apps/createApp.ts b/packages/cdkConstructs/src/apps/createApp.ts index bf15a2b..cfce045 100644 --- a/packages/cdkConstructs/src/apps/createApp.ts +++ b/packages/cdkConstructs/src/apps/createApp.ts @@ -6,6 +6,7 @@ import { } from "aws-cdk-lib" import {AwsSolutionsChecks} from "cdk-nag" import {getConfigFromEnvVar, getBooleanConfigFromEnvVar} from "../config" +import {EpsNagPack} from "../nag/pack/epsNagPack" export interface StandardStackProps extends StackProps { /** Semantic version of the deployment (from `versionNumber`). */ @@ -71,8 +72,10 @@ export function createApp({ } const app = new App() + app.node.setContext("isPullRequest", isPullRequest) Aspects.of(app).add(new AwsSolutionsChecks({verbose: true})) + Aspects.of(app).add(new EpsNagPack({verbose: true})) Tags.of(app).add("TagVersion", "1") Tags.of(app).add("Programme", "EPS") diff --git a/packages/cdkConstructs/src/index.ts b/packages/cdkConstructs/src/index.ts index d9c09c8..766960c 100644 --- a/packages/cdkConstructs/src/index.ts +++ b/packages/cdkConstructs/src/index.ts @@ -5,3 +5,4 @@ export * from "./apps/createApp.js" export * from "./config/index.js" export * from "./utils/helpers.js" export * from "./stacks/deleteUnusedStacks.js" +export * from "./nag/pack/epsNagPack.js" diff --git a/packages/cdkConstructs/src/nag/pack/epsNagPack.ts b/packages/cdkConstructs/src/nag/pack/epsNagPack.ts new file mode 100644 index 0000000..e6f0661 --- /dev/null +++ b/packages/cdkConstructs/src/nag/pack/epsNagPack.ts @@ -0,0 +1,219 @@ +import {NagMessageLevel, NagPack, NagPackProps} from "cdk-nag" +import {IConstruct} from "constructs" +import {CfnResource} from "aws-cdk-lib" +import {ApiGWMutualTls, APIGWStructuredLogging} from "../rules" +import {LambdaFunctionPublicAccessProhibited} from "cdk-nag/lib/rules/lambda" +import {CloudWatchLogGroupEncrypted} from "cdk-nag/lib/rules/cloudwatch" +import {ALBHttpDropInvalidHeaderEnabled, ELBLoggingEnabled, ELBTlsHttpsListenersOnly} from "cdk-nag/lib/rules/elb" +import {APIGWAccessLogging} from "cdk-nag/lib/rules/apigw" +import { + IAMNoInlinePolicy, + IAMPolicyNoStatementsWithAdminAccess, + IAMPolicyNoStatementsWithFullAccess +} from "cdk-nag/lib/rules/iam" +import {S3BucketPublicReadProhibited, S3BucketPublicWriteProhibited, S3DefaultEncryptionKMS} from "cdk-nag/lib/rules/s3" +import {SecretsManagerUsingKMSKey} from "cdk-nag/lib/rules/secretsmanager" +import {SNSEncryptedKMS} from "cdk-nag/lib/rules/sns" +import {VPCDefaultSecurityGroupClosed, VPCFlowLogsEnabled} from "cdk-nag/lib/rules/vpc" +import {WAFv2LoggingEnabled} from "cdk-nag/lib/rules/waf" + +// Nag pack implementing EPS specific rules +// It implements API gateway must have mutual TLS enabled +// and rules from https://github.com/cdklabs/cdk-nag/blob/main/RULES.md that are not in aws-solutions pack + +export class EpsNagPack extends NagPack { + constructor(props?: NagPackProps) { + super(props) + this.packName = "EpsNagPack" + } + + public visit(node: IConstruct): void { + if (node instanceof CfnResource) { + this.applyRule({ + ruleSuffixOverride: "EPS1", + info: "API Gateway must does not use mutual TLS.", + explanation: "All non pull request deployments must enforce mutual TLS on api gateways.", + level: NagMessageLevel.ERROR, + rule: ApiGWMutualTls, + node: node + }) + this.applyRule({ + ruleSuffixOverride: "EPS2", + info: "The Lambda function permission grants public access.", + explanation: + "Public access allows anyone on the internet to perform unauthenticated actions on the function.", + level: NagMessageLevel.ERROR, + rule: LambdaFunctionPublicAccessProhibited, + node: node + }) + this.applyRule({ + ruleSuffixOverride: "EPS3", + info: "The CloudWatch Log Group is not encrypted with an AWS KMS key.", + explanation: + "To help protect sensitive data at rest, ensure encryption is enabled for your Amazon CloudWatch Log Groups.", + level: NagMessageLevel.ERROR, + rule: CloudWatchLogGroupEncrypted, + node: node + }) + this.applyRule({ + ruleSuffixOverride: "EPS4", + info: "The ALB does not have invalid HTTP header dropping enabled.", + explanation: + "Ensure that your Application Load Balancers (ALB) are configured to drop http headers.", + level: NagMessageLevel.ERROR, + rule: ALBHttpDropInvalidHeaderEnabled, + node: node + }) + this.applyRule({ + ruleSuffixOverride: "EPS5", + info: "The WAFv2 web ACL does not have logging enabled.", + explanation: + // eslint-disable-next-line max-len + "AWS WAF logging provides detailed information about the traffic that is analyzed by your web ACL. The logs record the time that AWS WAF received the request from your AWS resource, information about the request, and an action for the rule that each request matched.", + level: NagMessageLevel.ERROR, + rule: WAFv2LoggingEnabled, + node: node + }) + + this.applyRule({ + ruleSuffixOverride: "EPS6", + info: "The API does not have access logging enabled.", + explanation: + "Enabling access logs helps operators view who accessed an API and how the caller accessed the API.", + level: NagMessageLevel.ERROR, + rule: APIGWAccessLogging, + node: node + }) + this.applyRule({ + ruleSuffixOverride: "EPS7", + info: "The API Gateway logs are not configured for the JSON format.", + explanation: + "JSON Structured logging makes it easier to derive queries to answer questions about your application.", + level: NagMessageLevel.ERROR, + rule: APIGWStructuredLogging, + node: node + }) + this.applyRule({ + ruleSuffixOverride: "EPS8", + info: "The ELB does not have access logs enabled.", + explanation: + "Access logs allow operators to analyze traffic patterns and identify and troubleshoot security issues.", + level: NagMessageLevel.ERROR, + rule: ELBLoggingEnabled, + node: node + }) + this.applyRule({ + ruleSuffixOverride: "EPS9", + info: "The ELB listener is not configured for secure (HTTPs or SSL) protocols for client communication.", + explanation: + // eslint-disable-next-line max-len + "The SSL protocols enable secure communication by encrypting the communication between the client and the load balancer.", + level: NagMessageLevel.ERROR, + rule: ELBTlsHttpsListenersOnly, + node: node + }) + this.applyRule({ + ruleSuffixOverride: "EPS10", + info: "The IAM Group, User, or Role contains an inline policy.", + explanation: + // eslint-disable-next-line max-len + "AWS recommends to use managed policies instead of inline policies. The managed policies allow reusability, versioning and rolling back, and delegating permissions management.", + level: NagMessageLevel.ERROR, + rule: IAMNoInlinePolicy, + node: node + }) + this.applyRule({ + ruleSuffixOverride: "EPS11", + // eslint-disable-next-line max-len + info: "The IAM policy grants admin access, meaning the policy allows a principal to perform all actions on all resources.", + explanation: + // eslint-disable-next-line max-len + 'AWS Identity and Access Management (IAM) can help you incorporate the principles of least privilege and separation of duties with access permissions and authorizations, restricting policies from containing "Effect": "Allow" with "Action": "*" over "Resource": "*". Allowing users to have more privileges than needed to complete a task may violate the principle of least privilege and separation of duties.', + level: NagMessageLevel.ERROR, + rule: IAMPolicyNoStatementsWithAdminAccess, + node: node + }) + this.applyRule({ + ruleSuffixOverride: "EPS12", + // eslint-disable-next-line max-len + info: "The IAM policy grants full access, meaning the policy allows a principal to perform all actions on individual resources.", + explanation: + // eslint-disable-next-line max-len + "Ensure IAM Actions are restricted to only those actions that are needed. Allowing users to have more privileges than needed to complete a task may violate the principle of least privilege and separation of duties.", + level: NagMessageLevel.ERROR, + rule: IAMPolicyNoStatementsWithFullAccess, + node: node + }) + this.applyRule({ + ruleSuffixOverride: "EPS13", + // eslint-disable-next-line max-len + info: "The S3 Bucket does not prohibit public read access through its Block Public Access configurations and bucket ACLs.", + explanation: + "The management of access should be consistent with the classification of the data.", + level: NagMessageLevel.ERROR, + rule: S3BucketPublicReadProhibited, + node: node + }) + this.applyRule({ + ruleSuffixOverride: "EPS14", + // eslint-disable-next-line max-len + info: "The S3 Bucket does not prohibit public write access through its Block Public Access configurations and bucket ACLs.", + explanation: + "The management of access should be consistent with the classification of the data.", + level: NagMessageLevel.ERROR, + rule: S3BucketPublicWriteProhibited, + node: node + }) + this.applyRule({ + ruleSuffixOverride: "EPS15", + info: "The S3 Bucket is not encrypted with a KMS Key by default.", + explanation: + // eslint-disable-next-line max-len + "Ensure that encryption is enabled for your Amazon Simple Storage Service (Amazon S3) buckets. Because sensitive data can exist at rest in an Amazon S3 bucket, enable encryption at rest to help protect that data.", + level: NagMessageLevel.ERROR, + rule: S3DefaultEncryptionKMS, + node: node + }) + this.applyRule({ + ruleSuffixOverride: "EPS16", + info: "The secret is not encrypted with a KMS Customer managed key.", + explanation: + // eslint-disable-next-line max-len + "To help protect data at rest, ensure encryption with AWS Key Management Service (AWS KMS) is enabled for AWS Secrets Manager secrets. Because sensitive data can exist at rest in Secrets Manager secrets, enable encryption at rest to help protect that data.", + level: NagMessageLevel.ERROR, + rule: SecretsManagerUsingKMSKey, + node: node + }) + this.applyRule({ + ruleSuffixOverride: "EPS17", + info: "The SNS topic does not have KMS encryption enabled.", + explanation: + // eslint-disable-next-line max-len + "Because sensitive data can exist at rest in published messages, enable encryption at rest to help protect that data.", + level: NagMessageLevel.ERROR, + rule: SNSEncryptedKMS, + node: node + }) + this.applyRule({ + ruleSuffixOverride: "EPS18", + info: "The VPC's default security group allows inbound or outbound traffic.", + explanation: + // eslint-disable-next-line max-len + "When creating a VPC through CloudFormation, the default security group will always be open. Therefore it is important to always close the default security group after stack creation whenever a VPC is created. Restricting all the traffic on the default security group helps in restricting remote access to your AWS resources.", + level: NagMessageLevel.ERROR, + rule: VPCDefaultSecurityGroupClosed, + node: node + }) + this.applyRule({ + ruleSuffixOverride: "EPS19", + info: "The VPC does not have an associated Flow Log.", + explanation: + // eslint-disable-next-line max-len + "The VPC flow logs provide detailed records for information about the IP traffic going to and from network interfaces in your Amazon Virtual Private Cloud (Amazon VPC). By default, the flow log record includes values for the different components of the IP flow, including the source, destination, and protocol.", + level: NagMessageLevel.ERROR, + rule: VPCFlowLogsEnabled, + node: node + }) + } + } +} diff --git a/packages/cdkConstructs/src/nag/rules/APIGWStructuredLogging.ts b/packages/cdkConstructs/src/nag/rules/APIGWStructuredLogging.ts new file mode 100644 index 0000000..bec59a2 --- /dev/null +++ b/packages/cdkConstructs/src/nag/rules/APIGWStructuredLogging.ts @@ -0,0 +1,73 @@ + +/* +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: Apache-2.0 +Modifications copyright (c) 2026 NHS Digital – see THIRD_PARTY_NOTICES.md +*/ +import {parse} from "node:path" +import {CfnResource, Stack} from "aws-cdk-lib" +import {CfnDeployment, CfnStage} from "aws-cdk-lib/aws-apigateway" +import {CfnStage as CfnStageV2} from "aws-cdk-lib/aws-apigatewayv2" +import {CfnApi, CfnHttpApi} from "aws-cdk-lib/aws-sam" +import {NagRuleCompliance} from "cdk-nag" + +// Copied from https://github.com/cdklabs/cdk-nag/blob/main/src/rules/apigw/APIGWStructuredLogging.ts +// with minor adjustments to handle CfnDeployment access log settings possibly being undefined +// see https://github.com/cdklabs/cdk-nag/issues/2267 +// and https://github.com/cdklabs/cdk-nag/pull/2268 + +const isJSON = (str: string) => { + try { + JSON.parse(str) + // eslint-disable-next-line @typescript-eslint/no-unused-vars + } catch (e) { + return false + } + return true +} + +/** + * API Gateway logs are configured in JSON format. + * @param node the CfnResource to check + */ +export default Object.defineProperty( + (node: CfnResource): NagRuleCompliance => { + if ( + node instanceof CfnApi || + node instanceof CfnHttpApi || + node instanceof CfnStage + ) { + const accessLogSetting = Stack.of(node).resolve(node.accessLogSetting) + if (!accessLogSetting ) { + return NagRuleCompliance.NOT_APPLICABLE + } + if (isJSON(accessLogSetting.format)) { + return NagRuleCompliance.COMPLIANT + } + return NagRuleCompliance.NON_COMPLIANT + } else if (node instanceof CfnDeployment) { + const stageDescription = Stack.of(node).resolve(node.stageDescription) + const accessLogSetting = stageDescription?.accessLogSetting + if (!accessLogSetting) { + return NagRuleCompliance.NOT_APPLICABLE + } + if (isJSON(accessLogSetting.format)) { + return NagRuleCompliance.COMPLIANT + } + return NagRuleCompliance.NON_COMPLIANT + } else if (node instanceof CfnStageV2) { + const accessLogSetting = Stack.of(node).resolve(node.accessLogSettings) + if (!accessLogSetting) { + return NagRuleCompliance.NOT_APPLICABLE + } + if (isJSON(accessLogSetting.format)) { + return NagRuleCompliance.COMPLIANT + } + return NagRuleCompliance.NON_COMPLIANT + } + return NagRuleCompliance.NOT_APPLICABLE + + }, + "name", + {value: parse(__filename).name} +) diff --git a/packages/cdkConstructs/src/nag/rules/ApiGWMutualTls.ts b/packages/cdkConstructs/src/nag/rules/ApiGWMutualTls.ts new file mode 100644 index 0000000..d5a7816 --- /dev/null +++ b/packages/cdkConstructs/src/nag/rules/ApiGWMutualTls.ts @@ -0,0 +1,48 @@ +import {parse} from "node:path" +import {CfnResource, Stack} from "aws-cdk-lib" +import {CfnDomainName} from "aws-cdk-lib/aws-apigateway" +import {NagRules, NagRuleCompliance} from "cdk-nag" +/** + * APIs gateway have mutual TLS enabled unless this is a pull request + * @param node the CfnResource to check + */ +export default Object.defineProperty( + (node: CfnResource): NagRuleCompliance => { + if (node instanceof CfnDomainName) { + const stack = Stack.of(node) + // Try getting isPullRequest context value + const isPullRequest = stack.node.tryGetContext("isPullRequest") === true + + if (isPullRequest) { + return NagRuleCompliance.COMPLIANT + } + + const mutualTls = node.mutualTlsAuthentication + if (mutualTls === undefined) { + return NagRuleCompliance.NON_COMPLIANT + } + + const trustStoreUri = NagRules.resolveIfPrimitive( + node, + (mutualTls as CfnDomainName.MutualTlsAuthenticationProperty) + .truststoreUri + ) + + const trustStoreVersion = NagRules.resolveIfPrimitive( + node, + (mutualTls as CfnDomainName.MutualTlsAuthenticationProperty) + .truststoreVersion + ) + + if (trustStoreUri === undefined || trustStoreVersion === undefined) { + return NagRuleCompliance.NON_COMPLIANT + } + + return NagRuleCompliance.COMPLIANT + } + + return NagRuleCompliance.NOT_APPLICABLE + }, + "name", + {value: parse(__filename).name} +) diff --git a/packages/cdkConstructs/src/nag/rules/index.ts b/packages/cdkConstructs/src/nag/rules/index.ts new file mode 100644 index 0000000..d4b8d67 --- /dev/null +++ b/packages/cdkConstructs/src/nag/rules/index.ts @@ -0,0 +1,2 @@ +export {default as ApiGWMutualTls} from "./ApiGWMutualTls" +export {default as APIGWStructuredLogging} from "./APIGWStructuredLogging" diff --git a/packages/cdkConstructs/tests/nag/ApiGWStructuredLogging.test.ts b/packages/cdkConstructs/tests/nag/ApiGWStructuredLogging.test.ts new file mode 100644 index 0000000..cbf1a63 --- /dev/null +++ b/packages/cdkConstructs/tests/nag/ApiGWStructuredLogging.test.ts @@ -0,0 +1,163 @@ +/* +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +SPDX-License-Identifier: Apache-2.0 +Modifications copyright (c) 2026 NHS Digital – see THIRD_PARTY_NOTICES.md +*/ +import {Aspects, Stack} from "aws-cdk-lib" +import {beforeEach, test} from "vitest" +import {TestPack, TestType, validateStack} from "./utils" +import {APIGWStructuredLogging} from "../../src/nag/rules" +import {describe} from "node:test" +import {CfnDeployment, CfnStage} from "aws-cdk-lib/aws-apigateway" +import {CfnApi, CfnHttpApi} from "aws-cdk-lib/aws-sam" +import {CfnStage as CfnV2Stage} from "aws-cdk-lib/aws-apigatewayv2" + +// Copied from https://github.com/cdklabs/cdk-nag/blob/main/test/rules/APIGW.test.ts +// with minor adjustments to handle CfnDeployment access log settings possibly being undefined +// only copied relevant tests for structured logging +// see https://github.com/cdklabs/cdk-nag/issues/2267 +// and https://github.com/cdklabs/cdk-nag/pull/2268 + +const testPack = new TestPack([ + APIGWStructuredLogging +]) +let stack: Stack +beforeEach(() => { + stack = new Stack() + Aspects.of(stack).add(testPack) +}) + +describe("APIGWStructuredLogging: API Gateway stages use JSON-formatted structured logging", () => { + const ruleId = "APIGWStructuredLogging" + + test("Noncompliance 1: Non-JSON format (CfnStage)", () => { + new CfnStage(stack, "RestApiStageNonJsonFormat", { + restApiId: "foo", + stageName: "prod", + accessLogSetting: { + destinationArn: + "arn:aws:logs:us-east-1:123456789012:log-group:API-Gateway-Execution-Logs_abc123/prod", + format: + // eslint-disable-next-line max-len + '$context.identity.sourceIp $context.identity.caller $context.identity.user [$context.requestTime] "$context.httpMethod $context.resourcePath $context.protocol" $context.status $context.responseLength $context.requestId' + } + }) + validateStack(stack, ruleId, TestType.NON_COMPLIANCE) + }) + + test("Noncompliance 2: No access log settings (CfnDeployment)", () => { + new CfnDeployment(stack, "RestApiDeploymentNoLogs", { + restApiId: "foo", + stageDescription: { + accessLogSetting: { + destinationArn: + "arn:aws:logs:us-east-1:123456789012:log-group:API-Gateway-Execution-Logs_abc123/prod" + } + } + }) + validateStack(stack, ruleId, TestType.NON_COMPLIANCE) + }) + + test("Noncompliance 3: No access log settings (CfnApi)", () => { + new CfnApi(stack, "SamApiNoLogs", { + stageName: "MyApi", + accessLogSetting: { + destinationArn: + "arn:aws:logs:us-east-1:123456789012:log-group:API-Gateway-Execution-Logs_abc123/prod" + } + }) + validateStack(stack, ruleId, TestType.NON_COMPLIANCE) + }) + + test("Noncompliance 4: No access log settings (CfnHttpApi)", () => { + new CfnHttpApi(stack, "SamHttpApiNoLogs", { + stageName: "MyApi", + accessLogSetting: { + destinationArn: + "arn:aws:logs:us-east-1:123456789012:log-group:API-Gateway-Execution-Logs_abc123/prod" + } + }) + validateStack(stack, ruleId, TestType.NON_COMPLIANCE) + }) + + test("Compliance 1: JSON-formatted log (CfnStage)", () => { + new CfnStage(stack, "RestApiStageJsonFormat", { + restApiId: "foo", + stageName: "prod", + accessLogSetting: { + destinationArn: + "arn:aws:logs:us-east-1:123456789012:log-group:API-Gateway-Execution-Logs_abc123/prod", + format: + // eslint-disable-next-line max-len + '{"requestId":"$context.requestId", "ip": "$context.identity.sourceIp", "caller":"$context.identity.caller", "user":"$context.identity.user","requestTime":"$context.requestTime", "httpMethod":"$context.httpMethod","resourcePath":"$context.resourcePath", "status":"$context.status","protocol":"$context.protocol", "responseLength":"$context.responseLength"}' + } + }) + validateStack(stack, ruleId, TestType.COMPLIANCE) + }) + + test("Compliance 2: HTTP API with JSON-formatted log (CfnStageV2)", () => { + new CfnV2Stage(stack, "HttpApiStageJsonFormat", { + apiId: "bar", + stageName: "prod", + accessLogSettings: { + destinationArn: + "arn:aws:logs:us-east-1:123456789012:log-group:API-Gateway-Execution-Logs_abc123/prod", + format: + // eslint-disable-next-line max-len + '{"requestId":"$context.requestId", "ip": "$context.identity.sourceIp", "requestTime":"$context.requestTime", "httpMethod":"$context.httpMethod","routeKey":"$context.routeKey", "status":"$context.status","protocol":"$context.protocol", "responseLength":"$context.responseLength"}' + } + }) + validateStack(stack, ruleId, TestType.COMPLIANCE) + }) + + test("Compliance 3: JSON-formatted log (CfnDeployment)", () => { + new CfnDeployment(stack, "RestApiDeploymentJsonFormat", { + restApiId: "foo", + stageDescription: { + accessLogSetting: { + destinationArn: + "arn:aws:logs:us-east-1:123456789012:log-group:API-Gateway-Execution-Logs_abc123/prod", + format: + // eslint-disable-next-line max-len + '{"requestId":"$context.requestId", "ip": "$context.identity.sourceIp", "caller":"$context.identity.caller", "user":"$context.identity.user","requestTime":"$context.requestTime", "httpMethod":"$context.httpMethod","resourcePath":"$context.resourcePath", "status":"$context.status","protocol":"$context.protocol", "responseLength":"$context.responseLength"}' + } + } + }) + validateStack(stack, ruleId, TestType.COMPLIANCE) + }) + + test("Compliance 4: JSON-formatted log (CfnApi)", () => { + new CfnApi(stack, "SamApiJsonFormat", { + stageName: "MyApi", + accessLogSetting: { + destinationArn: + "arn:aws:logs:us-east-1:123456789012:log-group:API-Gateway-Execution-Logs_abc123/prod", + format: + // eslint-disable-next-line max-len + '{"requestId":"$context.requestId", "ip": "$context.identity.sourceIp", "caller":"$context.identity.caller", "user":"$context.identity.user","requestTime":"$context.requestTime", "httpMethod":"$context.httpMethod","resourcePath":"$context.resourcePath", "status":"$context.status","protocol":"$context.protocol", "responseLength":"$context.responseLength"}' + } + }) + validateStack(stack, ruleId, TestType.COMPLIANCE) + }) + + test("Compliance 5: JSON-formatted log (CfnHttpApi)", () => { + new CfnHttpApi(stack, "SamHttpApiJsonFormat", { + stageName: "MyApi", + accessLogSetting: { + destinationArn: + "arn:aws:logs:us-east-1:123456789012:log-group:API-Gateway-Execution-Logs_abc123/prod", + format: + // eslint-disable-next-line max-len + '{"requestId":"$context.requestId", "ip": "$context.identity.sourceIp", "requestTime":"$context.requestTime", "httpMethod":"$context.httpMethod","routeKey":"$context.routeKey", "status":"$context.status","protocol":"$context.protocol", "responseLength":"$context.responseLength"}' + } + }) + validateStack(stack, ruleId, TestType.COMPLIANCE) + }) + + test("Compliance 6: No stageDescription (CfnDeployment)", () => { + new CfnDeployment(stack, "RestApiDeploymentNoStageDescription", { + restApiId: "foo" + }) + validateStack(stack, ruleId, TestType.COMPLIANCE) + }) +}) diff --git a/packages/cdkConstructs/tests/nag/ApiGatewayMutualTls.test.ts b/packages/cdkConstructs/tests/nag/ApiGatewayMutualTls.test.ts new file mode 100644 index 0000000..2a70a2b --- /dev/null +++ b/packages/cdkConstructs/tests/nag/ApiGatewayMutualTls.test.ts @@ -0,0 +1,70 @@ +import {Aspects, Stack} from "aws-cdk-lib" +import {beforeEach, test} from "vitest" +import {TestPack, TestType, validateStack} from "./utils" +import {ApiGWMutualTls} from "../../src/nag/rules" +import {describe} from "node:test" +import {CfnDomainName} from "aws-cdk-lib/aws-apigateway" + +const testPack = new TestPack([ + ApiGWMutualTls +]) +let stack: Stack +beforeEach(() => { + stack = new Stack() + Aspects.of(stack).add(testPack) +}) + +describe("ApiGWMutualTls", () => { + const ruleId = "ApiGWMutualTls" + test("Non-compliant when mutual TLS is not enabled", () => { + new CfnDomainName(stack, "TestDomain", { + domainName: "test.example.com" + }) + + // Validate + validateStack(stack, ruleId, TestType.NON_COMPLIANCE) + }) + test("Compliant when mutual TLS is enabled", () => { + new CfnDomainName(stack, "TestDomain", { + domainName: "test.example.com", + mutualTlsAuthentication: { + truststoreUri: "truststoreUri", + truststoreVersion: "truststoreVersion" + } + }) + + // Validate + validateStack(stack, ruleId, TestType.COMPLIANCE) + }) + + test("Non-compliant when mutual TLS is missing trustStoreVersion", () => { + new CfnDomainName(stack, "TestDomain", { + domainName: "test.example.com", + mutualTlsAuthentication: { + truststoreUri: "truststoreUri" + } + }) + + // Validate + validateStack(stack, ruleId, TestType.NON_COMPLIANCE) + }) + test("Compliant when mutual TLS is not enabled in a pull request", () => { + stack.node.setContext("isPullRequest", true) + new CfnDomainName(stack, "TestDomain", { + domainName: "test.example.com" + }) + + // Validate + validateStack(stack, ruleId, TestType.COMPLIANCE) + }) + test("Compliant when mutual TLS is not enabled in not a pull request", () => { + stack.node.setContext("isPullRequest", false) + new CfnDomainName(stack, "TestDomain", { + domainName: "test.example.com" + }) + + // Validate + validateStack(stack, ruleId, TestType.NON_COMPLIANCE) + }) + +}) diff --git a/packages/cdkConstructs/tests/nag/epsNagPack.test.ts b/packages/cdkConstructs/tests/nag/epsNagPack.test.ts new file mode 100644 index 0000000..28b716c --- /dev/null +++ b/packages/cdkConstructs/tests/nag/epsNagPack.test.ts @@ -0,0 +1,63 @@ +import { + App, + Aspects, + CfnResource, + Stack +} from "aws-cdk-lib" +import {EpsNagPack} from "../../src/" +import {test, describe, expect} from "vitest" +import {IApplyRule, NagMessageLevel} from "cdk-nag" + +describe("Check NagPack Details", () => { + describe("EPSNagPack", () => { + class EpsNagPackExtended extends EpsNagPack { + actualWarnings = new Array() + actualErrors = new Array() + applyRule(params: IApplyRule): void { + const ruleSuffix = params.ruleSuffixOverride + ? params.ruleSuffixOverride + : params.rule.name + const ruleId = `${pack.readPackName}-${ruleSuffix}` + if (params.level === NagMessageLevel.WARN) { + this.actualWarnings.push(ruleId) + } else { + this.actualErrors.push(ruleId) + } + } + } + const pack = new EpsNagPackExtended() + test("Pack Name is correct", () => { + expect(pack.readPackName).toStrictEqual("EpsNagPack") + }) + test("Pack contains expected warning and error rules", () => { + const expectedWarnings = [] as Array + const expectedErrors = [ + "EpsNagPack-EPS1", + "EpsNagPack-EPS2", + "EpsNagPack-EPS3", + "EpsNagPack-EPS4", + "EpsNagPack-EPS5", + "EpsNagPack-EPS6", + "EpsNagPack-EPS7", + "EpsNagPack-EPS8", + "EpsNagPack-EPS9", + "EpsNagPack-EPS10", + "EpsNagPack-EPS11", + "EpsNagPack-EPS12", + "EpsNagPack-EPS13", + "EpsNagPack-EPS14", + "EpsNagPack-EPS15", + "EpsNagPack-EPS16", + "EpsNagPack-EPS17", + "EpsNagPack-EPS18", + "EpsNagPack-EPS19" + ] + const stack = new Stack() + Aspects.of(stack).add(pack) + new CfnResource(stack, "rTestResource", {type: "foo"}) + App.of(stack)?.synth() + expect(pack.actualWarnings.sort()).toEqual(expectedWarnings.sort()) + expect(pack.actualErrors.sort()).toEqual(expectedErrors.sort()) + }) + }) +}) diff --git a/packages/cdkConstructs/tests/nag/utils.ts b/packages/cdkConstructs/tests/nag/utils.ts new file mode 100644 index 0000000..c44d565 --- /dev/null +++ b/packages/cdkConstructs/tests/nag/utils.ts @@ -0,0 +1,98 @@ + +import {App, CfnResource, Stack} from "aws-cdk-lib" +import {IConstruct} from "constructs" +import { + NagPack, + NagPackProps, + INagSuppressionIgnore, + NagMessageLevel, + NagRuleResult +} from "cdk-nag" +import {expect} from "vitest" + +export enum TestType { + NON_COMPLIANCE, + COMPLIANCE, + VALIDATION_FAILURE, +} +export function validateStack(stack: Stack, ruleId: string, type: TestType) { + expect(ruleId).not.toEqual("") + //const messages = SynthUtils.synthesize(stack).messages + const synthedApp = App.of(stack)?.synth() + const messages = synthedApp?.stacks[0].messages || [] + switch (type) { + case TestType.COMPLIANCE: + expect(messages).not.toContainEqual( + expect.objectContaining({ + entry: expect.objectContaining({ + data: expect.stringMatching(`.*${ruleId}(\\[.*\\])?:`) + }) + }) + ) + noValidationFailure() + break + case TestType.NON_COMPLIANCE: + expect(messages).toContainEqual( + expect.objectContaining({ + entry: expect.objectContaining({ + data: expect.stringContaining(`${ruleId}:`) + }) + }) + ) + noValidationFailure() + break + case TestType.VALIDATION_FAILURE: + expect(messages).toContainEqual( + expect.objectContaining({ + entry: expect.objectContaining({ + data: expect.stringMatching(`.*CdkNagValidationFailure.*${ruleId}`) + }) + }) + ) + break + } + + function noValidationFailure() { + expect(messages).not.toContainEqual( + expect.objectContaining({ + entry: expect.objectContaining({ + data: expect.stringMatching(`.*CdkNagValidationFailure.*${ruleId}`) + }) + }) + ) + } +} + +export class TestPack extends NagPack { + readonly rules: Array<(node: CfnResource) => NagRuleResult> + readonly ruleSuffixOverride?: string + readonly level?: NagMessageLevel + constructor( + rules: Array<(node: CfnResource) => NagRuleResult>, + ignoreSuppressionCondition?: INagSuppressionIgnore, + ruleSuffixOverride?: string, + level?: NagMessageLevel, + props?: NagPackProps + ) { + super(props) + this.packName = "Test" + this.rules = rules + this.packGlobalSuppressionIgnore = ignoreSuppressionCondition + this.ruleSuffixOverride = ruleSuffixOverride + this.level = level + } + public visit(node: IConstruct): void { + if (node instanceof CfnResource) { + this.rules.forEach((rule) => { + this.applyRule({ + ruleSuffixOverride: this.ruleSuffixOverride, + info: "foo.", + explanation: "bar.", + level: this.level ?? NagMessageLevel.ERROR, + rule: rule, + node: node + }) + }) + } + } +}