Skip to content

Commit 54dd10e

Browse files
committed
Add API Resource Policy
1 parent cdf57b6 commit 54dd10e

File tree

1 file changed

+36
-7
lines changed

1 file changed

+36
-7
lines changed

backend/src/iac/backend-stack.ts

Lines changed: 36 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -352,7 +352,7 @@ export class BackendStack extends cdk.Stack {
352352
);
353353

354354
// Add execution role policy to allow API Gateway to access VPC resources
355-
const executionRole = new iam.Role(this, `${appName}APIGatewayVPCRole-${props.environment}`, {
355+
new iam.Role(this, `${appName}APIGatewayVPCRole-${props.environment}`, {
356356
assumedBy: new iam.ServicePrincipal('apigateway.amazonaws.com'),
357357
managedPolicies: [
358358
iam.ManagedPolicy.fromAwsManagedPolicyName(
@@ -364,21 +364,50 @@ export class BackendStack extends cdk.Stack {
364364
],
365365
});
366366

367-
// Replace the problematic code with a proper way to set the API Gateway policy
368-
const apiPolicy = new iam.PolicyDocument({
367+
const apiResourcePolicy = new iam.PolicyDocument({
369368
statements: [
369+
// Allow all users to access the health endpoint in all stages
370370
new iam.PolicyStatement({
371371
effect: iam.Effect.ALLOW,
372-
principals: [new iam.ServicePrincipal('apigateway.amazonaws.com')],
373-
actions: ['sts:AssumeRole'],
374-
resources: [executionRole.roleArn],
372+
principals: [new iam.AnyPrincipal()],
373+
actions: ['execute-api:Invoke'],
374+
resources: [
375+
`arn:aws:execute-api:${this.region}:${this.account}:${api.restApiId}/*/GET/health`,
376+
],
377+
}),
378+
379+
// Allow only authenticated Cognito users to access all other endpoints
380+
new iam.PolicyStatement({
381+
effect: iam.Effect.ALLOW,
382+
principals: [new iam.AnyPrincipal()],
383+
actions: ['execute-api:Invoke'],
384+
resources: [`arn:aws:execute-api:${this.region}:${this.account}:${api.restApiId}/*/*`],
385+
conditions: {
386+
StringEquals: {
387+
'aws:PrincipalTag/cognito-identity.amazonaws.com:sub':
388+
'${cognito-identity.amazonaws.com:sub}',
389+
},
390+
},
391+
}),
392+
393+
// Deny all non-HTTPS requests
394+
new iam.PolicyStatement({
395+
effect: iam.Effect.DENY,
396+
principals: [new iam.AnyPrincipal()],
397+
actions: ['execute-api:Invoke'],
398+
resources: [`arn:aws:execute-api:${this.region}:${this.account}:${api.restApiId}/*/*`],
399+
conditions: {
400+
Bool: {
401+
'aws:SecureTransport': 'false',
402+
},
403+
},
375404
}),
376405
],
377406
});
378407

379408
// Apply the policy to the API Gateway using CfnRestApi
380409
const cfnApi = api.node.defaultChild as apigateway.CfnRestApi;
381-
cfnApi.policy = apiPolicy.toJSON();
410+
cfnApi.policy = apiResourcePolicy.toJSON();
382411

383412
// Outputs
384413
new cdk.CfnOutput(this, 'ReportsTableName', {

0 commit comments

Comments
 (0)