Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: AWS API Gateway OpenAPI validators trigger AwsSolutions-APIG2 #1312

Closed
wants to merge 5 commits into from
Closed
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
4 changes: 4 additions & 0 deletions .projen/deps.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions .projenrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const project = new awscdk.AwsCdkConstructLibrary({
description:
'Check CDK v2 applications for best practices using a combination on available rule packs.',
repositoryUrl: 'https://github.com/cdklabs/cdk-nag.git',
deps: ['yaml'],
devDeps: ['@aws-cdk/assert@^2.18'],
publishToPypi: {
distName: 'cdk-nag',
Expand Down
3 changes: 3 additions & 0 deletions package.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

33 changes: 32 additions & 1 deletion src/rules/apigw/APIGWRequestValidation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
import { readFileSync } from 'fs';
import { parse } from 'path';
import { CfnResource, Stack } from 'aws-cdk-lib';
import { CfnResource, Stack, Stage } from 'aws-cdk-lib';
import { CfnRequestValidator, CfnRestApi } from 'aws-cdk-lib/aws-apigateway';
import { parse as yamlparse } from 'yaml';
import { NagRuleCompliance, NagRules } from '../../nag-rules';

/**
Expand All @@ -27,6 +29,35 @@ export default Object.defineProperty(
}
}
}
if (node.bodyS3Location) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't capture the case where a user uses the L1 CfnRestApi directly and uses the Body property

const assetOutdir = NagRules.resolveResourceFromInstrinsic(
node,
Stage.of(node)?.assetOutdir
);
const assetPath = NagRules.resolveResourceFromInstrinsic(
node,
node.getMetadata('aws:asset:path')
);
const specFile = yamlparse(
readFileSync(assetOutdir + '/' + assetPath, 'utf-8')
);
Comment on lines +41 to +43
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should use the official OpenApi Library/Types for processing the spec

if ('x-amazon-apigateway-request-validators' in specFile) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The docs mentions that this can be done on a per method basis as well instead of just globally.

Each method can also override the global config, that needs to be checked as well

for (const prop in specFile[
'x-amazon-apigateway-request-validators'
]) {
if (
specFile['x-amazon-apigateway-request-validators'][prop]
.validateRequestBody &&
specFile['x-amazon-apigateway-request-validators'][prop]
.validateRequestParameters
) {
found = true;
} else {
found = false;
}
}
}
}
if (!found) {
return NagRuleCompliance.NON_COMPLIANT;
}
Expand Down
72 changes: 72 additions & 0 deletions test/rules/APIGW.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,18 @@
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
import { cx_api } from 'aws-cdk-lib';
import {
ApiDefinition,
AuthorizationType,
CfnClientCertificate,
CfnRequestValidator,
CfnRestApi,
CfnStage,
InlineApiDefinition,
MethodLoggingLevel,
RestApi,
SpecRestApi,
} from 'aws-cdk-lib/aws-apigateway';
import { CfnRoute, CfnStage as CfnV2Stage } from 'aws-cdk-lib/aws-apigatewayv2';
import { CfnWebACLAssociation } from 'aws-cdk-lib/aws-wafv2';
Expand Down Expand Up @@ -268,6 +272,62 @@ describe('Amazon API Gateway', () => {
});
validateStack(stack, ruleId, TestType.NON_COMPLIANCE);
});
test('Noncompliance 3', () => {
const apiSpec = new InlineApiDefinition({
openapi: '3.0.2',
paths: {
'/pets': {
get: {
responses: {
200: {
content: {
'application/json': {
schema: {
$ref: '#/components/schemas/Empty',
},
},
},
},
},
'x-amazon-apigateway-integration': {
responses: {
default: {
statusCode: '200',
},
},
requestTemplates: {
'application/json': '{"statusCode": 200}',
},
passthroughBehavior: 'when_no_match',
type: 'mock',
},
},
},
},
components: {
schemas: {
Empty: {
title: 'Empty Schema',
type: 'object',
},
},
},
});
new SpecRestApi(stack, 'SpecRestApi1', { apiDefinition: apiSpec });
validateStack(stack, ruleId, TestType.NON_COMPLIANCE);
});
test('Noncompliance 4', () => {
stack.node.setContext(
cx_api.ASSET_RESOURCE_METADATA_ENABLED_CONTEXT,
true
);
new SpecRestApi(stack, 'SpecRestApi2', {
apiDefinition: ApiDefinition.fromAsset(
'./test/rules/assets/NonCompliantOpenApi.json'
),
});
validateStack(stack, ruleId, TestType.NON_COMPLIANCE);
});
test('Compliance', () => {
const compliantRestApi = new RestApi(stack, 'RestApi');
compliantRestApi.addRequestValidator('RequestValidator', {
Expand All @@ -284,6 +344,18 @@ describe('Amazon API Gateway', () => {
});
validateStack(stack, ruleId, TestType.COMPLIANCE);
});
test('Compliance - API import', () => {
stack.node.setContext(
cx_api.ASSET_RESOURCE_METADATA_ENABLED_CONTEXT,
true
);
new SpecRestApi(stack, 'SpecRestApi', {
apiDefinition: ApiDefinition.fromAsset(
'./test/rules/assets/CompliantOpenApi.json'
),
});
validateStack(stack, ruleId, TestType.COMPLIANCE);
});
});

describe('APIGWSSLEnabled: API Gateway REST API stages are configured with SSL certificates', () => {
Expand Down
162 changes: 162 additions & 0 deletions test/rules/assets/CompliantOpenApi.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
{
"swagger": "2.0",
"info": {
"title": "ReqValidators Sample",
"version": "1.0.0"
},
"schemes": [
"https"
],
"basePath": "/v1",
"produces": [
"application/json"
],
"x-amazon-apigateway-request-validators" : {
"all" : {
"validateRequestBody" : true,
"validateRequestParameters" : true
},
"params-only" : {
"validateRequestBody" : true,
"validateRequestParameters" : true
}
},
"x-amazon-apigateway-request-validator" : "params-only",
"paths": {
"/validation": {
"post": {
"x-amazon-apigateway-request-validator" : "all",
"parameters": [
{
"in": "header",
"name": "h1",
"required": true
},
{
"in": "body",
"name": "RequestBodyModel",
"required": true,
"schema": {
"$ref": "#/definitions/RequestBodyModel"
}
}
],
"responses": {
"200": {
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Error"
}
},
"headers" : {
"test-method-response-header" : {
"type" : "string"
}
}
}
},
"security" : [{
"api_key" : []
}],
"x-amazon-apigateway-auth" : {
"type" : "none"
},
"x-amazon-apigateway-integration" : {
"type" : "http",
"uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets",
"httpMethod" : "POST",
"requestParameters": {
"integration.request.header.custom_h1": "method.request.header.h1"
},
"responses" : {
"2\\d{2}" : {
"statusCode" : "200"
},
"default" : {
"statusCode" : "400",
"responseParameters" : {
"method.response.header.test-method-response-header" : "'static value'"
},
"responseTemplates" : {
"application/json" : "json 400 response template",
"application/xml" : "xml 400 response template"
}
}
}
}
},
"get": {
"parameters": [
{
"name": "q1",
"in": "query",
"required": true
}
],
"responses": {
"200": {
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Error"
}
},
"headers" : {
"test-method-response-header" : {
"type" : "string"
}
}
}
},
"security" : [{
"api_key" : []
}],
"x-amazon-apigateway-auth" : {
"type" : "none"
},
"x-amazon-apigateway-integration" : {
"type" : "http",
"uri" : "http://petstore-demo-endpoint.execute-api.com/petstore/pets",
"httpMethod" : "GET",
"requestParameters": {
"integration.request.querystring.type": "method.request.querystring.q1"
},
"responses" : {
"2\\d{2}" : {
"statusCode" : "200"
},
"default" : {
"statusCode" : "400",
"responseParameters" : {
"method.response.header.test-method-response-header" : "'static value'"
},
"responseTemplates" : {
"application/json" : "json 400 response template",
"application/xml" : "xml 400 response template"
}
}
}
}
}
}
},
"definitions": {
"RequestBodyModel": {
"type": "object",
"properties": {
"id": { "type": "integer" },
"type": { "type": "string", "enum": ["dog", "cat", "fish"] },
"name": { "type": "string" },
"price": { "type": "number", "minimum": 25, "maximum": 500 }
},
"required": ["type", "name", "price"]
},
"Error": {
"type": "object",
"properties": {

}
}
}
}
Loading