aws / aws-cdk

The AWS Cloud Development Kit is a framework for defining cloud infrastructure in code
https://aws.amazon.com/cdk
Apache License 2.0
11.61k stars 3.9k forks source link

aws-apigateway: Removal of wildcard matching from Allowed origins for CORS preflight was a breaking change #28445

Open dlaudams opened 10 months ago

dlaudams commented 10 months ago

Describe the bug

The ability to match origins using regular expressions was removed with this change:

https://github.com/aws/aws-cdk/issues/26623

This causes a breaking change for Core origins relying on that behaviour.

A use case is matching a prefix/wildcard origin, for example, *.example.com -> /https:\/\/.+\.example\.com/

Expected Behavior

The ability to match wildcard origins.

e.g., https://*.example.com

https://github.com/aws/aws-cdk/blob/7264121edb10feca6d4c2bce359138deb62bdf79/packages/aws-cdk-lib/aws-apigateway/lib/resource.ts#L326C1-L326C76

Current Behavior

Only * wildcard or exact origins are allowed.

This prevents prefix matching of origins.

Reproduction Steps

const api = new apigw.RestApi(stack, 'cors-api-test', {
  defaultCorsPreflightOptions: {
    allowOrigins: ['https://*.amazon.com', 'https://twitch.tv'],
  },
});

Produces response template:

#set($origin = $input.params().header.get("Origin"))
#if($origin == "")
  #set($origin = $input.params().header.get("origin"))
#end
#if($origin == "https://*.amazon.com") || $origin == "https://twitch.tv")
  #set($context.responseOverride.header.Access-Control-Allow-Origin = $origin)
#end'

Possible Solution

const condition = origins.map(wildcardPrefixToRegex).map(regex => `$origin.matches("${regex}")`).join(' || ');

...
function wildcardPrefixToRegex(glob) {
// replace '.' with '\.'
// replace '*' with '.+'
}

Produces response template:

#set($origin = $input.params().header.get("Origin"))
#if($origin == "")
  #set($origin = $input.params().header.get("origin"))
#end
#if($origin.matches("https://.+\.amazon\.com") || $origin.matches("https:\/\/twitch\.tv"))
  #set($context.responseOverride.header.Access-Control-Allow-Origin = $origin)
#end'

Additional Information/Context

No response

CDK CLI Version

2.115.0 (build 58027ee)

Framework Version

No response

Node.js Version

v18.14.0.

OS

n/a

Language

TypeScript

Language Version

No response

Other information

No response

pahud commented 10 months ago

We changed its behavior on https://github.com/aws/aws-cdk/pull/26648 because of potential security concern as it was never intended to work as a regex. We need to improve the document on it though.