Skip to content

Commit fc5e263

Browse files
committed
fix: do not throw when binary is subtype 4 but invalid uuid
1 parent 305b1af commit fc5e263

File tree

3 files changed

+15
-4
lines changed

3 files changed

+15
-4
lines changed

src/binary.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -438,7 +438,7 @@ export class UUID extends Binary {
438438
* Checks if a value is a valid bson UUID
439439
* @param input - UUID, string or Buffer to validate.
440440
*/
441-
static isValid(input: string | Uint8Array | UUID): boolean {
441+
static isValid(input: string | Uint8Array | UUID | Binary): boolean {
442442
if (!input) {
443443
return false;
444444
}

src/parser/deserializer.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { Binary } from '../binary';
2-
import type { Document } from '../bson';
2+
import { Document, UUID } from '../bson';
33
import { Code } from '../code';
44
import * as constants from '../constants';
55
import { DBRef, DBRefLike, isDBRefLike } from '../db_ref';
@@ -404,7 +404,7 @@ function deserializeObject(
404404
value = ByteUtils.toLocalBufferType(buffer.slice(index, index + binarySize));
405405
} else {
406406
value = new Binary(buffer.slice(index, index + binarySize), subType);
407-
if (subType === constants.BSON_BINARY_SUBTYPE_UUID_NEW) {
407+
if (subType === constants.BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) {
408408
value = value.toUUID();
409409
}
410410
}
@@ -433,7 +433,8 @@ function deserializeObject(
433433
if (promoteBuffers && promoteValues) {
434434
value = _buffer;
435435
} else if (subType === constants.BSON_BINARY_SUBTYPE_UUID_NEW) {
436-
value = new Binary(buffer.slice(index, index + binarySize), subType).toUUID();
436+
const binary = new Binary(buffer.slice(index, index + binarySize), subType);
437+
value = UUID.isValid(binary) ? binary.toUUID() : binary;
437438
} else {
438439
value = new Binary(buffer.slice(index, index + binarySize), subType);
439440
}

test/node/uuid.test.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,16 @@ describe('UUID', () => {
185185
expect(deserializedUUID).to.deep.equal(expectedResult);
186186
});
187187

188+
it('returns Binary when value is subtype 4 but invalid UUID', () => {
189+
const exampleUUID = Binary.createFromHexString('aaaaaaaa', 4);
190+
const serializedUUID = BSON.serialize({ uuid: exampleUUID });
191+
const deserializedUUID = BSON.deserialize(serializedUUID);
192+
const expectedResult = {
193+
uuid: Binary.createFromHexString('aaaaaaaa', 4)
194+
};
195+
expect(deserializedUUID).to.deep.equal(expectedResult);
196+
});
197+
188198
context('when UUID bytes are not in v4 format', () => {
189199
it('returns UUID instance', () => {
190200
const nullUUID = '00'.repeat(16);

0 commit comments

Comments
 (0)