From a20d5345207cf54cea3f2be6843ad8f179e6d9b0 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Fri, 12 Feb 2021 16:28:44 +0100 Subject: [PATCH] fix(shell-api): make UUID() generate random UUID MONGOSH-593 This aligns mongosh with the legacy shell. --- packages/shell-api/src/shell-bson.spec.ts | 11 ++++------- packages/shell-api/src/shell-bson.ts | 13 ++++++++++--- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/packages/shell-api/src/shell-bson.spec.ts b/packages/shell-api/src/shell-bson.spec.ts index d00b2ffaf4..ddf55f95fd 100644 --- a/packages/shell-api/src/shell-bson.spec.ts +++ b/packages/shell-api/src/shell-bson.spec.ts @@ -391,13 +391,10 @@ describe('Shell BSON', () => { expect(shellBson.UUID('01234567-89ab-cdef-0123-456789abcdef').value()) .to.equal(shellBson.UUID('0123456789abcdef0123456789abcdef').value()); }); - it('errors for missing arg 1', () => { - try { - (shellBson.UUID as any)(); - } catch (e) { - return expect(e.message).to.contain('Missing required argument'); - } - expect.fail('Expecting error, nothing thrown'); + it('generates a random UUID when no arguments are passed', () => { + // https://en.wikipedia.org/wiki/Universally_unique_identifier#Format + expect(shellBson.UUID().value(true).toString('hex')).to.match( + /^[a-z0-9]{12}4[a-z0-9]{3}[89ab][a-z0-9]{15}$/); }); it('errors for wrong type of arg 1', () => { try { diff --git a/packages/shell-api/src/shell-bson.ts b/packages/shell-api/src/shell-bson.ts index 0d23b2d877..2c7d15682c 100644 --- a/packages/shell-api/src/shell-bson.ts +++ b/packages/shell-api/src/shell-bson.ts @@ -3,6 +3,7 @@ import Help from './help'; import { BinaryType, bson as BSON } from '@mongosh/service-provider-core'; import { CommonErrors, MongoshInternalError, MongoshInvalidInputError } from '@mongosh/errors'; import { assertArgsDefined, assertArgsType } from './helpers'; +import { randomBytes } from 'crypto'; function constructHelp(className: string): Help { const classHelpKeyPrefix = `shell-api.classes.${className}.help`; @@ -145,12 +146,18 @@ export default function constructShellBson(bson: typeof BSON): any { const buffer = Buffer.from(hexstr, 'hex'); return new bson.Binary(buffer, subtype); }, - UUID: function(hexstr: string): BinaryType { - assertArgsDefined(hexstr); + UUID: function(hexstr?: string): BinaryType { + if (hexstr === undefined) { + // Generate a version 4, variant 1 UUID, like the old shell did. + const uuid = randomBytes(16); + uuid[6] = (uuid[6] & 0x0f) | 0x40; + uuid[8] = (uuid[8] & 0x3f) | 0x80; + hexstr = uuid.toString('hex'); + } assertArgsType([hexstr], ['string']); // Strip any dashes, as they occur in the standard UUID formatting // (e.g. 01234567-89ab-cdef-0123-456789abcdef). - const buffer = Buffer.from(hexstr.replace(/-/g, ''), 'hex'); + const buffer = Buffer.from((hexstr as string).replace(/-/g, ''), 'hex'); return new bson.Binary(buffer, bson.Binary.SUBTYPE_UUID); }, MD5: function(hexstr: string): BinaryType {