Skip to content

Commit 7d0f32f

Browse files
authored
chore: address a number of CodeQL errors (#27253)
Reported by GitHub's code quality scanning tool. Many of these are problems with regular expressions. ---- *By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
1 parent ab52bb5 commit 7d0f32f

File tree

15 files changed

+31
-15
lines changed

15 files changed

+31
-15
lines changed

packages/aws-cdk-lib/aws-ec2/lib/cfn-init.ts

+4
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,10 @@ function deepMerge(target?: Record<string, any>, src?: Record<string, any>) {
303303
if (src == null) { return target; }
304304

305305
for (const [key, value] of Object.entries(src)) {
306+
if (key === '__proto__' || key === 'constructor') {
307+
continue;
308+
}
309+
306310
if (Array.isArray(value)) {
307311
if (target[key] && !Array.isArray(target[key])) {
308312
throw new Error(`Trying to merge array [${value}] into a non-array '${target[key]}'`);

packages/aws-cdk-lib/aws-ec2/test/cfn-init.test.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -660,7 +660,7 @@ function dontExpectLine(lines: string[], re: RegExp) {
660660
}
661661

662662
function cmdArg(command: string, argument: string) {
663-
return new RegExp(`${escapeRegex(command)}(\.exe)? .*${escapeRegex(argument)}`);
663+
return new RegExp(`${escapeRegex(command)}(\\.exe)? .*${escapeRegex(argument)}`);
664664
}
665665

666666
function escapeRegex(s: string) {

packages/aws-cdk-lib/aws-ecs/lib/images/repository.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { ContainerImage, ContainerImageConfig } from '../container-image';
88
* Regex pattern to check if it is an ECR image URL.
99
*
1010
*/
11-
const ECR_IMAGE_REGEX = /(^[a-zA-Z0-9][a-zA-Z0-9-_]*).dkr.ecr.([a-zA-Z0-9][a-zA-Z0-9-_]*).amazonaws.com(.cn)?\/.*/;
11+
const ECR_IMAGE_REGEX = /(^[a-zA-Z0-9][a-zA-Z0-9-_]*)\.dkr\.ecr\.([a-zA-Z0-9][a-zA-Z0-9-_]*)\.amazonaws.com(\.cn)?\/.*/;
1212

1313
/**
1414
* The properties for an image hosted in a public or private repository.

packages/aws-cdk-lib/aws-eks/lib/kubectl-handler/helm/__init__.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,8 @@ def helm_handler(event, context):
100100

101101
def get_oci_cmd(repository, version):
102102
# Generates OCI command based on pattern. Public ECR vs Private ECR are treated differently.
103-
private_ecr_pattern = 'oci://(?P<registry>\d+.dkr.ecr.(?P<region>[a-z0-9\-]+).amazonaws.com)*'
104-
public_ecr_pattern = 'oci://(?P<registry>public.ecr.aws)*'
103+
private_ecr_pattern = 'oci://(?P<registry>\d+\.dkr\.ecr\.(?P<region>[a-z0-9\-]+)\.amazonaws\.com)*'
104+
public_ecr_pattern = 'oci://(?P<registry>public\.ecr\.aws)*'
105105

106106
private_registry = re.match(private_ecr_pattern, repository).groupdict()
107107
public_registry = re.match(public_ecr_pattern, repository).groupdict()
@@ -115,7 +115,7 @@ def get_oci_cmd(repository, version):
115115
elif public_registry['registry'] is not None:
116116
logger.info("Found AWS public repository, will use default region as deployment")
117117
region = os.environ.get('AWS_REGION', 'us-east-1')
118-
118+
119119
if is_ecr_public_available(region):
120120
cmnd = [
121121
f"aws ecr-public get-login-password --region us-east-1 | " \
@@ -124,7 +124,7 @@ def get_oci_cmd(repository, version):
124124
else:
125125
# `aws ecr-public get-login-password` and `helm registry login` not required as ecr public is not available in current region
126126
# see https://helm.sh/docs/helm/helm_registry_login/
127-
cmnd = [f"helm pull {repository} --version {version} --untar"]
127+
cmnd = [f"helm pull {repository} --version {version} --untar"]
128128
else:
129129
logger.error("OCI repository format not recognized, falling back to helm pull")
130130
cmnd = [f"helm pull {repository} --version {version} --untar"]
@@ -144,7 +144,7 @@ def get_chart_from_oci(tmpdir, repository = None, version = None):
144144
output = subprocess.check_output(cmnd, stderr=subprocess.STDOUT, cwd=tmpdir, shell=True)
145145
logger.info(output)
146146

147-
# effectively returns "$tmpDir/$lastPartOfOCIUrl", because this is how helm pull saves OCI artifact.
147+
# effectively returns "$tmpDir/$lastPartOfOCIUrl", because this is how helm pull saves OCI artifact.
148148
# Eg. if we have oci://9999999999.dkr.ecr.us-east-1.amazonaws.com/foo/bar/pet-service repository, helm saves artifact under $tmpDir/pet-service
149149
return os.path.join(tmpdir, repository.rpartition('/')[-1])
150150
except subprocess.CalledProcessError as exc:

packages/aws-cdk-lib/aws-events-targets/lib/log-group.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ export class CloudWatchLogGroup implements events.IRuleTarget {
146146
if (typeof(resolvedTemplate) === 'string') {
147147
// need to add the quotes back to the string so that we can parse the json
148148
// '{"timestamp": <time>}' -> '{"timestamp": "<time>"}'
149-
const quotedTemplate = resolvedTemplate.replace(new RegExp('(\<.*?\>)', 'g'), '"$1"');
149+
const quotedTemplate = resolvedTemplate.replace(new RegExp('(<[^<>]*?>)', 'g'), '"$1"');
150150
try {
151151
const inputTemplate = JSON.parse(quotedTemplate);
152152
const inputTemplateKeys = Object.keys(inputTemplate);

packages/aws-cdk-lib/core/lib/cfn-mapping.ts

+4
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,10 @@ export class CfnMapping extends CfnRefElement {
5353
* Sets a value in the map based on the two keys.
5454
*/
5555
public setValue(key1: string, key2: string, value: any) {
56+
if ([key1, key2].some(k => ['__proto__', 'constructor'].includes(k))) {
57+
throw new Error('Cannot use \'__proto__\' or \'constructor\' as keys');
58+
}
59+
5660
this.validateAlphanumeric(key2);
5761

5862
if (!(key1 in this.mapping)) {

packages/aws-cdk-lib/core/lib/cfn-resource.ts

+4
Original file line numberDiff line numberDiff line change
@@ -651,6 +651,10 @@ function deepMerge(target: any, ...sources: any[]) {
651651
}
652652

653653
for (const key of Object.keys(source)) {
654+
if (key === '__proto__' || key === 'constructor') {
655+
continue;
656+
}
657+
654658
const value = source[key];
655659
if (typeof(value) === 'object' && value != null && !Array.isArray(value)) {
656660
// if the value at the target is not an object, override it with an

packages/aws-cdk-lib/core/lib/context-provider.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ function extractProviderError(value: any): string | undefined {
137137
* than that \ is going to lead to quoting hell when the keys are stored in JSON.
138138
*/
139139
function colonQuote(xs: string): string {
140-
return xs.replace('$', '$$').replace(':', '$:');
140+
return xs.replace(/\$/g, '$$').replace(/:/g, '$:');
141141
}
142142

143143
function propsToArray(props: {[key: string]: any}, keyPrefix = ''): string[] {

packages/aws-cdk-lib/core/test/validation/validation.test.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -771,7 +771,7 @@ const validationReport = (data: ValidationReportData[]) => {
771771
expect.stringMatching(new RegExp(`Plugin: ${d.pluginName}`)),
772772
expect.stringMatching(new RegExp(`Version: ${d.version ?? 'N/A'}`)),
773773
expect.stringMatching(new RegExp(`Status: ${d.status}`)),
774-
expect.stringMatching(new RegExp('\(Violations\)')),
774+
expect.stringMatching(new RegExp('\\(Violations\\)')),
775775
title,
776776
...d.severity ? [expect.stringMatching(new RegExp(`Severity: ${d.severity}`))] : [],
777777
expect.stringMatching(new RegExp(' Occurrences:')),

packages/aws-cdk/lib/import.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,7 @@ export class ResourceImporter {
293293
const defaultValue = typeof resourceProps[idProp] ?? '';
294294

295295
const prompt = [
296-
promptPattern.replace(/%/, chalk.blue(idProp)),
296+
promptPattern.replace(/%/g, chalk.blue(idProp)),
297297
defaultValue
298298
? `[${defaultValue}]`
299299
: '(empty to skip)',

packages/aws-cdk/lib/util/objects.ts

+4
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,10 @@ export function deepSet(x: any, path: string[], value: any) {
115115
export function deepMerge(...objects: Array<Obj<any> | undefined>) {
116116
function mergeOne(target: Obj<any>, source: Obj<any>) {
117117
for (const key of Object.keys(source)) {
118+
if (key === '__proto__' || key === 'constructor') {
119+
continue;
120+
}
121+
118122
const value = source[key];
119123

120124
if (isObject(value)) {

packages/aws-cdk/test/commands/migrate.test.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ describe('Migrate Function Tests', () => {
157157

158158
// Replaced stack file is referenced correctly in app file
159159
const app = fs.readFileSync(path.join(workDir, 'GoodJava', 'src', 'main', 'java', 'com', 'myorg', 'GoodJavaApp.java'), 'utf8').split('\n');
160-
expect(app.map(line => line.match('public class GoodJavaApp \{')).filter(line => line).length).toEqual(1);
160+
expect(app.map(line => line.match('public class GoodJavaApp {')).filter(line => line).length).toEqual(1);
161161
expect(app.map(line => line.match(/ new GoodJavaStack\(app, "GoodJava", StackProps.builder()/)).filter(line => line).length).toEqual(1);
162162

163163
// Replaced stack file is correctly generated

packages/cdk-assets/lib/private/shell.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ function hasAnyChars(...chars: string[]): (x: string) => boolean {
107107
*/
108108
function posixEscape(x: string) {
109109
// Turn ' -> '"'"'
110-
x = x.replace("'", "'\"'\"'");
110+
x = x.replace(/'/g, "'\"'\"'");
111111
return `'${x}'`;
112112
}
113113

tools/@aws-cdk/cdk-build-tools/lib/os.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ function hasAnyChars(...chars: string[]): (x: string) => boolean {
107107
*/
108108
function posixEscape(x: string) {
109109
// Turn ' -> '"'"'
110-
x = x.replace("'", "'\"'\"'");
110+
x = x.replace(/'/g, "'\"'\"'");
111111
return `'${x}'`;
112112
}
113113

tools/@aws-cdk/pkglint/lib/rules.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -1857,7 +1857,7 @@ function isIncludedInMonolith(pkg: PackageJson): boolean {
18571857
}
18581858

18591859
function beginEndRegex(label: string) {
1860-
return new RegExp(`(<\!--BEGIN ${label}-->)([\s\S]+)(<\!--END ${label}-->)`, 'm');
1860+
return new RegExp(`(<\!--BEGIN ${label}-->)([\\s\\S]+)(<\!--END ${label}-->)`, 'm');
18611861
}
18621862

18631863
function readIfExists(filename: string): string | undefined {

0 commit comments

Comments
 (0)