Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Fix for code scanning alert no. 512: Insecure randomness (#62852)

Fraser549b72685e47
diff --git a/enterprise/frontend/src/embedding-sdk-package/cli/utils/generate-password.ts b/enterprise/frontend/src/embedding-sdk-package/cli/utils/generate-password.ts
index 466db338e14..4cae3d0ec33 100644
--- a/enterprise/frontend/src/embedding-sdk-package/cli/utils/generate-password.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/cli/utils/generate-password.ts
@@ -1,3 +1,5 @@
+import * as crypto from "crypto";
+
export function generateRandomDemoPassword(): string {
const chars = "abcdefghijklmnopqrstuvwxyz";
const upperCaseChars = chars.toUpperCase();
@@ -20,10 +22,37 @@ export function generateRandomDemoPassword(): string {
return shuffle(password);
}
-const pickRandom = (arr: string) => arr[Math.floor(Math.random() * arr.length)];
+// Get a secure random integer within [0, max) (excluding max)
+function getRandomInt(max: number): number {
+ // crypto.randomBytes returns a Buffer. We can safely pick one byte at a time for moderate sizes.
+ // Note: Avoid modulo bias
+ if (max <= 0) {
+ throw new Error("max must be positive");
+ }
+
+ // Special case: when max is 1, the only value in [0, 1) is 0
+ if (max === 1) {
+ return 0;
+ }
+
+ const byteSize = Math.ceil(Math.log2(max) / 8);
+ const maxNum = Math.pow(256, byteSize);
+ const limit = maxNum - (maxNum % max);
+ let rand: number;
+ do {
+ rand = parseInt(crypto.randomBytes(byteSize).toString("hex"), 16);
+ } while (rand >= limit);
+ return rand % max;
+}
+
+const pickRandom = (arr: string) => arr[getRandomInt(arr.length)];
-const shuffle = (arr: string) =>
- arr
- .split("")
- .sort(() => Math.random() - 0.5)
- .join("");
+// Secure Fisher-Yates shuffle
+const shuffle = (str: string): string => {
+ const arr = str.split("");
+ for (let i = arr.length - 1; i > 0; i--) {
+ const j = getRandomInt(i + 1); // [0, i]
+ [arr[i], arr[j]] = [arr[j], arr[i]];
+ }
+ return arr.join("");
+};