Skip to content

Commit

Permalink
chore: Better randomness (#6755)
Browse files Browse the repository at this point in the history
## About the changes
This change is irrelevant as it doesn't pose a security risk, but
there's no reason for us not to use a different type of random
generation for the `sessionId`

**Note:** the magic number 18 was picked because that's the length of
the string we get from `String(Math.random())`

Closes https://github.com/Unleash/unleash/security/code-scanning/68 and
https://github.com/Unleash/unleash/security/code-scanning/69
  • Loading branch information
gastonfournier committed Apr 2, 2024
1 parent d5b7369 commit e845459
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 7 deletions.
7 changes: 2 additions & 5 deletions src/lib/features/frontend-api/create-context.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
// Copy of https://github.com/Unleash/unleash-proxy/blob/main/src/create-context.ts.

/* eslint-disable prefer-object-spread */
import crypto from 'crypto';
import type { Context } from 'unleash-client';

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export function createContext(value: any): Context {
const {
appName,
Expand Down Expand Up @@ -33,9 +31,8 @@ export function createContext(value: any): Context {
return cleanContext;
}

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export const enrichContextWithIp = (query: any, ip: string): Context => {
query.remoteAddress = query.remoteAddress || ip;
query.sessionId = query.sessionId || String(Math.random());
query.sessionId = query.sessionId || crypto.randomBytes(18).toString('hex');
return createContext(query);
};
7 changes: 5 additions & 2 deletions src/lib/features/frontend-api/frontend-api-service.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import crypto from 'crypto';
import type {
IUnleashConfig,
IUnleashServices,
Expand Down Expand Up @@ -88,7 +89,8 @@ export class FrontendApiService {
): Promise<FrontendApiFeatureSchema[]> {
const client = await this.clientForFrontendApiToken(token);
const definitions = client.getFeatureToggleDefinitions() || [];
const sessionId = context.sessionId || String(Math.random());
const sessionId =
context.sessionId || crypto.randomBytes(18).toString('hex');

const resultDefinitions = definitions
.filter((feature) =>
Expand All @@ -115,7 +117,8 @@ export class FrontendApiService {
): Promise<FrontendApiFeatureSchema[]> {
const client = await this.newClientForFrontendApiToken(token);
const definitions = client.getFeatureToggleDefinitions() || [];
const sessionId = context.sessionId || String(Math.random());
const sessionId =
context.sessionId || crypto.randomBytes(18).toString('hex');

const resultDefinitions = definitions
.filter((feature) => {
Expand Down

0 comments on commit e845459

Please sign in to comment.