Skip to content

Commit 6322db5

Browse files
authored
fix(shell-api): make UUID() generate random UUID MONGOSH-593 (#654)
This aligns mongosh with the legacy shell.
1 parent b60e94a commit 6322db5

File tree

2 files changed

+14
-10
lines changed

2 files changed

+14
-10
lines changed

packages/shell-api/src/shell-bson.spec.ts

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -391,13 +391,10 @@ describe('Shell BSON', () => {
391391
expect(shellBson.UUID('01234567-89ab-cdef-0123-456789abcdef').value())
392392
.to.equal(shellBson.UUID('0123456789abcdef0123456789abcdef').value());
393393
});
394-
it('errors for missing arg 1', () => {
395-
try {
396-
(shellBson.UUID as any)();
397-
} catch (e) {
398-
return expect(e.message).to.contain('Missing required argument');
399-
}
400-
expect.fail('Expecting error, nothing thrown');
394+
it('generates a random UUID when no arguments are passed', () => {
395+
// https://en.wikipedia.org/wiki/Universally_unique_identifier#Format
396+
expect(shellBson.UUID().value(true).toString('hex')).to.match(
397+
/^[a-z0-9]{12}4[a-z0-9]{3}[89ab][a-z0-9]{15}$/);
401398
});
402399
it('errors for wrong type of arg 1', () => {
403400
try {

packages/shell-api/src/shell-bson.ts

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import Help from './help';
33
import { BinaryType, bson as BSON } from '@mongosh/service-provider-core';
44
import { CommonErrors, MongoshInternalError, MongoshInvalidInputError } from '@mongosh/errors';
55
import { assertArgsDefined, assertArgsType } from './helpers';
6+
import { randomBytes } from 'crypto';
67

78
function constructHelp(className: string): Help {
89
const classHelpKeyPrefix = `shell-api.classes.${className}.help`;
@@ -145,12 +146,18 @@ export default function constructShellBson(bson: typeof BSON): any {
145146
const buffer = Buffer.from(hexstr, 'hex');
146147
return new bson.Binary(buffer, subtype);
147148
},
148-
UUID: function(hexstr: string): BinaryType {
149-
assertArgsDefined(hexstr);
149+
UUID: function(hexstr?: string): BinaryType {
150+
if (hexstr === undefined) {
151+
// Generate a version 4, variant 1 UUID, like the old shell did.
152+
const uuid = randomBytes(16);
153+
uuid[6] = (uuid[6] & 0x0f) | 0x40;
154+
uuid[8] = (uuid[8] & 0x3f) | 0x80;
155+
hexstr = uuid.toString('hex');
156+
}
150157
assertArgsType([hexstr], ['string']);
151158
// Strip any dashes, as they occur in the standard UUID formatting
152159
// (e.g. 01234567-89ab-cdef-0123-456789abcdef).
153-
const buffer = Buffer.from(hexstr.replace(/-/g, ''), 'hex');
160+
const buffer = Buffer.from((hexstr as string).replace(/-/g, ''), 'hex');
154161
return new bson.Binary(buffer, bson.Binary.SUBTYPE_UUID);
155162
},
156163
MD5: function(hexstr: string): BinaryType {

0 commit comments

Comments
 (0)