Skip to content

fix(NODE-4960): UUID validation too strict #572

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Apr 24, 2023
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