From fc5e263b5e6a1d055a017f83086c034910d84108 Mon Sep 17 00:00:00 2001 From: Neal Beeken Date: Mon, 24 Apr 2023 10:56:38 -0400 Subject: [PATCH] fix: do not throw when binary is subtype 4 but invalid uuid --- src/binary.ts | 2 +- src/parser/deserializer.ts | 7 ++++--- test/node/uuid.test.ts | 10 ++++++++++ 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/binary.ts b/src/binary.ts index 7749cf05..580f651a 100644 --- a/src/binary.ts +++ b/src/binary.ts @@ -438,7 +438,7 @@ export class UUID extends Binary { * Checks if a value is a valid bson UUID * @param input - UUID, string or Buffer to validate. */ - static isValid(input: string | Uint8Array | UUID): boolean { + static isValid(input: string | Uint8Array | UUID | Binary): boolean { if (!input) { return false; } diff --git a/src/parser/deserializer.ts b/src/parser/deserializer.ts index 50d7a8d8..d533cb87 100644 --- a/src/parser/deserializer.ts +++ b/src/parser/deserializer.ts @@ -1,5 +1,5 @@ import { Binary } from '../binary'; -import type { Document } from '../bson'; +import { Document, UUID } from '../bson'; import { Code } from '../code'; import * as constants from '../constants'; import { DBRef, DBRefLike, isDBRefLike } from '../db_ref'; @@ -404,7 +404,7 @@ function deserializeObject( value = ByteUtils.toLocalBufferType(buffer.slice(index, index + binarySize)); } else { value = new Binary(buffer.slice(index, index + binarySize), subType); - if (subType === constants.BSON_BINARY_SUBTYPE_UUID_NEW) { + if (subType === constants.BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) { value = value.toUUID(); } } @@ -433,7 +433,8 @@ function deserializeObject( if (promoteBuffers && promoteValues) { value = _buffer; } else if (subType === constants.BSON_BINARY_SUBTYPE_UUID_NEW) { - value = new Binary(buffer.slice(index, index + binarySize), subType).toUUID(); + const binary = new Binary(buffer.slice(index, index + binarySize), subType); + value = UUID.isValid(binary) ? binary.toUUID() : binary; } else { value = new Binary(buffer.slice(index, index + binarySize), subType); } diff --git a/test/node/uuid.test.ts b/test/node/uuid.test.ts index 53339123..77d6411b 100644 --- a/test/node/uuid.test.ts +++ b/test/node/uuid.test.ts @@ -185,6 +185,16 @@ describe('UUID', () => { expect(deserializedUUID).to.deep.equal(expectedResult); }); + it('returns Binary when value is subtype 4 but invalid UUID', () => { + const exampleUUID = Binary.createFromHexString('aaaaaaaa', 4); + const serializedUUID = BSON.serialize({ uuid: exampleUUID }); + const deserializedUUID = BSON.deserialize(serializedUUID); + const expectedResult = { + uuid: Binary.createFromHexString('aaaaaaaa', 4) + }; + expect(deserializedUUID).to.deep.equal(expectedResult); + }); + context('when UUID bytes are not in v4 format', () => { it('returns UUID instance', () => { const nullUUID = '00'.repeat(16);