Skip to content

Commit

Permalink
fix: do not throw when binary is subtype 4 but invalid uuid
Browse files Browse the repository at this point in the history
  • Loading branch information
nbbeeken committed Apr 24, 2023
1 parent 305b1af commit fc5e263
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 4 deletions.
2 changes: 1 addition & 1 deletion src/binary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
7 changes: 4 additions & 3 deletions src/parser/deserializer.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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();
}
}
Expand Down Expand Up @@ -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);
}
Expand Down
10 changes: 10 additions & 0 deletions test/node/uuid.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit fc5e263

Please sign in to comment.