Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 27 additions & 2 deletions packages/cdkConstructs/src/constructs/RestApiGateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@
readonly logRetentionInDays: number
/** Truststore object key to enable mTLS; leave undefined to disable mTLS or when enableServiceDomain is false. */
readonly mutualTlsTrustStoreKey: string | undefined
/** Required with mutualTlsTrustStoreKey. Service name, used as prefix for trust store key */
readonly serviceName: string | undefined
/** Optional stack UUID. If set, included in the mTLS trust store key prefix to prevent collisions
* when deploying multiple stacks with the same name, avoiding AWS API Gateway mTLS key caching issues. */
readonly trustStoreUuuid: string | undefined
/** Enables creation of a second subscription filter to forward logs to CSOC. */
readonly forwardCsocLogs: boolean
/** Destination ARN used by the optional CSOC subscription filter. */
Expand All @@ -56,6 +61,16 @@
readonly enableServiceDomain?: boolean
}

const getTrustStoreKeyPrefix = (stackName: string,
serviceName: string | undefined,
trustStoreUuuid: string | undefined) => {
if (trustStoreUuuid) {
return `${serviceName}/${stackName}-${trustStoreUuuid}-truststore`
} else {
return `${serviceName}/${stackName}-truststore`
}
}

/** Creates a regional REST API with standard logging, DNS, and optional mTLS/CSOC integration. */
export class RestApiGateway extends Construct {
/** Created API Gateway instance. */
Expand All @@ -69,9 +84,11 @@
* @example
* ```ts
* const api = new RestApiGateway(this, "MyApi", {
* stackName: "my-service",
* stackName: "v1.3",
* logRetentionInDays: 30,
* mutualTlsTrustStoreKey: "truststore.pem",
* serviceName: "my-service",
* trustStoreUuuid: "abc123",
* forwardCsocLogs: true,
* csocApiGatewayDestination: "arn:aws:logs:eu-west-2:123456789012:destination:csoc",
* executionPolicies: [myLambdaInvokePolicy],
Expand All @@ -80,7 +97,7 @@
* api.api.root.addResource("patients")
* ```
*/
public constructor(scope: Construct, id: string, props: RestApiGatewayProps) {

Check failure on line 100 in packages/cdkConstructs/src/constructs/RestApiGateway.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 16 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=NHSDigital_eps-cdk-utils&issues=AZ2Wbx_QPODDo0E6DMnL&open=AZ2Wbx_QPODDo0E6DMnL&pullRequest=669
super(scope, id)

const enableServiceDomain = (props.enableServiceDomain ?? true)
Expand All @@ -93,6 +110,10 @@
throw new Error("mutualTlsTrustStoreKey should not be provided when enableServiceDomain is false")
}

if (props.mutualTlsTrustStoreKey && !props.serviceName) {
throw new Error("serviceName must be provided when mTLS is set")
}

// Imports
const cloudWatchLogsKmsKey = Key.fromKeyArn(
this, "cloudWatchLogsKmsKey", ACCOUNT_RESOURCES.CloudwatchLogsKmsKeyArn)
Expand Down Expand Up @@ -158,7 +179,11 @@
let mtlsConfig: MTLSConfig | undefined

if (enableServiceDomain && props.mutualTlsTrustStoreKey) {
const trustStoreKeyPrefix = `cpt-api/${props.stackName}-truststore`
const trustStoreKeyPrefix = getTrustStoreKeyPrefix(
props.stackName,
props.serviceName,
props.trustStoreUuuid
)
const logGroup = new LogGroup(this, "LambdaLogGroup", {
Comment thread
connoravo-nhs marked this conversation as resolved.
Comment thread
connoravo-nhs marked this conversation as resolved.
encryptionKey: cloudWatchLogsKmsKey,
logGroupName: `/aws/lambda/${props.stackName}-truststore-deployment`,
Expand Down
106 changes: 106 additions & 0 deletions packages/cdkConstructs/tests/constructs/RestApiGateway.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,7 @@
stackName: "test-stack",
logRetentionInDays: 30,
mutualTlsTrustStoreKey: "truststore.pem",
serviceName: "cpt-api",
forwardCsocLogs: false,
csocApiGatewayDestination: "",
executionPolicies: [testPolicy],
Expand Down Expand Up @@ -321,6 +322,12 @@
expect(Object.keys(customResources).length).toBeGreaterThan(0)
})

test("uses serviceName in trust store deployment key prefix", () => {
template.hasResourceProperties("Custom::CDKBucketDeployment", {
DestinationBucketKeyPrefix: "cpt-api/test-stack-truststore"
})
})

test("disables execute-api endpoint when mTLS is enabled", () => {
template.hasResourceProperties("AWS::ApiGateway::RestApi", {
Name: "test-stack-apigw",
Expand All @@ -344,6 +351,80 @@
})
})

describe("RestApiGateway with mTLS and trustStoreUuuid", () => {
test("uses trustStoreUuuid in trust store deployment key prefix", () => {
interface ManagedPolicyResource {
Properties?: {
PolicyDocument?: {
Statement?: Array<{
Action?: Array<string>
Resource?: unknown | Array<unknown>

Check warning on line 361 in packages/cdkConstructs/tests/constructs/RestApiGateway.test.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

'unknown' overrides all other types in this union type.

See more on https://sonarcloud.io/project/issues?id=NHSDigital_eps-cdk-utils&issues=AZ2V5KYZDqE6GPUTPmn2&open=AZ2V5KYZDqE6GPUTPmn2&pullRequest=669
}>
}
}
}

const app = new App()
const stack = new Stack(app, "RestApiGatewayStackWithUuid")

const testPolicy = new ManagedPolicy(stack, "TestPolicy", {
description: "test execution policy",
statements: [
new PolicyStatement({
actions: ["lambda:InvokeFunction"],
resources: ["arn:aws:lambda:eu-west-2:123456789012:function:test-function"]
})
]
})

const apiGateway = new RestApiGateway(stack, "TestApiGateway", {
stackName: "test-stack",
logRetentionInDays: 30,
mutualTlsTrustStoreKey: "truststore.pem",
serviceName: "cpt-api",
trustStoreUuuid: "f47ac10b-58cc-4372-a567-0e02b2c3d479",
forwardCsocLogs: false,
csocApiGatewayDestination: "",
executionPolicies: [testPolicy],
enableServiceDomain: true
})

apiGateway.api.root.addMethod("GET")

const template = Template.fromStack(stack)
template.hasResourceProperties("Custom::CDKBucketDeployment", {
DestinationBucketKeyPrefix: "cpt-api/test-stack-f47ac10b-58cc-4372-a567-0e02b2c3d479-truststore"
})

const policies = template.findResources("AWS::IAM::ManagedPolicy")
const expectedTrustStoreObjectPath =
"cpt-api/test-stack-f47ac10b-58cc-4372-a567-0e02b2c3d479-truststore/truststore.pem"

const hasExpectedTrustStorePath = Object.values(policies).some((policy) => {
const statements = (policy as ManagedPolicyResource).Properties?.PolicyDocument?.Statement ?? []
return statements.some((statement) => {
if (!statement.Action?.includes("s3:PutObject")) {
return false
}

const resources = Array.isArray(statement.Resource)
? statement.Resource
: (statement.Resource ? [statement.Resource] : [])

Check warning on line 412 in packages/cdkConstructs/tests/constructs/RestApiGateway.test.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Extract this nested ternary operation into an independent statement.

See more on https://sonarcloud.io/project/issues?id=NHSDigital_eps-cdk-utils&issues=AZ2V5KYZDqE6GPUTPmn3&open=AZ2V5KYZDqE6GPUTPmn3&pullRequest=669

return resources.some((resource) => {
if (typeof resource === "string") {
return resource.includes(expectedTrustStoreObjectPath)
}

return JSON.stringify(resource).includes(expectedTrustStoreObjectPath)
})
})
})

expect(hasExpectedTrustStorePath).toBe(true)
})
})

describe("RestApiGateway validation errors", () => {
test("throws when forwardCsocLogs is true and csocApiGatewayDestination is empty string", () => {
const app = new App()
Expand Down Expand Up @@ -385,12 +466,37 @@
stackName: "test-stack",
logRetentionInDays: 30,
mutualTlsTrustStoreKey: "truststore.pem",
serviceName: "cpt-api",
forwardCsocLogs: false,
csocApiGatewayDestination: "",
executionPolicies: [testPolicy],
enableServiceDomain: false
})).toThrow("mutualTlsTrustStoreKey should not be provided when enableServiceDomain is false")
})

test("throws when mutualTlsTrustStoreKey is set and serviceName is missing", () => {
const app = new App()
const stack = new Stack(app, "ValidationStack3")
const testPolicy = new ManagedPolicy(stack, "TestPolicy", {
description: "test execution policy",
statements: [
new PolicyStatement({
actions: ["lambda:InvokeFunction"],
resources: ["arn:aws:lambda:eu-west-2:123456789012:function:test-function"]
})
]
})

expect(() => new RestApiGateway(stack, "TestApiGateway", {
stackName: "test-stack",
logRetentionInDays: 30,
mutualTlsTrustStoreKey: "truststore.pem",
forwardCsocLogs: false,
csocApiGatewayDestination: "",
executionPolicies: [testPolicy],
enableServiceDomain: true
})).toThrow("serviceName must be provided when mTLS is set")
})
})

describe("RestApiGateway enableServiceDomain default behaviour", () => {
Expand Down
Loading