From 3f8b581af7c0c8146c5b111f92ba6a024310c525 Mon Sep 17 00:00:00 2001 From: Ran Vaknin Date: Wed, 6 Sep 2023 12:52:16 -0700 Subject: [PATCH] fix(s3-presigned-post): ensure unique conditions in policy (#5184) * fix(s3-presigned-post): ensure unique conditions in policy --- .../src/createPresignedPost.ts | 27 ++++++++++++++----- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/packages/s3-presigned-post/src/createPresignedPost.ts b/packages/s3-presigned-post/src/createPresignedPost.ts index bedf4e7f3187..a4abaac439b1 100644 --- a/packages/s3-presigned-post/src/createPresignedPost.ts +++ b/packages/s3-presigned-post/src/createPresignedPost.ts @@ -66,13 +66,26 @@ export const createPresignedPost = async ( // Prepare policies. const expiration = new Date(now.valueOf() + Expires * 1000); - const conditions: PolicyEntry[] = [ - ...Conditions, - ...Object.entries(fields).map(([k, v]) => ({ [k]: v })), - Key.endsWith("${filename}") - ? ["starts-with", "$key", Key.substring(0, Key.lastIndexOf("${filename}"))] - : { key: Key }, - ]; + + const conditionsSet = new Set(); + + for (const condition of Conditions) { + const stringifiedCondition = JSON.stringify(condition); + conditionsSet.add(stringifiedCondition); + } + + for (const [k,v] of Object.entries(fields)) { + conditionsSet.add(JSON.stringify({ [k]: v })) + } + + if (Key.endsWith("${filename}")) { + conditionsSet.add(JSON.stringify(["starts-with", "$key", Key.substring(0, Key.lastIndexOf("${filename}"))])); + } else { + conditionsSet.add(JSON.stringify({ key: Key })); + } + + const conditions = Array.from(conditionsSet).map((item) => JSON.parse(item)); + const encodedPolicy = base64Encoder( utf8Decoder( JSON.stringify({